π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(feature): convention blocks and pins for the local-feature presets and learned models (#5899)
Dmytro Mishkin3af435c89a78
diff --git a/changelog.d/5899.added.md b/changelog.d/5899.added.mdnew file mode 100644index 000000000..a53a9e8a2--- /dev/null+++ b/changelog.d/5899.added.md@@ -0,0 +1 @@+Document the conventions of the `kornia.feature` local-feature presets and learned models (`LocalFeature`, `SIFTFeature`, `SIFTFeatureScaleSpace`, the AffNet/HardNet/KeyNet presets, `DISK`, `ALIKED`, `XFeat`, `XFeatModel`, `InterpolateSparse2d`, `DeDoDe`, `SOLD2`, `SOLD2_detector` and `DeFMO`) as Convention blocks and pointers: the input range and layout each model reads, the keypoint frame, order and dtype each returns, how DISK's `n` and ALIKED's top-k and threshold modes select keypoints and where that departs from the reference implementations, which dense descriptors are normalised, the padded slots of `LocalFeature` and why they must be dropped before matching, and the known defects of `SIFTFeature`, `ALIKED`, `SOLD2` and `InterpolateSparse2d`.diff --git a/docs/source/feature.local_features.rst b/docs/source/feature.local_features.rstindex 533a77f60..20531dd76 100644--- a/docs/source/feature.local_features.rst+++ b/docs/source/feature.local_features.rst@@ -25,11 +25,9 @@ slots. Use :func:`laf_is_filled` to identify real detections before matching.``rootsift=True`` selects RootSIFT normalization. Use ``descriptor_layout="opencv"``when feeding descriptors to :class:`LightGlueMatcher` with ``"sift"``.-This is an explicit recipe: both feature classes still default to-``descriptor_backend="patch"``. No constructor default or numerical behavior is-changed by this recommendation. Backend performance depends on device, image size,-feature count and batching; the recipe is not a claim that pyramid extraction is-always faster.+Both feature classes default to ``descriptor_backend="patch"``. Backend performance+depends on device, image size, feature count and batching; the recipe is not a claim+that pyramid extraction is always faster... list-table:: SIFT pipeline choices:header-rows: 1@@ -76,7 +74,7 @@ and description; no pyramid is retained between calls. Sampling and Gaussian supdiffer from patch extraction, so descriptors are not numerically interchangeable.For this backend, ``compile_modules`` accepts ``scale_pyr`` and ``subpix`` (or``True`` for both); sparse orientation and description run eagerly. The patch-backend retains the generic detector's compilation options.+backend passes ``compile_modules`` to :class:`ScaleSpaceDetector`.Matching with LightGlue^^^^^^^^^^^^^^^^^^^^^^^@@ -139,7 +137,7 @@ API reference:members: forward, from_pretrained, heatmap_and_dense_descriptors.. autoclass:: XFeat- :members: forward, from_pretrained, detectAndCompute, detectAndComputeDense, match_xfeat, match_xfeat_star+ :members: from_pretrained, detectAndCompute, detectAndComputeDense, match_xfeat, match_xfeat_star.. autoclass:: XFeatModel:members: forwarddiff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 07a6a557e..bf4051558 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -81,6 +81,10 @@ class ALIKEDFeatures:Since ALIKED detects a varying number of keypoints per image,``ALIKEDFeatures`` is not batched.+ Convention:+ The keypoints, descriptors and scores that :class:`~kornia.feature.ALIKED` returns for one image; its+ Convention block gives their frame and how many there are.+Args:keypoints: pixel coordinates ``(N, 2)`` as ``[x, y]``.descriptors: L2-normalised descriptors ``(N, D)``.@@ -762,12 +766,39 @@ class ALIKED(nn.Module):.. image:: _static/img/ALIKED.png+ Convention:+ - ``images`` are RGB in :math:`[0, 1]`, the range of the pretrained weights, and the network applies no+ normalisation; a :math:`(B, 1, H, W)` image is repeated to three channels. Any ``H`` and ``W`` work: the+ image is replicate-padded around its centre to multiples of 32 and the maps are cropped back, so the padding+ does not move the keypoints.+ - :meth:`forward` returns one :class:`ALIKEDFeatures` per image. Its keypoints are sub-pixel ``(x, y)`` in the+ pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`), in the image's dtype: a strict maximum of the+ score map in its ``2 * nms_radius + 1`` window (see the note), at least ``nms_radius`` pixels from the+ border, moved by a soft-argmax over that window. Its score is the score map read bilinearly there, and the+ descriptors are L2-normalised.+ - With ``detection_threshold > 0`` (threshold mode), the maxima strictly above it are kept, at most+ ``max_num_keypoints`` of them, and at most 20000 for a non-positive ``max_num_keypoints``. An image with no+ maximum above the threshold keeps the maxima above its own mean score instead, whatever the rest of the+ batch. With ``detection_threshold <= 0`` and ``max_num_keypoints > 0`` (top-k mode), the+ ``max_num_keypoints`` strongest maxima are kept, or all of them when there are fewer; with both ``<= 0``,+ the maxima above the image's mean score.+ - ``image_size`` holds the valid ``(W, H)`` of each image of a batch padded at the bottom and right to a+ common size: maxima closer than ``nms_radius`` pixels to that image's last valid row or column are dropped.+ - :meth:`forward_laf` returns padded tensors like :class:`~kornia.feature.LocalFeature`, but ``N`` is the+ largest keypoint count in the batch and the responses are :math:`(B, N, 1)`. Its ``mask`` multiplies the+ score map, and it takes no ``image_size``.+ - Known defects: on CPU, float16 and bfloat16 score and feature maps go to torch's ``grid_sample`` without+ an upcast: the half-precision kernel can return wrong values, NaN or overflow, and where torch has none the+ call raises (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).+Args:model_name: backbone configuration, one of``'aliked-t16'``, ``'aliked-n16'``, ``'aliked-n16rot'``, ``'aliked-n32'``.- max_num_keypoints: maximum number of keypoints to detect.- ``-1`` means no limit (threshold-based mode).- detection_threshold: minimum detection score in threshold mode.+ max_num_keypoints: the keypoint budget, a cap on the number of maxima kept in threshold mode and in top-k+ mode; see the Convention block.+ detection_threshold: a positive value selects threshold mode and is the score a maximum must exceed; zero or+ a negative value selects top-k mode when ``max_num_keypoints`` is positive. See the Convention block.nms_radius: NMS radius (kernel size ``= 2 * nms_radius + 1``). The suppression keeps strict local maximaonly; see the note below.@@ -777,10 +808,15 @@ class ALIKED(nn.Module):departs on purpose from the reference implementations (Shiaoming/ALIKED and LightGlue's port). Their``simple_nms`` also keeps tied maxima, and in two further rounds it adds the positions that become themaximum of their window once the windows around the maxima already kept are zeroed. Those positions lie on- the flank of a stronger peak and are not local maxima of the score map. kornia therefore returns a subset- of the reference keypoints. With the pretrained ``aliked-n16`` it returns 1363 of the reference's 1514 on- Oxford graf img1, and each of the 151 left out has a higher score in its window. The single pass is also- faster on CPU than the reference's three rounds.+ the flank of a stronger peak and are not local maxima of the score map. In threshold mode, when neither the+ keypoint budget nor the fallback below decides the count, kornia therefore returns a subset of the reference+ keypoints: with the pretrained ``aliked-n16`` and the default threshold it returns up to 10 % fewer keypoints+ than the reference on the Oxford img1 images, and each one left out has a higher score in its window.+ Otherwise the two keypoint sets need not be nested, because the reference ranks those extra positions with+ the maxima: in top-k mode, where it also fills ``top_k`` slots with positions that are not maxima when the+ score map has fewer maxima, and when the budget cuts the count in threshold mode. The reference falls back to+ the mean score only when no image of the batch has a maximum above the threshold; kornia returns maxima only+ and decides the fallback for each image, so an image's keypoints do not depend on the rest of the batch.Example:>>> aliked = ALIKED.from_pretrained('aliked-n16') # doctest: +SKIP@@ -949,9 +985,8 @@ class ALIKED(nn.Module):covariance, so the axes of the frame are its principal axes, and``det A > 0`` (the frame is never mirrored). The frame describes howsharply the score map peaks, not an image structure. Its scale- (:func:`~kornia.feature.get_laf_scale`) is about a pixel or less: 0.14- to 1.25 px, median 0.62 px, on Oxford graf img1 with the pretrained- ``aliked-n16``. That is much smaller than the region the descriptor+ (:func:`~kornia.feature.get_laf_scale`) is about a pixel or less with+ the pretrained ``aliked-n16``. That is much smaller than the region the descriptorsamples, so rescale the frames, for example with:func:`~kornia.feature.scale_laf`, before using them as a region size.diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex 6139747aa..59fef5319 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -81,9 +81,18 @@ class DeDoDe(nn.Module):See :cite:`edstedt2024dedode` for details.- .. note:: :meth:`forward`, :meth:`detect` and :meth:`describe` take RGB images in the range :math:`[0, 1]` and- apply the ImageNet normalization themselves; pass ``apply_imagenet_normalization=False`` for images that are- already normalized.+ Convention:+ - :meth:`forward`, :meth:`detect` and :meth:`describe` take RGB images in the range :math:`[0, 1]` and apply+ the ImageNet normalization themselves; pass ``apply_imagenet_normalization=False`` for images that are+ already normalized. ``pad_if_not_divisible`` zero-pads the normalized image at the bottom and right to+ multiples of 14, so the padding is the ImageNet mean colour, and removes it from the maps again.+ - :meth:`forward` returns pixel ``i`` as ``i + 0.5``: subtract 0.5 for the pixel frame of+ :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).+ :meth:`detect` returns it normalized, as ``(2 i + 1) / (W, H) - 1`` in :math:`[-1, 1]`+ (``align_corners=False``), the form :meth:`describe` takes; ``(k + 1) * (W, H) / 2 - 0.5`` converts such a+ ``k`` to kornia's frame. A description is read at the centre of pixel ``i``.+ - Each image gives its ``n`` best keypoints by score, in descending order: :math:`N = \min(n, H W)`, with no+ threshold and no padding. Keypoints and descriptions are float32, and descriptions are not normalized.Args:detector_model: The detector model kind. Available options are: `L`.@@ -154,7 +163,7 @@ class DeDoDe(nn.Module):scores: A torch.Tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.descriptions: A torch.Tensor of shape :math:`(B, N, DIM)` containing the descriptions- of the detected keypoints. DIM is 256 for B and 512 for G.+ of the detected keypoints. DIM is 256 for both B and G."""_B, _C, H, W = images.shapediff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex 33e9ab39f..828a55abf 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -375,6 +375,13 @@ class DeFMO(nn.Module):This is based on the original code from paper "DeFMO: Deblurring and Shape Recoveryof Fast Moving Objects". See :cite:`DeFMO2021` for more details.+ Convention:+ - The input is :math:`(B, 6, H, W)`: the RGB channels of the blurred image, then those of the background+ estimate, in :math:`[0, 1]` for the pretrained weights. ``H`` and ``W`` that are multiples of 16 give an+ output of the same size; other sizes give an output rounded up to the next multiples of 16.+ - The output is :math:`(B, 24, 4, H, W)`: 24 sub-frames in time order, sub-frame ``k`` rendered at the time+ ``k / 23``, each with red, green, blue and alpha channels in :math:`[0, 1]` after a sigmoid.+Args:pretrained: Download and set pretrained weights to the model. Default: false.@@ -382,7 +389,7 @@ class DeFMO(nn.Module):Temporal super-resolution without background.Shape:- Input: (B, 6, H, W)- - Output: (B, S, 4, H, W)+ - Output: (B, S, 4, H, W), with H and W rounded up to multiples of 16Examples:>>> import korniadiff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex b595013c1..e07b650e5 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -42,12 +42,33 @@ urls: dict[str, list[str]] = {class DISK(nn.Module):- r"""nn.Module which detects and described local features in an image using the DISK method.+ r"""nn.Module which detects and describes local features in an image using the DISK method.See :cite:`tyszkiewicz2020disk` for details... image:: _static/img/disk_outdoor_depth.jpg+ Convention:+ - ``images`` are RGB, :math:`(B, 3, H, W)`, which the U-Net sees as given, without normalisation. With the+ default U-Net, a common positive gain of the input, such as :math:`[0, 255]` instead of :math:`[0, 1]`,+ changes the outputs only through the instance norms' ``eps``, which weighs more the lower the image's+ contrast. At ordinary contrast the maps barely change, though a keypoint can still swap where scores nearly+ tie or at the ``n`` cut; at low contrast the keypoints and descriptors change substantially. With the+ ``depth`` weights and ``n=2048``, the :math:`[0, 1]` and :math:`[0, 255]` versions of Oxford graf, wall and+ bark ``img1`` differ in 0 to 2 keypoints, in 2 to 6 % of them with the intensities multiplied by 0.1, and+ in about 30 % multiplied by 0.01. ``H`` and ``W`` must be multiples of 16, unless+ ``pad_if_not_divisible=True`` zero-pads the bottom and right, in which case the maps are cropped back to the+ image before the suppression and no keypoint lies in the padding.+ - Each image gives a :class:`DISKFeatures`. Keypoints are the integer ``(x, y)`` pixels of the strict heatmap+ maxima (see the note), in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`), listed in raster order (row by row, then column+ by column) rather than by score, in the dtype of the network's output. ``detection_scores`` are the+ heatmap values there, and each descriptor is the dense descriptor at the keypoint's pixel, L2-normalised;+ :meth:`heatmap_and_dense_descriptors` returns the dense descriptors without normalisation.+ - ``score_threshold`` keeps the scores strictly above it. ``n`` is an upper bound on the maxima above+ ``score_threshold`` in each image; the ``n`` argument of :meth:`forward` says which of them are kept when+ there are more.+Args:desc_dim: The dimension of the descriptor.unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK@@ -64,7 +85,10 @@ class DISK(nn.Module):clips the window at the border, so it judges a border position against part of its window. Of several equalmaxima it keeps the one the max-pool reports first, which depends on an order PyTorch does not specify. Withthe pretrained ``depth`` weights on Oxford graf and boat img1, every keypoint of the reference that kornia- leaves out lies in that border strip.+ leaves out lies in that border strip. The reference's ``n`` keeps the scores strictly above the+ ``(n + 1)``-th largest, which drops the weakest maximum, with every maximum tied with it, of an image with+ ``n`` maxima or fewer, and every maximum tied across the cut. kornia's ``n`` is an upper bound, so such an+ image keeps every maximum, and a tie at the cut is filled in raster order.Example:>>> disk = DISK.from_pretrained('depth')@@ -124,9 +148,10 @@ class DISK(nn.Module):image with ``n`` such maxima or fewer keeps all of them; with more, its ``n`` strongest, where maximatied at the ``n``-th score are taken in raster order. If None, all keypoints are returned.window_size: The size of the non-maxima suppression window used to filter detections.- score_threshold: The minimum score a detection must have to be returned.+ score_threshold: Detections must score strictly above it to be returned.See :py:class:`DISKFeatures` for details.- pad_if_not_divisible: if True, the non-16 divisible input is zero-padded to the closest 16-multiply+ pad_if_not_divisible: if True, an input whose height or width is not a multiple of 16 is zero-padded at+ the bottom and right to the next multiple of 16.Returns:A list of length :math:`B` containing the detected features.diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.pyindex 70cff4805..62bd3f1c9 100644--- a/kornia/feature/disk/structs.py+++ b/kornia/feature/disk/structs.py@@ -30,12 +30,15 @@ class DISKFeatures:Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched.+ Convention:+ The keypoints, scores and descriptors that :class:`~kornia.feature.DISK` returns for one image; its+ Convention block gives their frame and order.+Args:keypoints: torch.Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints.descriptors: torch.Tensor of shape :math:`(N, D)`, where :math:`D` is the descriptor dimension.- detection_scores: torch.Tensor of shape :math:`(N,)` where the detection score can be interpreted as- the log-probability of keeping a keypoint after it has been proposed (see the paper- section *Method β Feature distribution* for details).+ detection_scores: torch.Tensor of shape :math:`(N,)`, the detection heatmap value at each keypoint: a raw+ logit of the network, not a log-probability."""@@ -54,10 +57,10 @@ class DISKFeatures:@propertydef device(self) -> Union[str, torch.device, None]:- """Return the device of the stored tensors or module parameters.+ """Return the device of the stored tensors.Returns:- Device used by the model parameters.+ Device of the keypoints."""return self.keypoints.devicediff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 87ac4e462..6b748d4e4 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -248,11 +248,35 @@ class LAFDescriptor(nn.Module):class LocalFeature(nn.Module):"""nn.Module, which combines local feature detector and descriptor.+ Convention:+ - ``forward`` runs the detector, multiplies the shape ``A`` of every LAF by ``scaling_coef``+ (:func:`~kornia.feature.scale_laf`) and describes the scaled LAFs. It returns ``(lafs, responses, descs)``+ with shapes :math:`(B, N, 2, 3)`, :math:`(B, N)` and :math:`(B, N, D)`: the scaled LAFs, in the frame of+ :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`),+ the detector's responses and one descriptor per LAF. ``scaling_coef`` leaves the centres and the responses+ unchanged.+ - ``N`` comes from the detector. The detectors of every preset (:class:`~kornia.feature.ScaleSpaceDetector`,+ :class:`~kornia.feature.MultiResolutionDetector`, :class:`~kornia.feature.KeyNetDetector` and the dedicated+ detector of ``SIFTFeatureScaleSpace(descriptor_backend="pyramid")``) return ``num_features`` slots for every+ image, not the largest count in the batch.+ - A slot that the detector did not fill holds a zero LAF and a zero response, and all such slots of an image+ share one descriptor: with :class:`~kornia.feature.LAFDescriptor`, that of a patch sampled at the origin.+ :class:`LocalFeatureMatcher` drops these slots before matching. Drop them yourself before any other+ matcher, including :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_mnn`,+ :func:`~kornia.feature.match_fginn`, :func:`~kornia.feature.match_adalam` and+ :class:`~kornia.feature.LightGlueMatcher`, since identical descriptors match each other at zero distance and+ a mutual test does not reject a pair of them: keep the slots where :func:`~kornia.feature.laf_is_filled` is+ true, ``descs[b][laf_is_filled(lafs)[b]]`` for image ``b``, rather than testing the response (see the+ Convention block of :func:`~kornia.feature.laf_is_filled`). The ratio tests of+ :func:`~kornia.feature.match_snn` and :func:`~kornia.feature.match_smnn` do not replace this filtering: when+ the other image has exactly one padded slot, the padded slots of the two images can match each other at zero+ distance.+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).- An ``int`` is converted to ``float``. Must be positive.+ scaling_coef: the multiplier of the detector's LAFs before the description, see the Convention block. An+ ``int`` is converted to ``float``. Must be positive."""@@ -280,23 +304,8 @@ class LocalFeature(nn.Module):- Response function values for corresponding lafs with shape :math:`(B,N)`.- Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.- The shape is fixed at the detector's ``num_features``. When an image yields fewer detections, the- remaining slots carry a zero response and a zero LAF, and their descriptor is that of a patch sampled- at the origin -- one and the same vector for every such slot. :class:`LocalFeatureMatcher` drops them- before matching; a hand-rolled pipeline must do the same before any other matcher, including- :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_mnn`, :func:`~kornia.feature.match_fginn`,- :func:`~kornia.feature.match_adalam` and :class:`~kornia.feature.LightGlueMatcher`, since identical- descriptors match each other at zero distance and a mutual test does not reject a pair of them, with- :func:`~kornia.feature.laf_is_filled`::-- from kornia.feature import laf_is_filled-- valid = laf_is_filled(lafs) # (B, N); the zero LAF marks a padded slot- descs, lafs = descs[0][valid[0]], lafs[:, valid[0]]-- Test the LAF, not the response: a signed response can legitimately peak at exactly zero. Only the ratio- tests in :func:`~kornia.feature.match_snn` and :func:`~kornia.feature.match_smnn` reject padded slots on- their own, because the second-nearest padded descriptor is at the same zero distance.+ The Convention block of :class:`LocalFeature` gives the frame, ``N`` and the slots the detector did not fill,+ which have to be dropped before matching."""lafs, responses = self.detector(img, mask)@@ -344,35 +353,35 @@ class _SIFTFeature(LocalFeature):class SIFTFeature(_SIFTFeature):"""Multiresolution DoG detection followed by a (Root)SIFT descriptor.- :class:`~kornia.feature.MultiResolutionDetector` applies a single-scale DoG response- independently at each image resolution and uses 2-D non-maximum suppression. It does- not select extrema across scale or refine positions and scales to subpixel precision.- It does not apply classical SIFT's contrast or Hessian edge rejection and assigns one- orientation per detection unless ``upright=True``. For new scale-space SIFT pipelines,- start with :class:`SIFTFeatureScaleSpace` and explicitly select+ For new scale-space SIFT pipelines, start with :class:`SIFTFeatureScaleSpace` and explicitly select``descriptor_backend="pyramid"``; see :ref:`sift-pipelines`.- ``descriptor_backend="pyramid"`` uses :class:`SIFTDescriptorFromPyramid` for- orientation and description at the detector's sparse LAFs. Detection and the- feature budget are unchanged. Its orientation integrates smoothed image- gradients before angular binning without extracting image patches. The- remaining performance and accuracy acceptance criteria are tracked in- `#5748 <https://github.com/kornia/kornia/issues/5748>`_. No deprecation warning- or removal version is set.- The standalone descriptor-only ``SIFTDescriptorFromPyramid.forward`` interface- remains useful for supplied oriented LAFs. The default ``"patch"`` backend retains the- existing patch-wise pipeline. Both return descriptors in kornia's SIFT layout by- default; ``descriptor_layout="opencv"`` returns them in OpenCV's, which- :class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.- :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.-- The detector applies :class:`~kornia.feature.MultiResolutionDetector` to the- magnitude of a single-scale :class:`~kornia.feature.BlobDoGSingle` response.- It retains extrema of both polarity: dark blobs are DoG maxima and bright- blobs are DoG minima. On each image-pyramid level, a keypoint is a strict- maximum of response magnitude in its ``config["nms_size"]`` window (15 pixels- by default); a stronger extremum of either polarity in that window suppresses- a weaker one. ``responses`` contains the magnitude.+ Convention:+ - A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of one grayscale+ image per call, :math:`(1, 1, H, W)`. The detector is a :class:`~kornia.feature.MultiResolutionDetector` on+ the magnitude of a single-scale :class:`~kornia.feature.BlobDoGSingle` response. With+ ``descriptor_backend="patch"``, the default, ``LAFOrienter(19)`` orients the LAFs unless ``upright`` and+ :class:`~kornia.feature.SIFTDescriptor` describes 41 x 41 patches. ``"pyramid"`` keeps the detector and+ orients and describes its LAFs with :class:`SIFTDescriptorFromPyramid`, which integrates smoothed image+ gradients without extracting patches.+ - The detector applies the response independently at each image resolution, with 2-D non-maximum+ suppression. It does not select extrema across scale or refine positions and scales to subpixel precision,+ and it does not apply classical SIFT's contrast or Hessian edge rejection. One orientation is assigned per+ detection unless ``upright=True``.+ - Extrema of both polarities are kept: dark blobs are DoG maxima and bright blobs are DoG minima. On each+ image-pyramid level, a keypoint is a strict maximum of the response magnitude in its ``config["nms_size"]``+ window (15 pixels by default), so a stronger extremum of either polarity suppresses a weaker one.+ ``responses`` holds the magnitude.+ - The frames are those of :class:`~kornia.feature.MultiResolutionDetector`: a pixel of a pyramid level, with a+ scale of ``config["s_mult"]`` (22 by default) times that level's pixel size whatever the size of the blob.+ Unlike the 6-sigma frames of :class:`SIFTFeatureScaleSpace`, their scale is not a fixed multiple of the+ detection sigma.+ - Descriptors come in kornia's SIFT layout; ``descriptor_layout="opencv"`` returns them in OpenCV's, which+ :class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.+ :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.+ - Known defects: ``descriptor_backend="pyramid"`` is less accurate than the patch backend on Oxford+ homographies at 2048 features, and not faster on CPU at 1024 features+ (`#5748 <https://github.com/kornia/kornia/issues/5748>`_)."""def __init__(@@ -419,25 +428,28 @@ class SIFTFeature(_SIFTFeature):class SIFTFeatureScaleSpace(LocalFeature):"""DoG scale-space detection, position/scale refinement and (Root)SIFT description.- For new scale-space SIFT pipelines, explicitly select ``descriptor_backend="pyramid"``;- see :ref:`sift-pipelines`. The constructor default remains ``"patch"`` and uses- :class:`~kornia.feature.ScaleSpaceDetector`. The pyramid backend is a specialized SIFT pipeline that reuses- the detector's Gaussian images and each detection's octave and layer. Image- gradients are computed once per used layer and sampled for sparse orientation- and descriptor integration. A dedicated DoG detector refines only sparse- extrema and ranks all valid candidates by response, without contrast or edge- rejection. Both backends search 3-D DoG extrema and refine position and scale;- neither applies classical SIFT's contrast or Hessian edge rejection, and each- assigns only one orientation per detection unless ``upright=True``. The backend- selects a different detector implementation as well as different orientation and- description stages. The feature budget is unchanged; detections may differ.- The default ``"patch"`` backend retains patch-wise orientation and description.- Both return descriptors in kornia's SIFT layout by default; ``descriptor_layout="opencv"``- returns them in OpenCV's, which :class:`~kornia.feature.LightGlueMatcher` expects with- ``"sift"``. :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.-- Pyramid extraction is not guaranteed to be faster on every device or workload.- Patch extraction remains available for existing pipelines and measured performance needs.+ For new scale-space SIFT pipelines, explicitly select ``descriptor_backend="pyramid"``; see :ref:`sift-pipelines`.++ Convention:+ - A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of grayscale+ images :math:`(B, 1, H, W)`; the pyramid backend converts an RGB image to grayscale first.+ ``descriptor_backend="patch"``, the default, runs :class:`~kornia.feature.ScaleSpaceDetector` with+ :class:`~kornia.feature.BlobDoG` on ``ScalePyramid(3, 1.6, 32, double_image=True)``, keeping minima as well+ as maxima, then ``LAFOrienter(19)`` unless ``upright``, and :class:`~kornia.feature.SIFTDescriptor` on 41 x+ 41 patches. ``"pyramid"`` runs a dedicated DoG detector and reuses its Gaussian images and the octave and+ layer of each detection for orientation and description: it refines only sparse extrema, ranks all valid+ candidates by absolute response, and computes image gradients once per used layer.+ - Both backends search 3-D DoG extrema and refine position and scale. Neither applies classical SIFT's contrast+ or Hessian edge rejection, and each assigns one orientation per detection unless ``upright=True``. The+ backend selects a different detector as well as different orientation and description stages, so the+ backends can return different detections as well as different descriptors; the feature budget is the same.+ - On both backends the LAF scale is 6 times the detection sigma, and ``responses`` is the absolute DoG, the+ same for a bright blob as for a dark one. The LAF centres are in the frame of+ :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`) on+ every octave.+ - Descriptors come in kornia's SIFT layout; ``descriptor_layout="opencv"`` returns them in OpenCV's, which+ :class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.+ :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two."""def __init__(@@ -512,7 +524,15 @@ class SIFTFeatureScaleSpace(LocalFeature):class GFTTAffNetHardNet(LocalFeature):- """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""+ """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor.++ Convention:+ A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of grayscale+ images :math:`(B, 1, H, W)`: a :class:`~kornia.feature.ScaleSpaceDetector` with the+ :class:`~kornia.feature.CornerGFTT` response, its maxima only and ``mr_size=6``, whose LAFs get their affine+ shape from :class:`~kornia.feature.LAFAffNetShapeEstimator`, then their orientation from ``LAFOrienter(19)``+ unless ``upright``, and are described by :class:`~kornia.feature.HardNet` on 32 x 32 patches.+ """def __init__(self,@@ -540,7 +560,15 @@ class GFTTAffNetHardNet(LocalFeature):class HesAffNetHardNet(LocalFeature):- """Convenience module, which implements Hessian detector + AffNet-HardNet descriptor."""+ """Convenience module, which implements Hessian detector + AffNet-HardNet descriptor.++ Convention:+ A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of grayscale+ images :math:`(B, 1, H, W)`: a :class:`~kornia.feature.ScaleSpaceDetector` with the+ :class:`~kornia.feature.BlobHessian` response, its maxima only and ``mr_size=6``, whose LAFs get their affine+ shape from :class:`~kornia.feature.LAFAffNetShapeEstimator`, then their orientation from ``LAFOrienter(19)``+ unless ``upright``, and are described by :class:`~kornia.feature.HardNet` on 32 x 32 patches.+ """def __init__(self,@@ -592,15 +620,16 @@ def _dog_detector(class DoGHardNet(LocalFeature):"""Convenience module, which implements DoG detector + HardNet descriptor.- The detector is the DoG :class:`~kornia.feature.ScaleSpaceDetector` of- :class:`~kornia.feature.SIFTFeatureScaleSpace`'s ``"patch"`` backend, and the orientation is estimated on its- 6-sigma frames. The returned LAFs are those frames scaled by two, to 12 sigma or six times OpenCV's- ``KeyPoint.size``, and HardNet describes them. These are the frames the ``"doghardnet"`` weights of- :class:`~kornia.feature.LightGlueMatcher` expect: pass the LAFs and descriptors, without the padded slots (see- :meth:`~kornia.feature.LocalFeature.forward`), to ``LightGlueMatcher("doghardnet")``.-- The image must have one channel, :math:`(B, 1, H, W)`: convert a color image with- :func:`~kornia.color.rgb_to_grayscale` first.+ Convention:+ - A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract. The detector is+ the DoG :class:`~kornia.feature.ScaleSpaceDetector` of :class:`~kornia.feature.SIFTFeatureScaleSpace`'s+ ``"patch"`` backend, and the orientation is estimated on its 6-sigma frames. The returned LAFs are those+ frames scaled by two (``scaling_coef=2``), to 12 sigma or six times OpenCV's ``KeyPoint.size``, and+ :class:`~kornia.feature.HardNet` describes them on 32 x 32 patches.+ - These are the frames the ``"doghardnet"`` weights of :class:`~kornia.feature.LightGlueMatcher` expect: pass+ the LAFs and descriptors, without the padded slots, to ``LightGlueMatcher("doghardnet")``.+ - The image must have one channel, :math:`(B, 1, H, W)`: convert a color image with+ :func:`~kornia.color.rgb_to_grayscale` first.Args:num_features: the number of features to detect.@@ -628,10 +657,11 @@ class DoGHardNet(LocalFeature):class DoGAffNetHardNet(LocalFeature):"""Convenience module, which implements DoG detector + AffNet-HardNet descriptor.- As :class:`~kornia.feature.DoGHardNet`, with the affine shape of each 6-sigma DoG frame estimated by- :class:`~kornia.feature.LAFAffNetShapeEstimator` before its orientation. The scale of the returned LAFs, the- square root of their determinant, is again 12 sigma. Pass the LAFs and descriptors, without the padded slots, to- ``LightGlueMatcher("dog_affnet_hardnet")``. The image must have one channel, :math:`(B, 1, H, W)`.+ Convention:+ As :class:`~kornia.feature.DoGHardNet`, with the affine shape of each 6-sigma DoG frame estimated by+ :class:`~kornia.feature.LAFAffNetShapeEstimator` before its orientation. The scale of the returned LAFs, the+ square root of their determinant, is again 12 sigma. Pass the LAFs and descriptors, without the padded slots,+ to ``LightGlueMatcher("dog_affnet_hardnet")``. The image must have one channel, :math:`(B, 1, H, W)`.Args:num_features: the number of features to detect.@@ -658,7 +688,15 @@ class DoGAffNetHardNet(LocalFeature):class KeyNetHardNet(LocalFeature):- """Convenience module, which implements KeyNet detector + HardNet descriptor."""+ """Convenience module, which implements KeyNet detector + HardNet descriptor.++ Convention:+ A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of one grayscale+ image per call, :math:`(1, 1, H, W)`: a :class:`~kornia.feature.KeyNetDetector`, whose LAFs get their+ orientation from :class:`~kornia.feature.OriNet` on 32 x 32 patches unless ``upright``, and are described by+ :class:`~kornia.feature.HardNet` on 32 x 32 patches. ``scale_laf`` is the ``scaling_coef`` of+ :class:`~kornia.feature.LocalFeature`: it multiplies the detector's LAFs before the description.+ """def __init__(self,@@ -687,6 +725,10 @@ class KeyNetAffNetHardNet(LocalFeature):"""Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor... image:: _static/img/keynet_affnet.jpg++ Convention:+ As :class:`~kornia.feature.KeyNetHardNet`, with the affine shape of each frame estimated by+ :class:`~kornia.feature.LAFAffNetShapeEstimator` before its orientation."""def __init__(diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex 561871e46..3e543c36b 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -43,6 +43,19 @@ class SOLD2(nn.Module):This is based on the original code from the paper "SOLDΒ²: Self-supervisedOcclusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.+ Convention:+ - :meth:`forward` takes the input and returns the heatmaps and the ``(row, col)`` line segments of+ :class:`~kornia.feature.SOLD2_detector`, whose Convention block gives their frame and order, and also+ ``dense_desc``, :math:`(B, 128, H / 4, W / 4)`, which is not normalized.+ - ``match`` takes segments as :meth:`forward` returns them and the descriptor map of one image each. It+ returns an int64 tensor :math:`(N_1,)`: for each segment of ``line_seg1``, the index of its match in+ ``line_seg2``, or ``-1``.+ - Known defects: ``match`` returns int32 when either set of segments is empty+ (`#5915 <https://github.com/kornia/kornia/issues/5915>`_). On CPU, it passes float16 and bfloat16+ descriptor maps to torch's ``grid_sample`` without an upcast: the half-precision kernel can return wrong+ values, NaN or overflow, and where torch has none the call raises+ (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).+Args:config: :class:`~kornia.feature.sold2.structures.DetectorCfg`, or a dict of its fields, specifyingparameters. None will load the default parameters, which are tuned for images in the range 400~800 px.diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex d3ffee186..3392454d3 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -40,10 +40,21 @@ class SOLD2_detector(nn.Module):This is based on the original code from the paper "SOLDΒ²: Self-supervisedOcclusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.+ Convention:+ - The input is a grayscale image :math:`(B, 1, H, W)`, in :math:`[0, 1]` for the pretrained weights, with+ ``H`` and ``W`` multiples of 8; other sizes raise an error or give heatmaps of another size.+ ``junction_heatmap`` and ``line_heatmap`` are :math:`(B, H, W)`.+ - ``line_segments`` holds one :math:`(N, 2, 2)` tensor per image: the two endpoints of each segment as+ ``(row, col)`` in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`), so ``flip(-1)`` gives ``(x, y)``. The endpoints+ of a segment, and the segments by their first endpoint, are in raster order: the smaller row first or, on+ the same row, the smaller column, whatever the junction scores.+ - The endpoints are junction pixels. The default junction refinement (``use_junction_refinement`` of+ ``LineDetectorCfg``) moves each of them by at most 1 pixel per axis, in 0.25 pixel steps.+Args:config (DetectorCfg): Configuration object containing all parameters. None will load the default parameters,- which are tuned for images in the range 400~800 px. Using a dataclass ensures type safety and clearer- parameter management.+ which are tuned for images in the range 400~800 px.pretrained (bool): If True, download and set pretrained weights to the model.Returns:diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex 81337d36c..0de316ebb 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -99,6 +99,16 @@ class XFeatModel(nn.Module):- ``keypoints``: keypoint logits :math:`(B, 65, H/8, W/8)`.- ``heatmap``: reliability map :math:`(B, 1, H/8, W/8)`.+ Convention:+ - The channels are averaged and the result is instance-normalised, so any channel count is accepted and an+ affine change ``a x + b`` of the intensities with ``a > 0`` changes the outputs only through the norm's+ ``eps`` (``1e-5``): negligibly while the variance of the channel mean is much larger than ``eps``, and+ substantially for a low-contrast image, whose variance is close to it (see :class:`XFeat`).+ - ``H`` and ``W`` must be multiples of 8; other sizes raise an error or give maps of mismatched sizes.+ :class:`XFeat` resizes its input to multiples of 32.+ - ``keypoints`` holds 65 logits per 8 x 8 cell: channel ``(y % 8) * 8 + x % 8`` of cell ``(y // 8, x // 8)``+ is pixel ``(x, y)``, and channel 64 is the "no keypoint" dustbin.+Note:Image normalisation (``InstanceNorm2d``) is wrapped in ``torch.no_grad()``following the original design; backpropagating through it is not supported.@@ -220,10 +230,21 @@ class XFeatModel(nn.Module):class InterpolateSparse2d(nn.Module):"""Bilinearly or bicubically sample a dense feature map at sparse 2-D positions.+ Convention:+ - ``pos`` holds ``(x, y)`` pixels of an image of height ``H`` and width ``W`` whose feature map has height+ ``h`` and width ``w``. A position ``(px, py)`` is read at ``px * w / (W - 1) - 0.5`` and+ ``py * h / (H - 1) - 0.5`` in the map's pixel frame: ``normgrid``'s ``2 p / (W - 1) - 1`` sampled with+ ``align_corners=False``, the convention the pretrained XFeat weights use. So a map of the image's own size is+ not read at ``p`` itself.+ - Known defects: on CPU, float16 and bfloat16 maps go to torch's ``grid_sample`` without an upcast: the+ half-precision kernel can return wrong values, NaN or overflow, and where torch has none the call raises+ (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).+Args:mode: interpolation mode for :func:`torch.nn.functional.grid_sample`.Default: ``'bicubic'``.- align_corners: passed to ``grid_sample``. Default: ``False``.+ align_corners: stored and not used: ``grid_sample`` is always called with ``align_corners=False``. Default:+ ``False``.Shape:- Input ``x``: :math:`(B, C, H, W)`.@@ -278,9 +299,39 @@ class XFeat(nn.Module):.. image:: _static/img/XFeat.png+ Convention:+ - XFeat defines no ``forward``: call :meth:`detectAndCompute` or :meth:`detectAndComputeDense`.+ - The image is :math:`(B, C, H, W)` with any channel count. Each extraction resizes the image it gets+ bilinearly to :math:`(H', W')`: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.+ :class:`XFeatModel` then averages the channels and instance-normalises the result, so an affine change of the+ intensities with a positive gain changes its maps only through the norm's ``eps``, which weighs more the+ lower the image's contrast. With the pretrained weights and ``top_k=2048``, the :math:`[0, 1]` and+ :math:`[0, 255]` versions of Oxford graf and wall ``img1`` differ in at most 1 keypoint, in 1 to 2 % of them+ with the intensities multiplied by 0.1, and in 35 to 40 % multiplied by 0.01. Every output is float32.+ - :meth:`detectAndCompute` keypoints are integer pixels ``i`` of the resized image, strict maxima of the+ keypoint heatmap in their 5 x 5 window (see the note), reported at ``i * (W / W', H / H')``. That is the+ pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`) when ``H`` and ``W`` are multiples of 32;+ otherwise the centre of the resized pixel is at ``(i + 0.5) * (W / W', H / H') - 0.5``.+ - The heatmap value must be strictly above ``detection_threshold``. ``scores`` is that value times the+ reliability map, and the ``top_k`` best keypoints come sorted by it. Each descriptor is 64-D, sampled+ bicubically from the dense map at the keypoint by :class:`InterpolateSparse2d`, and L2-normalised.+ - With ``multiscale=False``, :meth:`detectAndComputeDense` reports cell ``(j, i)`` of the 1/8-resolution map+ at ``8 * (j, i)``, times the same ratio: the top-left pixel of the cell, not its centre. It keeps the+ ``top_k`` cells of highest reliability, or every cell when there are fewer or ``top_k`` is below 1. With+ the default ``multiscale=True``, it rescales the image bilinearly by 0.6 and by 1.3, runs that extraction+ on each with ``top_k`` set to ``int(0.2 * top_k)`` and ``int(0.8 * top_k)``, and divides each keypoint by+ its factor; ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. A scale with fewer cells than its+ share returns all of them, and the truncation can lose one, so there can be fewer than ``top_k`` keypoints.+ Its descriptors are not normalised.+ - Known defects: with ``multiscale=True``, a share that rounds down to 0 keeps every cell of its scale, so a+ ``top_k`` from 1 to 4 returns all the cells of the 0.6 extraction, and ``top_k=1`` those of both+ (`#5924 <https://github.com/kornia/kornia/issues/5924>`_).+Args:top_k: maximum number of keypoints to keep per image. Default: ``4096``.- detection_threshold: minimum keypoint score. Default: ``0.05``.+ detection_threshold: the keypoint heatmap value a keypoint must exceed, see the Convention block. Default:+ ``0.05``.Note:Keypoints are the strict local maxima of the keypoint heatmap: :func:`~kornia.geometry.subpix.nms2d` keeps a@@ -317,7 +368,7 @@ class XFeat(nn.Module):Args:top_k: maximum number of keypoints to keep. Default: ``4096``.- detection_threshold: minimum keypoint score. Default: ``0.05``.+ detection_threshold: the keypoint heatmap value a keypoint must exceed. Default: ``0.05``.Returns:XFeat model with pretrained weights loaded, set to eval mode.@@ -496,13 +547,13 @@ class XFeat(nn.Module):Args:x: image tensor of shape :math:`(B, C, H, W)`.top_k: number of keypoints to keep (overrides ``self.top_k``).- detection_threshold: minimum score (overrides ``self.detection_threshold``).+ detection_threshold: the heatmap value to exceed (overrides ``self.detection_threshold``).Returns:List of length ``B``. Each element is a dict with:- ``'keypoints'``: :math:`(N, 2)` keypoints in (x, y) pixel coordinates.- - ``'scores'``: :math:`(N,)` reliability scores.+ - ``'scores'``: :math:`(N,)` keypoint heatmap value times reliability, in descending order.- ``'descriptors'``: :math:`(N, 64)` L2-normalised descriptors."""if top_k is None:diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 249a28a9a..2a77c89eb 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -18,12 +18,13 @@import pytestimport torch+import korniafrom kornia.feature import laf_is_filledfrom kornia.feature.aliked import ALIKED, ALIKEDFeaturesfrom kornia.feature.aliked.aliked import _affine_from_covfrom kornia.feature.aliked.deform_conv2d import deform_conv2d-from testing.base import BaseTester+from testing.base import BaseTester, supports_bilinear_2d_grid_sample, supports_replicate_padding# ---------------------------------------------------------------------------# deform_conv2d tests@@ -631,3 +632,212 @@ class TestALIKEDKeypointSelection(BaseTester):for i, j in enumerate(order):self.assert_close(batched[i].keypoints, alone[j].keypoints, rtol=0.0, atol=0.0)self.assert_close(batched[i].keypoint_scores, alone[j].keypoint_scores, rtol=0.0, atol=0.0)+++class TestConventionsALIKED(BaseTester):+ @pytest.fixture(autouse=True)+ def _kernels(self, device, dtype):+ if not (supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)):+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")++ @staticmethod+ def _score_map(peaks, device, dtype, batch=1, h=64, w=96, background=0.01):+ # A score map (after the sigmoid) with the given peaks (image, x, y, score) on a constant background.+ s = torch.full((batch, 1, h, w), background, dtype=torch.float64)+ for b, x, y, score in peaks:+ s[b, 0, y, x] = score+ return s.to(device, dtype)++ @staticmethod+ def _hooked(model, score_map):+ # the score head returns the logit of score_map, so the sigmoid after it gives score_map back+ return model.score_head.register_forward_hook(lambda m, i, o: torch.logit(score_map))++ @staticmethod+ def _raster(xy, w=1000):+ return xy[torch.argsort(xy[:, 1] * w + xy[:, 0])]++ @staticmethod+ def _peak_tol(dtype):+ # An isolated peak lands on its pixel. In half precision DKD computes in the map's dtype, so the position is+ # checked to 0.25 px, half of the 0.5 px offset of an edge-aligned frame.+ return 0.25 if dtype in (torch.float16, torch.bfloat16) else 1e-4++ def test_convention_aliked_keypoints_are_soft_argmax_peaks_in_the_pixel_frame(self, device, dtype):+ # Keypoints are pixel coordinates (x, y) of the score map, wh = (W - 1, H - 1) with align_corners=True (the+ # formula of Shiaoming/ALIKED 683d7c6's DKD): an isolated peak lands on its pixel, and the peak at (60, 40) with+ # a weaker right neighbour moves right by the soft-argmax (temperature 0.1) over its 5 x 5 window, by+ # (e**-1 - e**-7.9) / (1 + e**-1 + 23 * e**-7.9) = 0.267006 px. forward_laf returns the same centres and scores.+ half = dtype in (torch.float16, torch.bfloat16)+ peaks = [(0, 21, 13, 0.9), (0, 60, 40, 0.8), (0, 61, 40, 0.7), (0, 30, 10, 0.75)]+ expected = torch.tensor([[30.0, 10.0], [21.0, 13.0], [60.267006, 40.0]], dtype=torch.float64)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ for h, w, peaks_i, expected_i in (+ (64, 96, peaks, expected),+ (96, 64, [(b, y, x, s) for b, x, y, s in peaks], expected.flip(-1)), # relabelling: transpose+ ):+ hook = self._hooked(aliked, self._score_map(peaks_i, device, dtype, h=h, w=w))+ try:+ with torch.no_grad():+ image = torch.rand(1, 3, h, w, device=device, dtype=dtype)+ (feats,) = aliked(image)+ lafs, responses, _ = aliked.forward_laf(image)+ finally:+ hook.remove()+ assert feats.n == 3+ order = torch.argsort(feats.keypoints[:, 1] * 1000 + feats.keypoints[:, 0])+ found, expected_i = feats.keypoints[order].cpu().double(), self._raster(expected_i)+ # bfloat16 loses the soft-argmax step, so in half precision only the isolated peaks are checked+ isolated = (expected_i == expected_i.round()).all(dim=-1)+ checked = isolated if half else torch.ones_like(isolated)+ self.assert_close(found[checked], expected_i[checked], rtol=0.0, atol=self._peak_tol(dtype))+ self.assert_close(lafs[0, :, :, 2], feats.keypoints)+ self.assert_close(responses[0, :, 0], feats.keypoint_scores)+ if not half:+ # the score is the score map read bilinearly at the keypoint: 0.8 - 0.1 * 0.267006 at the moved peak+ expected_scores = torch.tensor([0.9, 0.75, 0.8 - 0.1 * 0.267006], device=device, dtype=dtype)+ self.assert_close(feats.keypoint_scores[order], expected_scores, rtol=0.0, atol=1e-4)++ def test_convention_aliked_forward_laf_pads_to_the_largest_count_in_the_batch(self, device, dtype):+ # forward_laf stacks the per-image detections and zero-pads them to the largest count in the batch, here 3,+ # not to max_num_keypoints; responses are (B, N, 1). compute_affine=False gives every filled frame A = I. A mask+ # multiplies the score map before the detection.+ peaks = [(0, 21, 13, 0.9), (0, 60, 40, 0.8), (0, 30, 50, 0.7), (1, 70, 20, 0.6)]+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=8).to(device, dtype).eval()+ hook = self._hooked(aliked, self._score_map(peaks, device, dtype, batch=2))+ try:+ with torch.no_grad():+ image = torch.rand(2, 3, 64, 96, device=device, dtype=dtype)+ lafs, responses, descs = aliked.forward_laf(image)+ lafs_id, _, _ = aliked.forward_laf(image, compute_affine=False)+ mask = torch.ones(2, 1, 64, 96, device=device, dtype=dtype)+ mask[0, :, :, :48] = 0.0+ lafs_masked, _, _ = aliked.forward_laf(image, mask=mask)+ finally:+ hook.remove()+ assert lafs.shape == (2, 3, 2, 3)+ assert responses.shape == (2, 3, 1)+ assert descs.shape == (2, 3, 64)+ assert lafs[1, 1:].abs().max() == 0+ assert responses[1, 1:].abs().max() == 0+ assert descs[1, 1:].abs().max() == 0+ assert kornia.feature.laf_is_filled(lafs).tolist() == [[True, True, True], [True, False, False]]+ tol = self._peak_tol(dtype)+ self.assert_close(lafs[1, 0, :, 2], torch.tensor([70.0, 20.0], device=device, dtype=dtype), rtol=0.0, atol=tol)+ eye = torch.eye(2, device=device, dtype=dtype)+ self.assert_close(lafs_id[0, :, :, :2], eye.expand(3, 2, 2))+ self.assert_close(lafs_id[1, 0, :, :2], eye)+ assert lafs_id[1, 1:].abs().max() == 0+ # the mask leaves (60, 40) in the first image: one keypoint in each image, so N = 1+ assert lafs_masked.shape == (2, 1, 2, 3)+ expected = torch.tensor([[60.0, 40.0], [70.0, 20.0]], device=device, dtype=dtype)+ self.assert_close(lafs_masked[:, 0, :, 2], expected, rtol=0.0, atol=tol)++ def test_convention_aliked_counts_by_threshold_or_top_k(self, device, dtype):+ # detection_threshold > 0: keep the maxima strictly above it, at most max_num_keypoints of them (-1: at most+ # 20000); detection_threshold <= 0 with max_num_keypoints > 0: the max_num_keypoints strongest maxima (this map+ # has more); both off: the maxima above the mean of the score map. An image with no maximum above the+ # threshold falls back to the maxima above its own mean.+ # Maxima 0.9, 0.8, 0.5 on row 20 (x = 20, 40, 60), 0.2, 0.15 on row 45 (x = 20, 40) and 0.013 at (80, 40); a+ # 16 x 26 plateau of 0.1, which has no strict maximum, lifts the map mean to 0.0165, above the 0.013 maximum.+ maxima = [(0, 20, 20, 0.9), (0, 40, 20, 0.8), (0, 60, 20, 0.5), (0, 20, 45, 0.2), (0, 40, 45, 0.15)]+ maxima.append((0, 80, 40, 0.013))+ score_map = self._score_map(maxima, "cpu", torch.float64)+ score_map[..., :16, 70:] = 0.1+ score_map = score_map.to(device, dtype)+ kept = {}+ for kwargs in (+ {},+ {"max_num_keypoints": 2},+ {"detection_threshold": 0.5},+ {"max_num_keypoints": 4, "detection_threshold": 0.5},+ {"detection_threshold": 0.0},+ {"max_num_keypoints": 4, "detection_threshold": 0.0},+ ):+ aliked = ALIKED(model_name="aliked-t16", **kwargs).to(device, dtype).eval()+ hook = self._hooked(aliked, score_map)+ try:+ with torch.no_grad():+ (feats,) = aliked(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ finally:+ hook.remove()+ kept[str(kwargs)] = sorted((round(x), round(y)) for x, y in feats.keypoints.float().tolist())+ assert kept == {+ "{}": [(20, 20), (40, 20), (60, 20)],+ "{'max_num_keypoints': 2}": [(20, 20), (40, 20)],+ "{'detection_threshold': 0.5}": [(20, 20), (40, 20)],+ "{'max_num_keypoints': 4, 'detection_threshold': 0.5}": [(20, 20), (40, 20)],+ "{'detection_threshold': 0.0}": [(20, 20), (20, 45), (40, 20), (40, 45), (60, 20)],+ "{'max_num_keypoints': 4, 'detection_threshold': 0.0}": [(20, 20), (20, 45), (40, 20), (60, 20)],+ }+ # the fallback: an image alone whose best score, 0.15, is below 0.2 keeps both its maxima+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ hook = self._hooked(aliked, self._score_map([(0, 20, 20, 0.15), (0, 60, 40, 0.12)], device, dtype))+ try:+ with torch.no_grad():+ (feats,) = aliked(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ finally:+ hook.remove()+ assert sorted((round(x), round(y)) for x, y in feats.keypoints.float().tolist()) == [(20, 20), (60, 40)]++ def test_convention_aliked_image_size_is_the_valid_width_and_height_of_each_image(self, device, dtype):+ # image_size holds (W, H) per image of a batch padded at the bottom and right to a common size: maxima within+ # nms_radius (2) of an image's own valid border are dropped, so column W - 3 and row H - 3 are the last kept.+ # Image 0 is valid on (W, H) = (62, 41), image 1 on (50, 60), both inside a 64 x 96 batch.+ peaks = [+ (0, 21, 13, 0.9),+ (0, 59, 20, 0.9),+ (0, 60, 30, 0.9),+ (0, 40, 38, 0.9),+ (0, 45, 39, 0.9),+ (1, 47, 10, 0.9),+ (1, 48, 30, 0.9),+ (1, 20, 57, 0.9),+ (1, 25, 58, 0.9),+ ]+ expected = [[[21.0, 13.0], [59.0, 20.0], [40.0, 38.0]], [[47.0, 10.0], [20.0, 57.0]]]+ # relabelling: the transposed batch with the transposed sizes keeps the transposed maxima+ peaks_t = [(b, y, x, s) for b, x, y, s in peaks]+ expected_t = [[p[::-1] for p in e] for e in expected]+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ for h, w, peaks_i, size, expected_i in (+ (64, 96, peaks, [[62, 41], [50, 60]], expected),+ (96, 64, peaks_t, [[41, 62], [60, 50]], expected_t),+ ):+ hook = self._hooked(aliked, self._score_map(peaks_i, device, dtype, batch=2, h=h, w=w))+ try:+ with torch.no_grad():+ image = torch.rand(2, 3, h, w, device=device, dtype=dtype)+ feats = aliked(image, image_size=torch.tensor(size, device=device))+ finally:+ hook.remove()+ for f, e in zip(feats, expected_i):+ reference = self._raster(torch.tensor(e, dtype=torch.float64))+ found = self._raster(f.keypoints.cpu().double())+ self.assert_close(found, reference, rtol=0.0, atol=self._peak_tol(dtype))++ def test_convention_aliked_takes_raw_rgb_or_grayscale_and_crops_its_padding(self, device, dtype):+ # The backbone sees the image as given, without ImageNet normalisation (the pretrained weights take [0, 1], the+ # ToTensor() range of Shiaoming/ALIKED); a grayscale image is repeated to three channels. A 50 x 75 image is+ # replicate-padded to 64 x 96, 7 rows above and below and 10 / 11 columns left / right, and the score map is+ # cropped back, so the peaks placed at padded pixels (31, 20) and (70, 47) are the keypoints (21, 13) and+ # (60, 40) of the input.+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ seen = []+ pre = aliked.block1.register_forward_pre_hook(lambda m, i: seen.append(i[0]))+ hook = self._hooked(aliked, self._score_map([(0, 31, 20, 0.9), (0, 70, 47, 0.8)], device, dtype))+ rgb = torch.rand(1, 3, 50, 75, device=device, dtype=dtype)+ gray = torch.rand(1, 1, 50, 75, device=device, dtype=dtype)+ expected = torch.tensor([[21.0, 13.0], [60.0, 40.0]], device=device, dtype=dtype)+ try:+ with torch.no_grad():+ for image in (rgb, gray):+ (feats,) = aliked(image)+ x = seen[-1]+ assert x.shape == (1, 3, 64, 96)+ self.assert_close(x[..., 7:57, 10:85], image.expand(1, 3, 50, 75), rtol=0.0, atol=0.0)+ self.assert_close(x[..., 7:57, 0], image.expand(1, 3, 50, 75)[..., 0], rtol=0.0, atol=0.0)+ self.assert_close(feats.keypoints, expected, rtol=0.0, atol=self._peak_tol(dtype))+ finally:+ pre.remove()+ hook.remove()diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex bcd802913..2fa486027 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -280,3 +280,90 @@ class TestDeDoDe:assert keypoints.shape == (shape[0], n, 2)assert scores.shape == (shape[0], n)assert descriptions.shape == (shape[0], n, 256)+++class _FixedMap(torch.nn.Module):+ """A DeDoDe network stand-in that returns ``fn(images)`` and records its input."""++ def __init__(self, fn):+ super().__init__()+ self.fn = fn+ self.seen = []++ def forward(self, images):+ self.seen.append(images)+ return self.fn(images)+++class TestConventionsDeDoDe(BaseTester):+ @staticmethod+ def _model(monkeypatch, peaks):+ # DeDoDe with its networks replaced (no VGG is built, nothing is downloaded): the detector returns logits -20+ # with the given peaks (x, y, logit), the descriptor a two-channel map (column, row), so a description names+ # the pixel it was read at.+ def detector(images):+ b, _, h, w = images.shape+ logits = torch.full((b, 1, h, w), -20.0, device=images.device, dtype=images.dtype)+ for x, y, logit in peaks:+ if y < h and x < w:+ logits[:, 0, y, x] = logit+ return logits++ def descriptor(images):+ b, _, h, w = images.shape+ yy, xx = torch.meshgrid(+ torch.arange(h, device=images.device), torch.arange(w, device=images.device), indexing="ij"+ )+ return torch.stack([xx, yy])[None].expand(b, 2, h, w).to(images.dtype)++ monkeypatch.setattr("kornia.feature.dedode.dedode.get_detector", lambda *a, **k: _FixedMap(detector))+ monkeypatch.setattr("kornia.feature.dedode.dedode.get_descriptor", lambda *a, **k: _FixedMap(descriptor))+ return DeDoDe(detector_model="L", descriptor_model="B")++ def test_convention_dedode_forward_returns_edge_aligned_pixels_and_detect_normalised_ones(+ self, device, dtype, monkeypatch+ ):+ # Logit peaks at pixels (60, 40) and (21, 13) of a 56 x 84 image. forward returns pixel i as i + 0.5 (subtract+ # 0.5 for kornia's frame), detect returns (2 i + 1) / (W, H) - 1 in [-1, 1], and the description is read at+ # pixel i itself; keypoints and descriptions are float32 whatever the model dtype, keypoints come sorted by+ # score, N = min(n, H W) with no threshold or padding. The grid and its pixel conversion are the formulas of+ # Parskatt/DeDoDe 6d15618 (utils.get_grid, to_pixel_coords).+ peaks = [(21, 13, 18.0), (60, 40, 20.0)]+ pixels = torch.tensor([[[60.0, 40.0], [21.0, 13.0]]], device=device)+ for h, w, peaks_i, image_pixels in (+ (56, 84, peaks, pixels),+ (84, 56, [(y, x, v) for x, y, v in peaks], pixels.flip(-1)), # relabelling: transpose+ ):+ model = self._model(monkeypatch, peaks_i).to(device, dtype)+ image = torch.rand(1, 3, h, w, device=device, dtype=dtype)+ keypoints, scores, descriptions = model(image, n=2)+ normalised, _ = model.detect(image, n=2)+ assert keypoints.dtype == normalised.dtype == descriptions.dtype == torch.float32+ self.assert_close(keypoints, image_pixels + 0.5)+ size = torch.tensor([w, h], device=device)+ self.assert_close(normalised, (2.0 * image_pixels + 1.0) / size - 1.0)+ self.assert_close(descriptions, image_pixels)+ assert scores[0, 0] > scores[0, 1]+ keypoints, scores, descriptions = model(torch.rand(2, 3, 14, 28, device=device, dtype=dtype), n=1000)+ assert keypoints.shape == (2, 392, 2)+ assert scores.shape == (2, 392)+ assert descriptions.shape == (2, 392, 2)++ def test_convention_dedode_takes_rgb_in_the_unit_range_and_imagenet_normalises_it(self, device, dtype, monkeypatch):+ # forward, detect and describe feed the networks (x - mean) / std with ImageNet's mean (0.485, 0.456, 0.406) and+ # std (0.229, 0.224, 0.225), the normalisation the pretrained weights expect (Parskatt/DeDoDe's image loader);+ # apply_imagenet_normalization=False feeds the input as given.+ model = self._model(monkeypatch, [(21, 13, 18.0), (60, 40, 20.0)]).to(device, dtype)+ image = torch.rand(1, 3, 56, 84, device=device, dtype=dtype)+ mean = torch.tensor([0.485, 0.456, 0.406], device=device, dtype=dtype).view(1, 3, 1, 1)+ std = torch.tensor([0.229, 0.224, 0.225], device=device, dtype=dtype).view(1, 3, 1, 1)+ model(image, n=2)+ model.detect(image, n=2)+ model.describe(image)+ model(image, n=2, apply_imagenet_normalization=False)+ seen = model.detector.seen + model.descriptor.seen+ assert len(seen) == 6+ for net in (model.detector, model.descriptor):+ for normalised in net.seen[:2]:+ self.assert_close(normalised, (image - mean) / std)+ self.assert_close(net.seen[2], image, rtol=0.0, atol=0.0)diff --git a/tests/feature/test_defmo.py b/tests/feature/test_defmo.pyindex fa5d71c91..a9e9bc2c5 100644--- a/tests/feature/test_defmo.py+++ b/tests/feature/test_defmo.py@@ -117,3 +117,46 @@ class TestDeFMO(BaseTester):model_jit = torch.jit.script(DeFMO(True).to(patches.device, patches.dtype).eval())with torch.no_grad():self.assert_close(model(patches), model_jit(patches))+++class _RecordingRenderer(torch.nn.Module):+ """A stand-in for the rendering network: returns fixed values per output channel and records each input."""++ def __init__(self, values):+ super().__init__()+ self.values = values+ self.seen = []++ def forward(self, latent):+ self.seen.append(latent)+ b, _, h, w = latent.shape+ out = self.values.to(latent).view(1, -1, 1, 1).expand(b, -1, 16 * h, 16 * w)+ return out.clone()+++class TestConventionsDeFMO(BaseTester):+ def test_convention_defmo_renders_24_rgba_subframes_in_time_order(self, device, dtype):+ # DeFMO takes (B, 6, H, W) and returns (B, 24, 4, H, W) for H and W multiples of 16; other sizes are rounded up+ # to the next multiple of 16. The encoder's latent is (B, 2048, H / 16, W / 16); sub-frame k is rendered from it+ # with the time t = k / 23 prepended as channel 0, and all four channels, RGB and alpha, go through a sigmoid.+ # The rendering network is replaced by a recorder that upsamples by 16 as the real one does. The input channel+ # order (the blurred RGB image, then the RGB background: the order of rozumden/DeFMO 9b69769 run.py) only+ # matters to the trained weights and is not visible here.+ with torch.random.fork_rng(devices=[]):+ torch.manual_seed(0)+ model = DeFMO().eval()+ model = model.to(device, dtype)+ values = torch.tensor([-3.0, -1.0, 0.5, 4.0], device=device, dtype=dtype)+ model.rendering.net = _RecordingRenderer(values)+ with torch.no_grad():+ out = model(torch.rand(2, 6, 64, 96, device=device, dtype=dtype))+ assert model(torch.rand(1, 6, 60, 90, device=device, dtype=dtype)).shape == (1, 24, 4, 64, 96)+ assert out.shape == (2, 24, 4, 64, 96)+ self.assert_close(out[1, 7, :, 50, 11], torch.sigmoid(values))+ self.assert_close(out[0, 23, :, 3, 90], torch.sigmoid(values))+ assert len(model.rendering.net.seen) == 48 # 24 sub-frames per call+ latents = model.rendering.net.seen[:24]+ assert all(latent.shape == (2, 2049, 4, 6) for latent in latents)+ times = torch.stack([latent[:, 0] for latent in latents]) # (24, B, h, w), each constant+ expected = torch.linspace(0, 1, 24, device=device, dtype=dtype).view(24, 1, 1, 1).expand_as(times)+ self.assert_close(times, expected)diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.pyindex 93d67072b..3ec26b051 100644--- a/tests/feature/test_disk.py+++ b/tests/feature/test_disk.py@@ -22,7 +22,12 @@ import torchfrom kornia.feature.disk import DISK, DISKFeatures-from testing.base import BaseTester+from testing.base import (+ BaseTester,+ supports_bicubic_2d_grid_sample,+ supports_bilinear_2d_grid_sample,+ supports_replicate_padding,+)from testing.casts import dict_to@@ -209,3 +214,179 @@ class TestDiskKeypointSelection(BaseTester):):kept = {n: self._features(heatmaps, device, dtype, n=n)[0][0] for n in expected_i}assert kept == expected_i+++class _FixedUNet(torch.nn.Module):+ """A U-Net stand-in that returns a fixed output and records its input."""++ def __init__(self, output):+ super().__init__()+ self.output = output+ self.seen = []++ def forward(self, images):+ self.seen.append(images)+ return self.output+++class TestConventionsDISK(BaseTester):+ @staticmethod+ def _disk(peaks, device, dtype, h=48, w=80):+ # DISK with its U-Net replaced (the public unet argument) by a fixed output: heatmap channel 128 is -1 with the+ # given peaks (x, y, logit); descriptor channels 0, 1, 2 are the column, the row and 1, so a descriptor names+ # its pixel.+ out = torch.zeros(1, 129, h, w, dtype=torch.float64)+ out[0, 128] = -1.0+ for x, y, logit in peaks:+ out[0, 128, y, x] = logit+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ out[0, 0], out[0, 1], out[0, 2] = xx, yy, torch.ones_like(xx)+ return DISK(unet=_FixedUNet(out.to(device, dtype))).eval()++ def test_convention_disk_keypoints_are_the_xy_pixels_of_the_heatmap_maxima(self, device, dtype):+ # Peaks at (x, y) = (13, 21), (50, 9), (60, 33) of a 48 x 80 heatmap. The keypoints are those pixels as (x, y),+ # in raster (row-major) order rather than by score; detection_scores are the heatmap values there and each+ # descriptor is the L2-normalised dense descriptor at its pixel.+ peaks = [(13, 21, 2.0), (50, 9, 1.5), (60, 33, 1.0)]+ expected = torch.tensor([[50.0, 9.0], [13.0, 21.0], [60.0, 33.0]], device=device, dtype=dtype)+ image = torch.rand(1, 3, 48, 80, device=device, dtype=dtype)+ (feats,) = self._disk(peaks, device, dtype)(image)+ self.assert_close(feats.keypoints, expected, rtol=0.0, atol=0.0)+ self.assert_close(feats.detection_scores, torch.tensor([1.5, 2.0, 1.0], device=device, dtype=dtype))+ named = torch.cat([expected, torch.ones_like(expected[:, :1])], dim=-1)+ self.assert_close(feats.descriptors[:, :3], torch.nn.functional.normalize(named, dim=-1), low_tolerance=True)+ assert feats.descriptors[:, 3:].abs().max() == 0+ # heatmap_and_dense_descriptors returns the dense descriptors as the network outputs them, not normalised+ _heatmaps, dense = self._disk(peaks, device, dtype).heatmap_and_dense_descriptors(image)+ self.assert_close(dense[0, :3, 21, 13], torch.tensor([13.0, 21.0, 1.0], device=device, dtype=dtype))+ # relabelling: the transposed heatmap gives the transposed keypoints, again in raster order+ disk_t = self._disk([(y, x, s) for x, y, s in peaks], device, dtype, h=80, w=48)+ (feats_t,) = disk_t(image.transpose(-1, -2))+ assert feats_t.keypoints.tolist() == [[21.0, 13.0], [9.0, 50.0], [33.0, 60.0]]++ def test_convention_disk_takes_raw_rgb_and_pads_bottom_right_to_a_multiple_of_16(self, device, dtype):+ # The U-Net sees the RGB input as given (cvlab-epfl/disk divides uint8 images by 255 before the network). With+ # pad_if_not_divisible a 45 x 75 image is zero-padded at the bottom and right to 48 x 80, and the maps are+ # cropped back to 45 x 75 before the suppression: the peaks at (40, 45) and (77, 10) lie in the padding, and+ # (73, 20) is 1 px from the cropped right edge, so none of them is a keypoint; (72, 30), 2 px from it, is.+ peaks = [(13, 21, 2.0), (72, 30, 1.0), (73, 20, 1.0), (40, 45, 3.0), (77, 10, 3.0)]+ disk = self._disk(peaks, device, dtype)+ image = torch.rand(1, 3, 45, 75, device=device, dtype=dtype)+ (feats,) = disk(image, pad_if_not_divisible=True)+ seen = disk.unet.seen[0]+ assert seen.shape == (1, 3, 48, 80)+ self.assert_close(seen[..., :45, :75], image, rtol=0.0, atol=0.0)+ assert seen[..., 45:, :].abs().max() == 0+ assert seen[..., :, 75:].abs().max() == 0+ assert feats.keypoints.tolist() == [[13.0, 21.0], [72.0, 30.0]]++ def test_convention_disk_default_unet_sees_a_common_gain_only_through_the_norms_eps(self, device, dtype):+ # The default U-Net instance-normalises every channel before each convolution but the first, which removes a+ # common positive gain of the input together with the first convolution's bias, so [0, 255] gives the maps,+ # keypoints and descriptors of [0, 1] up to the norms' eps (random weights) at ordinary contrast. At low+ # contrast eps weighs against the variance and the gain shows. An offset is not removed: the first+ # convolution's zero padding does not move with it.+ with torch.random.fork_rng(devices=[]):+ torch.manual_seed(0)+ disk = DISK().eval()+ image = torch.rand(1, 3, 48, 80)+ disk, image = disk.to(device, dtype), image.to(device, dtype)+ tol = {torch.float16: 2e-2, torch.bfloat16: 1e-1}.get(dtype, 3e-3) # the maps span about 3+ # torch 2.5.1's CPU float16 instance norm overflows on a [0, 255] image, so float16 scales by 16 instead+ scale = 16.0 if dtype == torch.float16 else 255.0+ with torch.no_grad():+ heatmap, dense = disk.heatmap_and_dense_descriptors(image)+ heatmap_s, dense_s = disk.heatmap_and_dense_descriptors(scale * image)+ self.assert_close(heatmap_s, heatmap, rtol=0.0, atol=tol)+ self.assert_close(dense_s, dense, rtol=0.0, atol=tol)+ if dtype in (torch.float32, torch.float64): # half-precision rounding can swap near-tied maxima+ (feats,), (feats_s,) = disk(image), disk(scale * image)+ assert feats.n > 10+ assert torch.equal(feats_s.keypoints, feats.keypoints)+ self.assert_close(feats_s.descriptors, feats.descriptors, rtol=0.0, atol=tol)+ assert (disk.heatmap_and_dense_descriptors(image + 0.3)[0] - heatmap).abs().max() > 0.2+ low = 0.01 * image # intensities spread over 0.01: the same gain moves the heatmap by about 0.5+ heatmap_low = disk.heatmap_and_dense_descriptors(low)[0]+ assert (disk.heatmap_and_dense_descriptors(scale * low)[0] - heatmap_low).abs().max() > 0.2++ def test_convention_disk_n_keeps_the_strongest_and_score_threshold_is_strict(self, device, dtype):+ # n is an upper bound on the maxima above score_threshold: with more maxima than n, forward keeps the n+ # strongest, and with n of them it keeps all; score_threshold keeps the scores strictly above it. The keypoints+ # stay in raster order. TestDiskKeypointSelection pins the count above score_threshold and the ties at the cut.+ disk = self._disk([(13, 21, 2.0), (50, 9, 1.5), (60, 33, 1.0)], device, dtype)+ image = torch.rand(1, 3, 48, 80, device=device, dtype=dtype)+ kept = {}+ for kwargs in ({}, {"n": 1}, {"n": 2}, {"n": 3}, {"score_threshold": 1.0}, {"score_threshold": 1.5}):+ (feats,) = disk(image, **kwargs)+ kept[str(kwargs)] = feats.detection_scores.tolist()+ assert kept == {+ "{}": [1.5, 2.0, 1.0],+ "{'n': 1}": [2.0],+ "{'n': 2}": [1.5, 2.0],+ "{'n': 3}": [1.5, 2.0, 1.0],+ "{'score_threshold': 1.0}": [1.5, 2.0],+ "{'score_threshold': 1.5}": [2.0],+ }++ @pytest.mark.parametrize("model", ["DISK", "ALIKED", "XFeat"])+ def test_convention_learned_detectors_keep_strict_maxima_whose_window_fits_in_the_image(self, device, dtype, model):+ # DISK, ALIKED and XFeat keep a position only if it is greater than every other score of its 5 x 5 window and+ # the window lies in the image: the peaks one pixel from each border, the tied pair at (40, 50) and (41, 50),+ # and the flank (12, 30), (14, 30) of the peak at (10, 30) are not keypoints. This departs on purpose from+ # cvlab-epfl/disk, Shiaoming/ALIKED and verlab/accelerated_features, whose max-pool NMS clips the window at the+ # border and keeps ties, and, for ALIKED, re-admits the flank. ALIKED's soft-argmax moves the (10, 30) peak+ # towards its flank by 2 * (e**-0.5 - e**-8.9) / (1 + e**-0.5 + 23 * e**-8.9) = 0.7534 px; in half precision+ # ALIKED's positions are checked to 0.25 px, enough to tell the surviving maxima apart.+ from kornia.feature import ALIKED, XFeat++ if model == "ALIKED" and not (+ supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)+ ):+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")+ border = [(1, 40, 0.95), (94, 20, 0.95), (60, 1, 0.95), (45, 62, 0.95)]+ inside = [(2, 10, 0.6), (93, 50, 0.6), (70, 2, 0.6), (20, 61, 0.6)]+ tie_and_flank = [(40, 50, 0.7), (41, 50, 0.7), (10, 30, 0.9), (12, 30, 0.85), (14, 30, 0.8)]+ peaks = border + inside + tie_and_flank+ kept = [[70.0, 2.0], [2.0, 10.0], [10.7534 if model == "ALIKED" else 10.0, 30.0], [93.0, 50.0], [20.0, 61.0]]+ half = dtype in (torch.float16, torch.bfloat16)+ tol = (0.25 if half else 1e-4) if model == "ALIKED" else 0.0+ for h, w, peaks_i, expected in (+ (64, 96, peaks, kept),+ (96, 64, [(y, x, s) for x, y, s in peaks], [[y, x] for x, y in kept]), # relabelling: transpose+ ):+ image = torch.rand(1, 3, h, w, device=device, dtype=dtype)+ if model == "DISK":+ out = torch.zeros(1, 129, h, w, dtype=torch.float64)+ out[0, 128] = -1.0+ for x, y, s in peaks_i:+ out[0, 128, y, x] = s+ (feats,) = DISK(unet=_FixedUNet(out.to(device, dtype))).eval()(image)+ keypoints = feats.keypoints+ elif model == "ALIKED":+ score_map = torch.full((1, 1, h, w), 0.01, dtype=torch.float64)+ for x, y, s in peaks_i:+ score_map[0, 0, y, x] = s+ logits = torch.logit(score_map).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ aliked.score_head.register_forward_hook(lambda m, i, o, logits=logits: logits)+ with torch.no_grad():+ (feats,) = aliked(image)+ keypoints = feats.keypoints+ else:+ if not supports_bicubic_2d_grid_sample(device, torch.float32):+ pytest.skip("XFeat samples its descriptors bicubically, absent on this device")+ # keypoint logits: dustbin 10, a peak of score s gets 10 + 2 s in its cell's channel (y % 8) * 8 + x % 8+ logits = torch.zeros(1, 65, h // 8, w // 8)+ logits[0, 64] = 10.0+ for x, y, s in peaks_i:+ logits[0, (y % 8) * 8 + x % 8, y // 8, x // 8] = 10.0 + 2.0 * s+ outputs = (torch.zeros(1, 64, h // 8, w // 8), logits, torch.full((1, 1, h // 8, w // 8), 0.5))+ xfeat = XFeat().to(device).eval()+ outputs = tuple(t.to(device) for t in outputs)+ xfeat.net.register_forward_hook(lambda m, i, o, outputs=outputs: outputs)+ keypoints = xfeat.detectAndCompute(image)[0]["keypoints"]+ order = torch.argsort(keypoints[:, 1] * 1000 + keypoints[:, 0]) # raster order+ reference = torch.tensor(sorted(expected, key=lambda p: (p[1], p[0])), device=device)+ self.assert_close(keypoints[order].float(), reference, rtol=0.0, atol=tol)diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex dbf3aae5c..006ce4f1f 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -47,7 +47,13 @@ from kornia.feature.integrated import LocalFeatureMatcherfrom kornia.feature.scale_space_detector import get_default_detector_configfrom kornia.geometry import RANSAC, resize, transform_points-from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_replicate_padding+from testing.base import (+ DYNAMO_UNAVAILABLE_REASON,+ BaseTester,+ dynamo_is_available,+ supports_reflect_padding,+ supports_replicate_padding,+)from testing.casts import dict_to@@ -1122,3 +1128,159 @@ class TestConventionsSIFTScaleSpaceKeypointSize(BaseTester):# the frame's own rounding on top of the backend's detection errorrtol = backend_rtol + 2.0 * torch.finfo(dtype).epsself.assert_close(scale, torch.tensor(3.0 * 8.871075630187988, dtype=torch.float64), rtol=rtol, atol=0.0)+++class _PatchMeanDescriptor(nn.Module):+ """A descriptor that does not normalise: the patch mean and a constant 1, so no patch maps to the zero vector."""++ def forward(self, patches: torch.Tensor) -> torch.Tensor:+ mean = patches.mean(dim=(1, 2, 3))+ return torch.stack([mean, torch.ones_like(mean)], dim=-1)+++class TestConventionsLocalFeature(BaseTester):+ @staticmethod+ def _blobs(blobs, device, dtype, h=72, w=96):+ # Bright Gaussian blobs (x, y, sigma) on a black H != W image, built in float64 on the CPU, then cast.+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ img = sum(torch.exp(-((xx - x0) ** 2 + (yy - y0) ** 2) / (2.0 * s * s)) for x0, y0, s in blobs)+ return img[None, None].to(device, dtype)++ def test_convention_local_feature_pads_every_image_to_num_features_with_zero_frames(self, device, dtype):+ # Blobs at (30, 22) sigma 3 and (61, 47) sigma 4; the second image has the second blob only.+ # ScaleSpaceDetector(8) finds one frame per blob, so the images fill 2 and 1 of the 8 slots: N is the detector's+ # num_features for every image, not the largest count in the batch. The centres are checked to 0.1 px, and to+ # 0.25 px in half precision, half of the 0.5 px offset of an edge-aligned frame.+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):+ pytest.skip("ScaleSpaceDetector and SIFTDescriptor need reflection and replication padding for this dtype")+ img = torch.cat(+ [+ self._blobs([(30.0, 22.0, 3.0), (61.0, 47.0, 4.0)], device, dtype),+ self._blobs([(61.0, 47.0, 4.0)], device, dtype),+ ]+ )+ descriptor = LAFDescriptor(SIFTDescriptor(32), patch_size=32)+ feature = LocalFeature(ScaleSpaceDetector(8), descriptor).to(device, dtype)+ with torch.no_grad():+ lafs, responses, descs = feature(img)+ lafs_t, _, _ = feature(img.transpose(-1, -2).contiguous())+ zero_frame = descriptor(img, lafs.new_zeros(2, 1, 2, 3))+ assert lafs.shape == (2, 8, 2, 3)+ assert responses.shape == (2, 8)+ assert descs.shape == (2, 8, 128)+ filled = laf_is_filled(lafs)+ assert filled.sum(dim=-1).tolist() == [2, 1]+ tol = 0.25 if dtype in (torch.float16, torch.bfloat16) else 0.1+ blobs = torch.tensor([[30.0, 22.0], [61.0, 47.0]], dtype=torch.float64)+ centres = get_laf_center(lafs).cpu().double()+ self.assert_close(centres[0, filled[0].cpu()], blobs, rtol=0.0, atol=tol)+ self.assert_close(centres[1, filled[1].cpu()], blobs[1:], rtol=0.0, atol=tol)+ # relabelling: the transposed image gives the transposed centres+ centres_t = get_laf_center(lafs_t).cpu().double()[0, laf_is_filled(lafs_t)[0].cpu()]+ self.assert_close(centres_t, blobs.flip(-1), rtol=0.0, atol=tol)+ # an unfilled slot is a zero LAF with a zero response ...+ assert lafs[~filled].abs().max() == 0+ assert responses[~filled].abs().max() == 0+ # ... and every one of them carries the descriptor of a patch sampled at the origin, one vector per image.+ # SIFT maps that constant patch to almost zero, so a descriptor that does not normalise shows it is described.+ for b in range(2):+ assert (descs[b, ~filled[b]] == descs[b, ~filled[b]][:1]).all()+ self.assert_close(descs[0, ~filled[0]], zero_frame[0].expand(6, 128))+ self.assert_close(descs[1, ~filled[1]], zero_frame[1].expand(7, 128))+ # The same frames described on a ramp whose origin pixel differs from every other pixel and between the+ # images: a zero LAF samples every patch pixel at the origin, so the patch mean is ramp[b, 0, 0, 0].+ yy, xx = torch.meshgrid(torch.arange(72.0), torch.arange(96.0), indexing="ij")+ ramp = ((xx + 100.0 * yy) / 8000.0 + torch.tensor([0.25, 0.5]).view(2, 1, 1, 1)).to(device, dtype)+ mean_feature = LocalFeature(lambda im, mask=None: (lafs, responses), LAFDescriptor(_PatchMeanDescriptor(), 8))+ with torch.no_grad():+ _, _, mean_descs = mean_feature.to(device, dtype)(ramp)+ origin = torch.stack([ramp[:, 0, 0, 0], torch.ones_like(ramp[:, 0, 0, 0])], dim=-1)+ self.assert_close(mean_descs[0, ~filled[0]], origin[0].expand(6, 2))+ self.assert_close(mean_descs[1, ~filled[1]], origin[1].expand(7, 2))++ # preset: (detector, num_features, mr_size, response, orientation estimator and its patch size, affine shape,+ # descriptor, patch size). mr_size multiplies the detection scale into the LAF scale: sigma for ScaleSpaceDetector,+ # the pyramid level's pixel size for the multi-resolution detectors. The upright variants orient with PassLAF.+ _PRESETS = {+ "SIFTFeature": ("MultiResolutionDetector", 8000, 22.0, None, "PatchDominantGradientOrientation", 19, "PassLAF",+ "SIFTDescriptor", 41),+ "SIFTFeatureScaleSpace": ("ScaleSpaceDetector", 8000, 6.0, "BlobDoG", "PatchDominantGradientOrientation", 19,+ "PassLAF", "SIFTDescriptor", 41),+ "GFTTAffNetHardNet": ("ScaleSpaceDetector", 8000, 6.0, "CornerGFTT", "PatchDominantGradientOrientation", 19,+ "LAFAffNetShapeEstimator", "HardNet", 32),+ "HesAffNetHardNet": ("ScaleSpaceDetector", 2048, 6.0, "BlobHessian", "PatchDominantGradientOrientation", 19,+ "LAFAffNetShapeEstimator", "HardNet", 32),+ "KeyNetHardNet": ("KeyNetDetector", 8000, 22.0, "KeyNet", "OriNet", 32, "PassLAF", "HardNet", 32),+ "KeyNetAffNetHardNet": ("KeyNetDetector", 8000, 22.0, "KeyNet", "OriNet", 32, "LAFAffNetShapeEstimator",+ "HardNet", 32),+ } # fmt: skip++ @pytest.mark.parametrize("preset", list(_PRESETS))+ def test_convention_presets_compose_their_documented_modules(self, monkeypatch, preset):+ # The presets load pretrained HardNet, AffNet, OriNet and KeyNet weights; random networks keep this offline.+ # SIFTFeature's response, the magnitude of BlobDoGSingle(1.0, 1.6), is checked by TestSIFTFeature.+ from kornia.feature import KeyNetDetector, LAFAffNetShapeEstimator, OriNet++ integrated = "kornia.feature.integrated"+ monkeypatch.setattr(f"{integrated}.HardNet", lambda pretrained=False: HardNet(False))+ monkeypatch.setattr(+ f"{integrated}.LAFAffNetShapeEstimator",+ lambda pretrained=False, preserve_orientation=True: LAFAffNetShapeEstimator(False, preserve_orientation),+ )+ monkeypatch.setattr(f"{integrated}.OriNet", lambda pretrained=False, eps=1e-8: OriNet(False))+ monkeypatch.setattr(f"{integrated}.KeyNetDetector", lambda pretrained=False, **kw: KeyNetDetector(False, **kw))+ spec = self._PRESETS[preset]+ detector, num_features, mr_size, response, orienter, orienter_size, affine, descriptor, patch_size = spec+ cls = getattr(kornia.feature, preset)+ extra = {"scale_laf": 2.0} if preset.startswith("KeyNet") else {}+ feature = cls(**extra)+ det = feature.detector+ assert type(det).__name__ == detector+ assert det.num_features == num_features+ assert det.mr_size == mr_size+ if response is not None:+ assert type(getattr(det, "resp", None) or det.model).__name__ == response+ assert type(det.ori).__name__ == "LAFOrienter"+ assert type(det.ori.angle_detector).__name__ == orienter+ assert det.ori.patch_size == orienter_size+ assert type(det.aff).__name__ == affine+ if affine != "PassLAF":+ # the detectors estimate the affine shape before the orientation, so AffNet's upright shape gets turned+ assert det.aff.preserve_orientation is False+ assert type(feature.descriptor).__name__ == "LAFDescriptor"+ assert type(feature.descriptor.descriptor).__name__ == descriptor+ assert feature.descriptor.patch_size == patch_size+ # the KeyNet presets' scale_laf is LocalFeature's scaling_coef; every other preset keeps the detector frames+ assert feature.scaling_coef == (2.0 if extra else 1.0)+ assert type(cls(upright=True).detector.ori).__name__ == "PassLAF"++ def test_convention_local_feature_ratio_tests_keep_a_single_padded_pair(self, device, dtype):+ # A detector that filled num_features - 1 slots leaves one padded slot: a zero LAF with the descriptor of the+ # origin patch. Image 0 has 4 real slots and 1 padded one, image 1 has 3 real and 1 padded. The padded pair is+ # at distance 0 and each padded descriptor's second-nearest is a real one, so the ratio is 0: match_snn and+ # match_smnn both report the pair, and filtering with laf_is_filled removes it.+ gen = torch.Generator().manual_seed(3)+ real = torch.nn.functional.normalize(torch.rand(7, 8, generator=gen, dtype=torch.float64), dim=-1)+ pad = torch.nn.functional.normalize(+ torch.tensor([[0.9, 0.1, 0.4, 0.2, 0.7, 0.3, 0.5, 0.6]], dtype=torch.float64), dim=-1+ )+ desc0 = torch.cat([real[:4], pad]).to(device, dtype)+ desc1 = torch.cat([real[4:], pad]).to(device, dtype)+ centres = torch.tensor([[[23.0, 11.0], [61.0, 17.0], [9.0, 40.0], [75.0, 33.0]]])+ scales, oris = torch.full((1, 4, 1, 1), 6.0), torch.full((1, 4, 1), 17.0)+ lafs = kornia.feature.laf_from_center_scale_ori(centres, scales, oris)+ lafs0 = torch.cat([lafs, torch.zeros(1, 1, 2, 3)], dim=1).to(device, dtype)+ lafs1 = torch.cat([lafs[:, :3], torch.zeros(1, 1, 2, 3)], dim=1).to(device, dtype)+ filled0, filled1 = laf_is_filled(lafs0)[0], laf_is_filled(lafs1)[0]+ assert filled0.tolist() == [True, True, True, True, False]+ assert filled1.tolist() == [True, True, True, False]+ for matcher, th in ((kornia.feature.match_snn, 0.8), (kornia.feature.match_smnn, 0.95)):+ dists, idxs = matcher(desc0, desc1, th)+ pairs = [tuple(pair) for pair in idxs.tolist()]+ assert (4, 3) in pairs+ assert dists[pairs.index((4, 3))].item() == 0.0+ _, idxs_filled = matcher(desc0[filled0], desc1[filled1], th)+ assert (idxs_filled[:, 0] < 4).all()+ assert (idxs_filled[:, 1] < 3).all()diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pyindex 0463058eb..322d2726f 100644--- a/tests/feature/test_sift_scale_space.py+++ b/tests/feature/test_sift_scale_space.py@@ -887,3 +887,31 @@ class TestSIFTScaleSpaceDetector(BaseTester):lafs, responses = detector(torch.zeros(1, 1, 32, 32, device=device))(lafs.sum() + responses.sum()).backward()assert torch.isfinite(dog.grad).all()+++class TestConventionsSIFTFeatureScaleSpace(BaseTester):+ def test_convention_pyramid_backend_centres_are_pixel_centres_at_every_octave(self, device, dtype):+ # Three bright blobs (x, y, sigma) at non-integer centres of a 120 x 176 image, detected on octaves 0, 1 and 2.+ # The pyramid backend maps every octave's pixel back to the image's pixel-centre frame, so each centre is+ # within 0.1 px of its blob. Half-precision input is detected in float32 and the LAFs are cast to the dtype at+ # the end, which adds half a unit in the last place at coordinates below 128: 0.25 px in bfloat16, 1 / 32 px+ # in float16.+ tol = 0.1 + {torch.bfloat16: 0.25, torch.float16: 1.0 / 32}.get(dtype, 0.0)+ blobs = [(37.3, 41.6, 1.5), (112.7, 38.2, 3.5), (71.4, 84.3, 8.0)]+ yy, xx = torch.meshgrid(+ torch.arange(120, dtype=torch.float64), torch.arange(176, dtype=torch.float64), indexing="ij"+ )+ img = sum(torch.exp(-((xx - x0) ** 2 + (yy - y0) ** 2) / (2.0 * s * s)) for x0, y0, s in blobs)[None, None]+ expected = torch.tensor([[x0, y0] for x0, y0, _ in blobs], dtype=torch.float64)+ feature = SIFTFeatureScaleSpace(32, upright=True, descriptor_backend="pyramid").to(device, dtype)+ for image, centres in ((img, expected), (img.transpose(-1, -2), expected.flip(-1))): # relabelling: transpose+ image = image.contiguous().to(device, dtype)+ with torch.no_grad():+ lafs, _, _ = feature(image)+ _, _, filled_d, _, octaves, _ = feature.detector._detect_with_pyramid(image, 32)+ filled = laf_is_filled(lafs)[0]+ assert torch.equal(filled, filled_d[0])+ found = get_laf_center(lafs)[0, filled].cpu().double()+ nearest = (found[None] - centres[:, None]).norm(dim=-1).argmin(dim=1)+ assert octaves[0, filled][nearest.to(device)].tolist() == [0, 1, 2]+ self.assert_close(found[nearest], centres, rtol=0.0, atol=tol)diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex 617fd5728..3f092e4f9 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -324,3 +324,122 @@ class TestKeypointsToGrid(BaseTester):op = keypoints_to_gridop_optimized = torch_optimizer(op)self.assert_close(op(kp, (32, 64)), op_optimized(kp, (32, 64)))+++class _FixedSOLD2Net(torch.nn.Module):+ """A SOLD2 network stand-in that returns fixed outputs."""++ def __init__(self, outputs):+ super().__init__()+ self.outputs = outputs++ def forward(self, img):+ return self.outputs+++class TestConventionsSOLD2(BaseTester):+ @staticmethod+ def _maps(start, end, s_start, s_end, device, dtype, h=96, w=128):+ # Junction and line heatmaps (B, H, W) for one line from start to end, given as (x, y), with the junction+ # scores s_start and s_end.+ junctions = torch.zeros(1, h, w)+ junctions[0, start[1], start[0]], junctions[0, end[1], end[0]] = s_start, s_end+ heatmap = torch.zeros(1, h, w)+ t = torch.linspace(0, 1, 400)+ heatmap[+ 0,+ torch.round(start[1] + (end[1] - start[1]) * t).long(),+ torch.round(start[0] + (end[0] - start[0]) * t).long(),+ ] = 1.0+ return junctions.to(device, dtype), heatmap.to(device, dtype)++ @staticmethod+ def _segments(model, maps, image):+ # The network is replaced by one that returns the given junction and line maps (and empty descriptors); the+ # line detector runs as usual.+ junctions, heatmap = maps+ h, w = heatmap.shape[-2:]+ descriptors = heatmap.new_zeros(1, 128, h // 4, w // 4)+ network = model.model+ model.model = _FixedSOLD2Net({"junctions": junctions, "heatmap": heatmap, "descriptors": descriptors})+ try:+ with torch.no_grad():+ return model(image)["line_segments"][0]+ finally:+ model.model = network++ @pytest.mark.parametrize("model_cls", [SOLD2_detector, SOLD2])+ def test_convention_sold2_segments_are_row_col_endpoints_in_raster_order(self, device, dtype, model_cls):+ # A line from (x, y) = (100, 30) to (20, 70) on a 96 x 128 image. Segments are (N, 2, 2) endpoints (row, col) in+ # kornia's pixel frame (flip(-1) gives (x, y)), and the first endpoint is the one with the smaller row, here the+ # one with the larger column, whatever the junction scores. Without junction refinement the endpoints are the+ # junction pixels. The default refinement (JunctionRefineCfg: 9 perturbations 0.25 px apart) moves each+ # endpoint by at most 1 px per axis, in 0.25 px steps, and does not depend on the junction scores.+ image = torch.rand(1, 1, 96, 128, device=device, dtype=dtype)+ unrefined = DetectorCfg(line_detector_cfg=LineDetectorCfg(use_junction_refinement=False))+ junctions = torch.tensor([[[30.0, 100.0], [70.0, 20.0]]], device=device)+ for config in (unrefined, None):+ model = model_cls(pretrained=False, config=config).to(device, dtype)+ per_score_order = []+ for scores in ((0.5, 1.0), (1.0, 0.5)):+ maps = self._maps((100, 30), (20, 70), *scores, device, dtype)+ per_score_order.append(self._segments(model, maps, image).float())+ for segments in per_score_order:+ if config is unrefined:+ self.assert_close(segments, junctions, rtol=0.0, atol=0.0)+ else:+ assert (segments - junctions).abs().max() <= 1.0+ assert torch.equal(segments * 4, (segments * 4).round())+ assert torch.equal(per_score_order[0], per_score_order[1])+ # relabelling: the transposed maps give the transposed endpoints, (row, col) in the transposed image, where the+ # other endpoint now has the smaller row and comes first+ model = model_cls(pretrained=False, config=unrefined).to(device, dtype)+ maps = self._maps((30, 100), (70, 20), 0.5, 1.0, device, dtype, h=128, w=96)+ segments = self._segments(model, maps, image.transpose(-1, -2))+ self.assert_close(segments.float(), junctions.flip(-1).flip(1), rtol=0.0, atol=0.0)++ def test_convention_sold2_takes_one_channel_and_returns_maps_at_the_input_size(self, device, dtype):+ # (B, 1, H, W) with H and W multiples of 8: the junction and line heatmaps are (B, H, W), SOLD2's dense+ # descriptors (B, 128, H / 4, W / 4); a three-channel image is rejected. SOLD2.match returns an int64 index into+ # the second set of segments per segment of the first, or -1.+ # The detection threshold is raised above any probability, so that the line detector, which this pin does not+ # read, has no junctions of the random network to connect.+ model = SOLD2(pretrained=False, config=DetectorCfg(detection_thresh=2.0)).to(device, dtype)+ image = torch.rand(2, 1, 64, 96, device=device, dtype=dtype)+ with torch.no_grad():+ out = model(image)+ raw = model.model(image)["descriptors"]+ with pytest.raises(ShapeError):+ model(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ assert out["junction_heatmap"].shape == (2, 64, 96)+ assert out["line_heatmap"].shape == (2, 64, 96)+ assert out["dense_desc"].shape == (2, 128, 16, 24)+ # dense_desc is the descriptor head's output as it is, not normalised per position+ assert torch.equal(out["dense_desc"], raw)+ assert (raw.float().norm(dim=1) - 1.0).abs().max() > 0.1+ segments1 = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]], device=device)+ segments2 = torch.cat([segments1 + 1.0, torch.tensor([[[5.0, 5.0], [5.0, 60.0]]], device=device)])+ maps = torch.rand(2, 1, 128, 16, 24, device=device) # float32: torch 2.5.1 has no CPU half grid_sample+ matches = model.match(segments1, segments2, maps[0], maps[1])+ assert matches.dtype == torch.int64+ assert matches.shape == (2,)+ assert ((matches >= -1) & (matches < 3)).all()++ def test_wart_sold2_match_returns_int32_when_a_set_of_segments_is_empty_5915(self, device, dtype):+ # SOLD2.match returns an int64 index per segment of line_seg1, but int32 when either set of segments is empty+ # (#5915): an empty tensor when image 1 has no segments, -1 per segment when image 2 has none.+ model = SOLD2(pretrained=False)+ segments = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]], device=device)+ maps = torch.rand(2, 1, 128, 16, 24, device=device, dtype=dtype)+ for line_seg1, line_seg2, expected in (+ (segments[:0], segments, []),+ (segments, segments[:0], [-1, -1]),+ (segments[:0], segments[:0], []),+ ):+ matches = model.match(line_seg1, line_seg2, maps[0], maps[1])+ assert matches.dtype == torch.int32+ assert matches.device == maps.device+ assert matches.tolist() == expected+ # two non-empty sets give int64 (float32 maps: torch 2.5.1 has no CPU half grid_sample)+ matches = model.match(segments, segments, maps[0].float(), maps[1].float())+ assert matches.dtype == torch.int64diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex d102ea7dc..9cd1f3331 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -15,13 +15,22 @@# limitations under the License.#+import math+import pytestimport torch+from torch.overrides import TorchFunctionModefrom kornia.feature.lightglue import LightGluefrom kornia.feature.xfeat import InterpolateSparse2d, XFeat, XFeatModel-from testing.base import BaseTester, supports_bicubic_2d_grid_sample, supports_bilinear_2d_grid_sample+from testing.base import (+ BaseTester,+ supports_bicubic_2d_grid_sample,+ supports_bilinear_2d_grid_sample,+ supports_nearest_2d_grid_sample,+ supports_replicate_padding,+)# ---------------------------------------------------------------------------# XFeatModel backbone tests@@ -445,3 +454,238 @@ def test_lighterglue_reference_matches(device, data):# NN matching in joint (x0,y0,x1,y1) space with max L2 distance 2.0frac = _nn_match_fraction(ref_pairs, comp_pairs, max_dist=2.0)assert frac > 0.95, f"Only {frac:.1%} of reference matches reproduced within joint distance 2.0 px"+++class TestConventionsXFeat(BaseTester):+ @staticmethod+ def _net_outputs(peaks, h, w, reliability=0.5):+ # What XFeatModel returns for an h x w (resized) image, replaced through a forward hook: keypoint logits with+ # the dustbin (channel 64) at 10 and the given peaks (x, y, logit) in channel (y % 8) * 8 + x % 8 of cell+ # (y // 8, x // 8), a constant reliability map, and dense features (column, row, 1, 0, ...) per cell.+ logits = torch.zeros(1, 65, h // 8, w // 8)+ logits[0, 64] = 10.0+ for x, y, logit in peaks:+ logits[0, (y % 8) * 8 + x % 8, y // 8, x // 8] = logit+ yy, xx = torch.meshgrid(torch.arange(h // 8.0), torch.arange(w // 8.0), indexing="ij")+ feats = torch.zeros(1, 64, h // 8, w // 8)+ feats[0, 0], feats[0, 1], feats[0, 2] = xx, yy, torch.ones_like(xx)+ return feats, logits, torch.full((1, 1, h // 8, w // 8), reliability)++ def _detect(self, image, outputs, **kwargs):+ # detectAndCompute samples the descriptors bicubically, in float32 whatever the input dtype+ if not supports_bicubic_2d_grid_sample(image.device, torch.float32):+ pytest.skip("This device does not support bicubic interpolation for 2D grid_sample")+ xfeat = XFeat(**kwargs).to(image.device).eval()+ seen = []++ def hook(module, inputs, output):+ seen.append(inputs[0])+ return tuple(t.to(image.device) for t in outputs)++ handle = xfeat.net.register_forward_hook(hook)+ try:+ (out,) = xfeat.detectAndCompute(image)+ finally:+ handle.remove()+ return out, seen[0]++ def test_convention_xfeat_keypoints_are_pixels_of_the_resized_grid_times_the_resize_ratio(self, device, dtype):+ # detectAndCompute resizes to (max(32, 32 floor(H / 32)), max(32, 32 floor(W / 32))), takes integer heatmap+ # pixels i there and reports i * (W / W', H / H') (the formula of verlab/accelerated_features e92685f): kornia's+ # pixel frame when H and W are multiples of 32. The score is the keypoint heatmap value times the reliability,+ # keypoints come sorted by it, and outputs are float32 whatever the input dtype. Heatmap value of a peak with+ # logit v: exp(v) / (exp(v) + exp(10) + 63), the softmax over the 65 channels.+ peaks = [(22, 13, 11.0), (70, 41, 12.0)] # in-cell offsets (6, 5) and (6, 1): x % 8 != y % 8+ heat = [math.exp(v) / (math.exp(v) + math.exp(10.0) + 63.0) for _, _, v in peaks]+ expected_scores = torch.tensor([0.5 * heat[1], 0.5 * heat[0]], device=device) # the stronger, later in raster+ for h, w, peaks_i, expected in (+ (64, 96, peaks, [[70.0, 41.0], [22.0, 13.0]]),+ (96, 64, [(y, x, v) for x, y, v in peaks], [[41.0, 70.0], [13.0, 22.0]]), # relabelling: transpose+ ):+ image = torch.rand(1, 3, h, w, device=device, dtype=dtype)+ out, seen = self._detect(image, self._net_outputs(peaks_i, h, w))+ assert seen.shape == (1, 3, h, w)+ assert out["keypoints"].dtype == out["scores"].dtype == out["descriptors"].dtype == torch.float32+ assert out["keypoints"].tolist() == expected+ self.assert_close(out["scores"], expected_scores)+ self.assert_close(out["descriptors"].norm(dim=-1), torch.ones(2, device=device))+ # detection_threshold bounds the heatmap value (0.8805 and 0.7305 here), not the score (half of it)+ image = torch.rand(1, 3, 64, 96, device=device, dtype=dtype)+ for threshold, expected in ((0.5, [[70.0, 41.0], [22.0, 13.0]]), (0.8, [[70.0, 41.0]])):+ out, _ = self._detect(image, self._net_outputs(peaks, 64, 96), detection_threshold=threshold)+ assert out["keypoints"].tolist() == expected+ # 100 x 150 is resized to 96 x 128: resized pixel (22, 13) is reported at (22 * 150 / 128, 13 * 100 / 96); its+ # centre in the input's pixel frame would be (22.5 * 150 / 128 - 0.5, 13.5 * 100 / 96 - 0.5). A side below 32+ # is enlarged to 32: 20 x 150 is resized to 32 x 128.+ for h, w, h_resized in ((100, 150, 96), (20, 150, 32)):+ image = torch.rand(1, 3, h, w, device=device, dtype=dtype)+ out, seen = self._detect(image, self._net_outputs([(22, 13, 12.0)], h_resized, 128))+ assert seen.shape == (1, 3, h_resized, 128)+ expected = torch.tensor([[22 * w / 128, 13 * h / h_resized]], device=device)+ self.assert_close(out["keypoints"], expected)++ def test_convention_xfeat_dense_keypoints_are_the_top_left_pixels_of_their_8_pixel_cells(self, device, dtype):+ # detectAndComputeDense keeps the cells of highest reliability and reports cell (j, i) at (8 j, 8 i) times the+ # resize ratio: the cell's top-left pixel, not its centre (8 j + 3.5, 8 i + 3.5); the formula is create_xy * 8+ # of verlab/accelerated_features e92685f. Cells (2, 1) and (8, 5) of a 64 x 96 image.+ xfeat = XFeat().to(device).eval()+ for h, w, cells, expected in (+ (64, 96, [(2, 1), (8, 5)], [[16.0, 8.0], [64.0, 40.0]]),+ (96, 64, [(1, 2), (5, 8)], [[8.0, 16.0], [40.0, 64.0]]), # relabelling: transpose+ ):+ feats, logits, reliability = self._net_outputs([], h, w, reliability=0.1)+ (j0, i0), (j1, i1) = cells+ reliability[0, 0, i0, j0], reliability[0, 0, i1, j1] = 0.9, 0.8+ outputs = tuple(t.to(device) for t in (feats, logits, reliability))+ handle = xfeat.net.register_forward_hook(lambda m, i, o, outputs=outputs: outputs)+ try:+ out = xfeat.detectAndComputeDense(torch.rand(1, 3, h, w, device=device, dtype=dtype), 2, False)+ finally:+ handle.remove()+ assert out["keypoints"].tolist() == [expected]+ assert out["descriptors"].shape == (1, 2, 64)+ # the descriptors are the dense features of those cells, (j, i, 1, 0, ...), not normalised+ assert out["descriptors"][0, :, :3].tolist() == [[float(j0), float(i0), 1.0], [float(j1), float(i1), 1.0]]++ def test_convention_xfeat_dense_multiscale_runs_the_extraction_at_0_6_and_1_3_and_divides_by_the_factor(+ self, device, dtype+ ):+ # multiscale=True (the default) is the multiscale=False extraction of the image rescaled by 0.6 and by 1.3, with+ # int(0.2 * top_k) and int(0.8 * top_k) cells, each keypoint divided by its factor; scales is 1 / factor.+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 160, 224, device=device, dtype=dtype)+ out = xfeat.detectAndComputeDense(image, 100)+ parts = []+ for factor, k in ((0.6, 20), (1.3, 80)):+ scaled = torch.nn.functional.interpolate(image, scale_factor=factor, mode="bilinear", align_corners=False)+ parts.append((xfeat.detectAndComputeDense(scaled, k, False), factor, k))+ assert out["keypoints"].shape == (1, 100, 2)+ start = 0+ for single, factor, k in parts:+ self.assert_close(out["keypoints"][:, start : start + k], single["keypoints"] / factor)+ self.assert_close(out["descriptors"][:, start : start + k], single["descriptors"])+ assert (out["scales"][:, start : start + k] == 1 / factor).all()+ start += k++ def test_convention_xfeat_dense_keeps_the_top_k_cells_capped_by_the_cells_of_each_scale(self, device, dtype):+ # each extraction keeps its top_k cells, or every cell when there are fewer or top_k < 1; multiscale=True gives+ # the 0.6 and 1.3 extractions int(0.2 * top_k) and int(0.8 * top_k). A 64 x 64 image has 16 cells at 0.6+ # (resized to 32 x 32) and 64 at 1.3 (64 x 64), so a share above them is capped, and 9 gives 1 + 7 = 8.+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ counts = {k: xfeat.detectAndComputeDense(image, k)["keypoints"].shape[1] for k in (0, 5, 9, 10, 20, 100, 4096)}+ assert counts == {0: 80, 5: 5, 9: 8, 10: 10, 20: 20, 100: 80, 4096: 80}+ single = {k: xfeat.detectAndComputeDense(image, k, False)["keypoints"].shape[1] for k in (-1, 0, 1, 7, 100)}+ assert single == {-1: 64, 0: 64, 1: 1, 7: 7, 100: 64}++ def test_wart_xfeat_dense_multiscale_keeps_every_cell_of_a_zero_share_5924(self, device, dtype):+ # a share int(0.2 * top_k) or int(0.8 * top_k) that rounds down to 0 reaches the "top_k < 1 keeps every cell"+ # rule, so a top_k from 1 to 4 returns all 16 cells of the 0.6 extraction, and 1 those of both scales+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ counts = {k: xfeat.detectAndComputeDense(image, k)["keypoints"].shape[1] for k in (1, 2, 4)}+ assert counts == {1: 16 + 64, 2: 16 + 1, 4: 16 + 3}++ def test_convention_xfeat_model_reads_the_channel_mean_through_an_instance_norm(self, device, dtype):+ # XFeatModel averages the channels and instance-normalises the result (model.py of verlab/accelerated_features+ # e92685f), so any channel count is accepted and an affine change a x + b of the intensities with a > 0 leaves+ # the outputs unchanged, up to the norm's eps, unless the image's variance is close to eps.+ tol = {torch.float16: 2e-3, torch.bfloat16: 6e-3}.get(dtype, 1e-4)+ with torch.random.fork_rng(devices=[]):+ torch.manual_seed(0)+ model = XFeatModel().eval()+ rgb = torch.rand(1, 3, 72, 104)+ model = model.to(device, dtype)+ rgb = rgb.to(device, dtype)+ gray = rgb.mean(dim=1, keepdim=True)+ with torch.no_grad():+ reference = model(rgb)+ for variant in (gray, gray.expand(1, 5, 72, 104), rgb.flip(1)):+ for out, ref in zip(model(variant), reference):+ self.assert_close(out, ref, rtol=0.0, atol=1e-6 if tol == 1e-4 else tol)+ # torch 2.5.1's CPU float16 instance norm overflows on a [0, 255] image, so float16 scales by 16 instead+ scale = 16.0 if dtype == torch.float16 else 255.0+ for variant in (2.0 * rgb + 1.0, scale * rgb):+ for out, ref in zip(model(variant), reference):+ self.assert_close(out, ref, rtol=0.0, atol=tol)+ # not every change is invisible: squaring the image moves the keypoint logits+ assert (model(rgb**2)[1] - reference[1]).abs().max() > 0.02+ # nor is the gain at low contrast, where the variance of the channel mean (about 3e-7 here) is below eps+ low = 0.003 * rgb+ assert (model(scale * low)[1] - model(low)[1]).abs().max() > 0.02++ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])+ def test_convention_interpolate_sparse2d_reads_position_p_at_map_coordinate_p_times_map_size_over_size_minus_one(+ self, device, dtype, mode+ ):+ # pos (x, y) on an H x W image reads the h x w map at (x * w / (W - 1) - 0.5, y * h / (H - 1) - 0.5) in the+ # map's pixel frame: normgrid's 2 p / (W - 1) - 1 sampled with align_corners=False (the formula of+ # verlab/accelerated_features e92685f, InterpolateSparse2d). align_corners is stored and not used. A ramp map+ # reads back that coordinate bilinearly, and its nearest pixel with mode="nearest"; the default bicubic kernel+ # does not reproduce a ramp exactly, but reads at the same coordinate. Half precision is checked to one unit in+ # the last place at the largest value read (below 8).+ if mode == "bilinear" and not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip("This device does not support bilinear interpolation for 2D grid_sample")+ if mode == "nearest" and not supports_nearest_2d_grid_sample(device, dtype):+ pytest.skip("This device does not support nearest interpolation for 2D grid_sample")+ h, w, H, W = 8, 12, 64, 96+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ ramp = torch.stack([xx, yy])[None] # channel 0: column, channel 1: row+ pos = torch.tensor([[[22.0, 13.0], [60.0, 41.0], [33.25, 20.75]]], dtype=torch.float64)+ read = pos * torch.tensor([w / (W - 1), h / (H - 1)], dtype=torch.float64) - 0.5+ # read[0] = [[2.278947, 1.150794], [7.078947, 4.706349], [3.7, 2.134921]]+ expected = read if mode == "bilinear" else read.round()+ tol = {torch.float16: 2.0**-8, torch.bfloat16: 2.0**-5}.get(dtype, 1e-4)+ for align_corners in (False, True):+ interp = InterpolateSparse2d(mode, align_corners=align_corners)+ out = interp(ramp.to(device, dtype), pos.to(device, dtype), H, W)+ self.assert_close(out.cpu().double(), expected, rtol=0.0, atol=tol)+ # relabelling: the transposed map and swapped positions read the swapped coordinates+ out_t = interp(ramp.flip(1).transpose(-1, -2).to(device, dtype), pos.flip(-1).to(device, dtype), W, H)+ self.assert_close(out_t.cpu().double(), expected.flip(-1), rtol=0.0, atol=tol)++ @pytest.mark.parametrize("sampler", ["InterpolateSparse2d", "ALIKED", "SOLD2"])+ def test_wart_samplers_send_cpu_half_maps_to_the_half_grid_sample_5810(self, device, dtype, sampler):+ # torch's CPU float16 / bfloat16 grid_sample returns wrong values, NaN and overflow on sparse grids into larger+ # maps (#5810), and torch 2.5.1 has no such kernel. XFeat's InterpolateSparse2d, ALIKED (DKD scores and SDDH+ # descriptors) and SOLD2.match call it with the half map and grid directly;+ # kornia.core.utils._torch_grid_sample, which the warps use, samples CPU half in float32 instead.+ if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("the defect is in the CPU float16 / bfloat16 path")+ if sampler == "ALIKED" and not supports_replicate_padding(device, dtype):+ pytest.skip("ALIKED pads with replication, absent for this dtype")+ from kornia.feature import ALIKED, SOLD2++ calls = []++ class GridSampleRecorder(TorchFunctionMode):+ # Records the dtypes that reach grid_sample and samples in float32, so that the pipeline runs on every+ # torch. It is a mode rather than a monkeypatch of torch.nn.functional.grid_sample: while another function+ # mode is active, grid_sample re-dispatches through its module attribute, so a patched recorder would also+ # see its own float32 call.+ def __torch_function__(self, func, types, args=(), kwargs=None):+ kwargs = kwargs or {}+ if func is not torch.nn.functional.grid_sample:+ return func(*args, **kwargs)+ source, grid, *rest = args+ calls.append((source.dtype, grid.dtype))+ return func(source.float(), grid.float(), *rest, **kwargs).to(source.dtype)++ with torch.no_grad(), GridSampleRecorder():+ if sampler == "InterpolateSparse2d":+ InterpolateSparse2d()(+ torch.rand(1, 8, 8, 12, dtype=dtype), torch.tensor([[[22.0, 13.0]]], dtype=dtype), 64, 96+ )+ elif sampler == "ALIKED":+ ALIKED(model_name="aliked-t16").to(dtype=dtype).eval()(torch.rand(1, 3, 64, 96, dtype=dtype))+ else:+ segments = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]])+ maps = torch.rand(2, 1, 128, 24, 32, dtype=dtype)+ SOLD2(pretrained=False).match(segments, segments + 1.0, maps[0], maps[1])+ assert calls+ assert set(calls) == {(dtype, dtype)}