Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): stop MultiResolutionDetector fabricating detections, honour its mask, keep its dtype (#4098)

Dmytro Mishkina1919354a8a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2bd49e968..52034cbf4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
now emits a `TracerWarning` about converting a tensor to a Python boolean that it did not emit before. The guard
is a static check and the traced graph is unchanged β€” the warning is noise, not a correctness signal.
+* `MultiResolutionDetector` and `KeyNetDetector` change their output: padded slots now read as a zero response and
+ a zero LAF instead of `torch.finfo(dtype).min / 2` and an arbitrary border coordinate; the previously inert `mask`
+ argument now suppresses detections, and must be `(1 or B, 1, H, W)` at the image size -- a `(B, H, W)` mask
+ passed directly to either detector, which was accepted only because it went unread, is rejected; half-precision
+ input yields half-precision LAFs; the returned shape is always `num_features`; a multi-channel response is rejected instead of
+ producing invalid or duplicate LAFs; a negative `score_threshold` is rejected with `ValueError`; and `detect`
+ enforces its documented `(1, C, H, W)` input. The `mask` of both detectors is now "where a detection may be": a
+ boolean or integer mask is binary (a 0/255 mask no longer scales the responses by 255), a floating-point mask
+ weights the scores, it is resampled conservatively so a thin zero region survives the coarse levels, and it is
+ applied to the non-maxima-suppression output, so its edge cannot manufacture maxima (#4102). A mask whose dtype
+ differs from the image no longer promotes the response dtype, and a mask that is not `(1 or B, 1, H, W)` for the
+ image is rejected instead of stretched or broadcast onto the wrong axis -- that includes an image-shaped
+ `(1, C, H, W)` mask and a coarse `(N, H/8, W/8)` one, which `LocalFeatureMatcher` used to accept and silently
+ ignore (the old docstring said "same shape as the input image") and now forwards to the detector's check.
+ `ScaleSpaceDetector` additionally stops returning its own top-K sentinel as a detection for a batch, no longer
+ returns a frame for a candidate its border check rejected, and re-checks a sub-pixel-refined centre against the
+ mask; a short result is sorted in both detectors. `detect_features_on_single_level`'s new `mask` parameter is
+ keyword-only, and it now requires the response map to have the level's spatial size: a valid-convolution
+ response net that returned a smaller map had every keypoint decoded one pixel off its peak, since a response
+ index is read as a level pixel with no offset, and is rejected with a message rather than silently misplaced.
+ See the entry under **Bug fixes** (#4089, #4090, #4091) for the details and the
+ migration.
+
+* `MKDDescriptor` runs in `float16` and `bfloat16`. Its gradient-embedding and spatial-encoding stages were held in
+ a plain `dict`, so `.to(device, dtype)` never reached their buffers and a half-precision input failed at the
+ whitening matmul with `expected m1 and m2 to have the same dtype`. They are now an `nn.ModuleDict`; float32 and
+ float64 outputs are byte-identical, and `state_dict()` gains the stages' buffer keys (`feats.<parametrization>.*`).
+ A state dict saved by an earlier release still loads with `strict=True`: those buffers are derived from the
+ constructor arguments, and when a state dict has no `feats.*` key at all they are filled in from the module being
+ loaded into (one that has some and lost one is reported by `strict=True`, as for any other missing key). The
+ reverse is not covered: a state dict saved by this release carries the `feats.*` keys and fails `strict=True` on
+ an earlier kornia, which does not know them; load it with `strict=False` there.
+
+* `DescriptorMatcherWithSteerer(normalize=True)`, `DiscreteSteerer.steer_descriptions(normalize=True)` and the
+ `MKD` descriptors, like `SIFTDescriptor` and `HardNet`, L2-normalise a float16 input in float32 and cast back,
+ so an all-zero float16 descriptor normalises to zero instead of NaN (the 1e-12 guard underflows in float16) and a
+ descriptor whose norm sits below the smallest float16 normal still normalises to one rather than being clamped.
+ `PatchDominantGradientOrientation`, and with it `LAFOrienter`, take the gradient magnitude and orientation of a
+ float16 patch through the same float32 step `SIFTDescriptor` uses, so a flat patch yields a finite angle instead
+ of a NaN LAF -- which reached a *filled* detection slot in a float16 `SIFTFeature` pipeline and poisoned that
+ descriptor row. `SIFTDescriptor(rootsift=True)` and `DenseSIFTDescriptor(rootsift=True)`
+ compute the RootSIFT square root in float32 for a float16 input: the float16-representable guard would have
+ read every empty bin as `sqrt(6.1e-5)` and biased the descriptor norm to ~1.004. Float32 and float64 outputs are
+ unchanged.
+
+* `LocalFeatureMatcher` no longer matches the zero-LAF slots with which a fixed-shape detector pads an under-filled
+ result, and now forwards its documented `mask0`/`mask1` inputs to feature extraction. `nn` and `mnn` callers can
+ therefore receive fewer correspondences: identical descriptors sampled at padded origin frames are no longer
+ reported as matches. Three-dimensional `(B, H, W)` masks keep working and are promoted to the detectors'
+ `(B, 1, H, W)` form; four-dimensional masks are forwarded unchanged. Because the masks now reach the detector,
+ they are subject to its check: a mask that is not at the image's spatial size, which used to be ignored, is
+ rejected. A floating-point mask changes meaning in `ScaleSpaceDetector`-based pipelines too, see below.
+
### Bug fixes
* Make `guided_blur` / `GuidedBlur` work in `float16` and `bfloat16` when the guidance has more than one channel.
@@ -187,6 +240,169 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
matchers `nn` and `mnn` goes at least down to -1 on unit-norm descriptors, and is unbounded below for arbitrary
ones.
+* Stop `MultiResolutionDetector` (and therefore `KeyNetDetector`) fabricating detections, honour its `mask` argument,
+ and keep its LAFs in the input dtype (#4089, #4090, #4091).
+
+ **Padded slots are zero, and the shape is always `num_features`.** `detect_features_on_single_level` masked every
+ non-candidate position to `torch.finfo(dtype).min / 2` and then ran `topk` with `k` clamped against the *pixel
+ count* rather than the number of surviving candidates. Once a pyramid level ran out of above-threshold maxima,
+ `topk` could no longer rank -- every remaining position carried the same sentinel -- so it returned an arbitrary
+ tie-break subset, in practice the low flat indices, which is exactly the border strip `remove_borders` had just
+ zeroed. `MultiResolutionDetector(BlobHessian(), num_features=100)` on a plain `64x64` image returned 70 of its 100
+ features that way, each with a response of `-1.7e38` and a real-looking coordinate. Those slots are now padded
+ with a zero response and a zero LAF, which is what `ScaleSpaceDetector.detect` already does for a short result,
+ and `forward` re-applies that padding after the affine-shape and orientation modules, which would otherwise
+ normalise a zero frame into a finite one. `detect` also only ever *trimmed* an over-long result, so a level
+ capped at its own pixel count, or a per-level quota rounded down to zero, produced a short one: a one-level `8x8`
+ image asking for 100 features returned 64, and the default configuration asking for 1 feature returned **0**,
+ which made `lafs[0, 0]` raise. The result is now padded up to `num_features` with the same zero response and
+ zero LAF. Callers that tested for the sentinel (`resp < 0`) should test `resp == 0`; callers that consumed the
+ responses as scores no longer need to.
+
+ **`num_features=1` returns a real detection.** The per-level quotas each truncate independently, and at
+ `num_features=1` the six default shares are `0.508 .. 0.016`, so every one of them rounded to zero and no level
+ was asked for a single candidate. The apportionment now hands its one slot to the level with the largest share
+ whenever truncation would otherwise lose every slot, so `num_features=1` returns the same best feature that
+ `num_features=2` returns first. An apportionment that already gives out a slot is untouched, which with the
+ default configuration is every `num_features >= 2` (verified byte-identical with `torch.equal` over 16 size/count
+ combinations).
+
+ **The `mask` argument works, and means "where a detection may be".** `forward(img, mask)` and `detect(img, mask)`
+ accepted a `mask`, documented it as "a mask with weights where to apply the response function", and ignored it --
+ an all-zero mask returned bit-identical output. Anyone who was passing a mask and silently getting unmasked
+ detections now gets masked ones. The semantics are the same in both detectors and are chosen from the caller's
+ side. A boolean or integer mask is binary: any non-zero value keeps a position, so a 0/1 mask, an OpenCV 0/255
+ mask and `img > 0` all mean the same thing (a raw cast would have multiplied the responses by 255 and defeated an
+ absolute `score_threshold`). A floating-point mask is used as weights on the detection scores: a weight in
+ `(0, 1]` scales a score toward the worst -- a non-negative score is multiplied by it, a negative one divided -- so
+ a down-weighted candidate never outranks a full-weight one with an at-least-as-good score (a plain multiply pulled
+ a negative score toward zero, i.e. *up* the ranking of a signed response), and a zero or negative weight
+ suppresses. The weights are cast to the image dtype, so a weight a half-precision image cannot hold rounds to
+ zero and suppresses, and clamped to one, so a float 0/255 mask (an OpenCV mask through `.astype(np.float32)`)
+ means what the integer one means rather than scaling every score by 255. The weighting runs in float32 for
+ half-precision input and is bounded at the dtype's most negative finite value, so a negative score divided by a
+ small weight cannot overflow to `-inf`; an unfilled slot is ranked with `-inf` (not a finite sentinel such as
+ `finfo.min / 2`, which a genuine extreme response could sort below, and did: four float32 maxima at `-2e38`
+ were returned for a single image and dropped for a batch), so every finite detection precedes the padding. The
+ mask is checked at the integer maximum and again at the sub-pixel-refined centre, conservatively (every octave
+ pixel the centre touches), so the refinement cannot carry a detection into the zero region. A NaN weight
+ suppresses rather than winning the ranking. The mask must be `(1 or B, 1, H, W)` with the
+ image's spatial size. It is resampled onto every pyramid level or octave with a
+ min-pool rather than an interpolation, so a zero region suppresses every level pixel it touches and a two-pixel
+ zero stripe does not vanish at a factor-four level. And it is applied to the non-maxima-suppression output, not
+ to the response the suppression reads: multiplying the response first carves an edge into it, and the bilinear
+ ramp of that edge was a "maximum" on the suppressed side, so a blob wholly inside the zero region was still
+ detected (#4102). `ScaleSpaceDetector`, which did multiply its response per octave, takes the same path; its
+ detections inside the region kept by a binary mask are unchanged. A *floating-point* mask used to weight the
+ response before the non-maxima suppression and the sub-pixel refinement, so a graded mask moved maxima and
+ their refined positions; it now weights only the score of a maximum found in the unweighted response, so the
+ set of candidates and their positions are those of the unmasked image and the weight decides their rank.
+
+ `LocalFeatureMatcher` now carries those masks through the full extraction-and-matching path. It documented
+ `mask0`/`mask1` as `(B, H, W)` inputs but never passed either to its local feature module; that historical shape is
+ accepted by adding the singleton channel, and the detectors' `(B, 1, H, W)` form is also accepted directly.
+
+ **A mask no longer changes the response dtype.** It is resampled *and cast* onto the response map, where the
+ multiplication used to promote it, so a `float16` image with a `float32` mask returned `float32` responses beside
+ `float16` LAFs. This also applies to `ScaleSpaceDetector`, which shares the resampling helper: a `float32` image
+ with a `float64` mask used to return `float64` and now returns `float32`, i.e. the image dtype, in both detectors.
+ `ScaleSpaceDetector` gains the same shape check, and accepts a boolean or integer mask through the same helper
+ (it raised on one before). It resampled a mask of any size onto its octaves without complaint, so a stale mask
+ from before a resize, or a transposed one, was silently stretched onto the wrong geometry, and a multi-channel
+ mask was broadcast over the scale levels rather than the channels -- an error when the counts differed, the wrong
+ weighting when they matched. Both detectors now require `(1 or B, 1, H, W)`.
+
+ **`ScaleSpaceDetector` no longer leaks its own top-K sentinel for a batch.** For `B > 1` the per-octave top-K
+ ranks over the whole scale-space volume with non-candidates masked to `torch.finfo(dtype).min / 2`, and an image
+ with fewer maxima than requested got those sentinels back as detections: `ScaleSpaceDetector()` on
+ `torch.zeros(2, 1, 32, 32)` returned 70 slots per image with a response of `-1.7e38` and an arbitrary LAF, where
+ the same input at `B = 1` returned 500 zeros. Which slots a detection filled is now tracked through the top-K
+ rather than inferred from the response, and an unfilled one -- the sentinel, the padding that tops a short
+ result up to `num_features`, or a candidate whose frame reached outside the image -- carries a zero response and
+ a zero LAF, in `detect` and, after the affine-shape and orientation modules have run, in `forward`, and sorts
+ after every real detection, including a negative one. The mask is deliberately *not* `response == 0`: the
+ response function is pluggable and may be signed, so an exact zero can be a genuine maximum and keeps its frame.
+ The border-rejected candidate is the one visible change at `B = 1`: it used to keep its coordinates beside a
+ zero response, i.e. a keypoint that was never detected, and its scale was often the largest in the result. Both
+ detectors' `forward` read occupancy off the zero LAF, so a subclass overriding `detect` is honoured whole.
+
+ **Half-precision input yields half-precision LAFs.** `detect_features_on_single_level` hardcoded `.float()` on the
+ pixel coordinates, so a `float16`/`bfloat16` image came back with `float32` LAFs beside half-precision responses.
+ The index-to-coordinate arithmetic runs in float32 (float64 for a float64 image) and only the finished coordinate
+ is cast to the input dtype; `float32` and `float64` output is unchanged. A half-precision LAF centre carries the
+ dtype's integer resolution: exact up to 256 in `bfloat16` and up to 2048 in `float16`, then on a 2 px grid up to
+ twice that, 4 px up to four times, and so on -- where the old `float32` LAFs were exact.
+
+ **A detector model must return one spatial response map.** `detect_features_on_single_level` flattened the
+ whole response tensor and decoded the flat top-K index with the width alone, so a candidate from channel `c`
+ landed at `y + c * H`; `BlobHessian` on an RGB image put 56 of 100 LAFs outside a `64x64` frame, up to
+ `y = 179.9`. Merely decoding the channel would still spend the budget on duplicate LAFs -- a grayscale image
+ repeated into RGB returned three copies of almost every feature, whose grayscale descriptors are identical.
+ `MultiResolutionDetector` and `ScaleSpaceDetector` now require their detector model to emit one response channel
+ and fail with a named error otherwise. This does not restrict the model input: a learned detector may consume RGB
+ (or any other channel count) and collapse it to one response map itself, which is the intended color-image path.
+ Single-channel input and response output are unchanged.
+
+ **`score_threshold` must be non-negative**, and `MultiResolutionDetector.__init__` raises `ValueError` otherwise:
+ non-maxima suppression writes an exact zero at every suppressed position, so a negative threshold admitted all of
+ them as detections (with `score_threshold=-1.0` on a `64x64` image, 70 of 100 returned features were suppressed
+ border pixels) and would now also be indistinguishable from the zero response that marks an unfilled slot.
+
+ **`detect` enforces its documented `(1, C, H, W)`.** It is public, and a larger batch was flattened across the
+ batch axis and silently returned coordinates for the wrong image. `forward` already had that guard, so only
+ direct `detect` callers see a difference.
+
+ **A short result is sorted.** `MultiResolutionDetector.detect` only ran its final top-K when the levels had
+ produced *more* slots than `num_features`, so a short result came back in level order with each level's own
+ padding left in place: with `pyramid_levels=2, up_levels=0, num_features=6000` on a `48x48` image the three real
+ detections sat at flat indices 0, 1 and 2304. The ranking is now unconditional, as it is in
+ `ScaleSpaceDetector.detect`, and the zero-response padding sorts to the end.
+
+ **Padding is not a correspondence.** `LocalFeatureMatcher` used to describe and match every fixed-shape slot, so
+ `DescriptorMatcher("nn")` returned every padded origin frame and `mnn` returned one false origin match even when
+ neither image contained a detection. Zero LAFs are honest, but they are also identical, and identical descriptors
+ match each other at zero distance -- with plain nearest-neighbour matching the padded block became the largest
+ consistent set of "correspondences" and captured RANSAC (`SIFTFeature(400)` on two crops of one image: 0.09 px
+ mean reprojection error on `main`, 31 px with the zero LAFs matched, 0.09 px with them dropped). The matcher now
+ filters zero LAFs before matching, and skips a pair when either side has nothing left (`matcher` is an arbitrary
+ module with no obligation to accept a `(0, D)` input); the ratio tests `match_snn` and `match_smnn` reject the
+ block on their own (`match_mnn` and `match_nn` do not: identical zero descriptors are mutual nearest neighbours
+ at distance zero), and
+ `LocalFeature.forward` documents the one-line filter for a hand-rolled `match_nn` pipeline. The feature benchmark
+ does the same before affine/orientation/description, avoiding meaningless descriptor work and the quadratic
+ distance-matrix cost of padded rows; its CUDA timers also synchronize around the measured detector and full
+ matching regions.
+
+* `SIFTDescriptor`, `DenseSIFTDescriptor`, `HardNet` and `HardNet8` return NaN for a constant patch in `float16`,
+ and the SIFT descriptors' backward is NaN in `float16` wherever two neighbouring pixels are equal.
+
+ `F.normalize`'s default `eps` of 1e-12 is not representable in `float16` and rounds to zero, so the
+ `norm.clamp_min(eps)` that exists to stop a zero-norm input becoming `0 / 0` was itself zero in exactly that
+ dtype: an all-zero patch normalised to NaN, while `bfloat16`, `float32` and `float64` were fine. A detector that
+ pads a short result hands the descriptor a zero LAF, which samples one image point repeatedly and produces
+ exactly that patch -- `ScaleSpaceDetector(400)` on a random `64x64` `float16` image gave 365 NaN descriptor rows
+ -- and a NaN descriptor is worse than a meaningless one, because it propagates through `torch.cdist` and poisons
+ the whole matching. The nine `F.normalize` calls in those four modules now go through one helper that
+ normalises a `float16` input in float32 and casts back (an `eps` representable in `float16` is safe but not
+ neutral: a norm in the subnormal window came back as 0.5). `bfloat16`, `float32` and `float64` results are
+ unchanged: they keep the 1e-12 default.
+
+ The forward pass was only half of it. `SIFTDescriptor` and `DenseSIFTDescriptor` guard `sqrt(gx^2 + gy^2 + eps)`
+ and `atan2(gy, gx + eps)` with `eps = 1e-10`, which is zero in `float16` -- and a squared `float16` gradient
+ underflows long before that -- so at every pixel with a zero gradient both sat on their singular point and the
+ input gradient came back NaN (9 of 4096 on ordinary random `32x32` patches). The gradient magnitude and
+ orientation are now computed in float32 for `float16` input and cast back, and the RootSIFT `sqrt` is computed
+ in float32 for `float16` as well. An *exactly* flat patch -- what a zero-LAF padding slot samples -- was the
+ remaining case: the guard gave every zero-gradient pixel a magnitude of `sqrt(eps)`, so a flat patch's
+ descriptor was a unit vector built from `eps` (float32) or a subnormal one (float16) whose `1 / norm` gradient,
+ together with `atan2`'s `1 / eps`, overflowed through the float16 cast into an all-NaN input gradient (and was
+ a meaningless ~1e8 in float32). A zero-gradient pixel now contributes a zero magnitude, a zero vector normalises
+ to zero with a zero gradient (the `eps` clamp's `1 / eps` was never meaningful), and
+ `PatchDominantGradientOrientation` skips its parabolic refinement on an empty or uniform histogram instead of
+ dividing `0 / 0`; a flat patch has a zero SIFT descriptor and a zero input gradient in every dtype. `bfloat16`,
+ whose exponent range holds both the guard and the squares, and the wider dtypes are byte-identical at every
+ pixel whose gradient is not exactly zero; a patch with such pixels (a saturated region) loses their `sqrt(eps)`
+ contribution, a change of at most `1e-5` per pixel before normalisation.
## :rocket: [0.6.11] - 2022-03-28
### :new: New Features
diff --git a/benchmarks/feature/scale_space_detector.py b/benchmarks/feature/scale_space_detector.py
index ea5153067..f4d34c718 100644
--- a/benchmarks/feature/scale_space_detector.py
+++ b/benchmarks/feature/scale_space_detector.py
@@ -182,16 +182,24 @@ class ScaleSpaceExtractor(nn.Module):
@torch.no_grad()
def forward(self, img: torch.Tensor):
+ if img.device.type == "cuda":
+ torch.cuda.synchronize()
t_det0 = time.perf_counter()
lafs, _ = self.detector(img)
if img.device.type == "cuda":
torch.cuda.synchronize()
det_ms = (time.perf_counter() - t_det0) * 1000
- lafs = self.aff(lafs, img)
- lafs = self.ori(lafs, img)
- patches = KF.extract_patches_from_pyramid(img, lafs, self.patch_size)
- B, N, C, H, W = patches.shape
- desc = self.desc(patches.view(B * N, C, H, W)).view(B, N, -1)
+ # Fixed-shape detectors pad an under-filled result with zero LAFs. They are not
+ # features: describing and matching them distorts both quality and end-to-end timing.
+ valid = lafs[0].ne(0).any(dim=-1).any(dim=-1)
+ lafs = lafs[:, valid]
+ # The affine-shape and orientation modules extract patches, which is impossible for zero
+ # frames; a blank or fully masked image skips them and produces a valid (0, D) result,
+ # whose descriptor width the shared helper preserves on the empty path.
+ if lafs.shape[1] > 0:
+ lafs = self.aff(lafs, img)
+ lafs = self.ori(lafs, img)
+ desc = KF.get_laf_descriptors(img, lafs, self.desc, self.patch_size)
return KF.get_laf_center(lafs)[0], desc[0], det_ms
@@ -280,7 +288,8 @@ class KeyNetExtractor(nn.Module):
@torch.no_grad()
def forward(self, img: torch.Tensor):
lafs, _, desc = self.feat(img)
- return KF.get_laf_center(lafs)[0], desc[0], None
+ valid = lafs[0].ne(0).any(dim=-1).any(dim=-1)
+ return KF.get_laf_center(lafs[:, valid])[0], desc[0, valid], None
# ---------------------------------------------------------------------------
@@ -354,10 +363,14 @@ def make_label(method: str, resp: str, subpix: str, desc: str, ori: str, aff: st
@torch.no_grad()
def match_pair(img1, img2, extractor, ransac):
+ if img1.device.type == "cuda":
+ torch.cuda.synchronize()
t0 = time.perf_counter()
kp1, desc1, det_ms1 = extractor(img1)
kp2, desc2, det_ms2 = extractor(img2)
_, idxs = KF.match_snn(desc1, desc2, 0.85)
+ if img1.device.type == "cuda":
+ torch.cuda.synchronize()
ms = (time.perf_counter() - t0) * 1000
det_ms = (det_ms1 + det_ms2) if (det_ms1 is not None and det_ms2 is not None) else None
if idxs.shape[0] < 4:
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 070117c0a..6fa742cc6 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -123,7 +123,7 @@ Detectors
.. autoclass:: ScaleSpaceDetector
- :members: forward
+ :members: forward, detect
.. autoclass:: KeyNetDetector
:members: forward
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 48ae151b5..5b1c63782 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -23,6 +23,7 @@ from dataclasses import asdict, fields, is_dataclass
from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union
import torch
+import torch.nn.functional as F
from torch.linalg import inv_ex
from kornia.core._compat import torch_version_ge
@@ -134,6 +135,33 @@ def _normalize_to_float32_or_float64(dtype: torch.dtype) -> torch.dtype:
return dtype if dtype in (torch.float32, torch.float64) else torch.float32
+def _l2_normalize(input: torch.Tensor, dim: int = 1) -> torch.Tensor:
+ """L2-normalise ``input`` along ``dim`` with :func:`torch.nn.functional.normalize`'s default ``eps``.
+
+ ``normalize`` divides by ``norm.clamp_min(eps)``, and the 1e-12 default underflows to zero in
+ float16, where an all-zero input therefore normalised to NaN. A float16 input is normalised in
+ float32 and cast back. Clamping the norm at the smallest float16 normal instead is safe but not
+ neutral: a vector whose norm sits in the subnormal window -- representable, and computed exactly
+ because the float16 ``norm`` accumulates in float32 -- came back with a norm of 0.5 rather than
+ 1. Every other floating dtype carries the 1e-12 default and is unchanged.
+
+ Args:
+ input: the tensor to normalise.
+ dim: the dimension to normalise along.
+
+ Returns:
+ the normalised tensor, in ``input``'s dtype. An all-zero vector normalises to zero with a
+ zero gradient: a zero vector has no direction, and the gradient of the ``eps`` clamp there,
+ ``1 / eps``, is ~1e12 in float32 and overflows to ``inf`` once cast back to float16. A
+ non-zero vector keeps ``normalize``'s value and gradient.
+ """
+ x = input.float() if input.dtype == torch.float16 else input
+ # `amax` rather than a squared norm, so a tiny non-zero vector cannot underflow into the zero branch.
+ nonzero = x.abs().amax(dim=dim, keepdim=True) > 0
+ out = torch.where(nonzero, F.normalize(x, dim=dim, eps=1e-12), torch.zeros_like(x))
+ return out.to(input.dtype)
+
+
def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:
"""Closed-form inverse for batched 3x3 matrices.
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 24b41e203..8fdefee27 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -18,12 +18,11 @@
from typing import Dict
import torch
-import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.download import hf_url, load_state_dict_from_url
-from kornia.core.utils import is_mps_tensor_safe
+from kornia.core.utils import _l2_normalize, is_mps_tensor_safe
urls: Dict[str, str | list[str]] = {}
urls["hardnet++"] = [
@@ -123,7 +122,9 @@ class HardNet(nn.Module):
x_norm: torch.Tensor = self._normalize_input(input)
x_features: torch.Tensor = self.features(x_norm)
x_out = x_features.view(x_features.size(0), -1)
- return F.normalize(x_out, dim=1)
+ # A constant patch drives the features to zero; the default `eps` is not representable in
+ # float16, where the normalisation would then return NaN.
+ return _l2_normalize(x_out, dim=1)
class HardNet8(nn.Module):
@@ -228,6 +229,7 @@ class HardNet8(nn.Module):
x_features: torch.Tensor = self.features(x_norm)
mean: torch.Tensor = torch.jit.annotate(torch.Tensor, self.mean)
components: torch.Tensor = torch.jit.annotate(torch.Tensor, self.components)
- x_prePCA = F.normalize(x_features.view(x_features.size(0), -1))
+ x_flat = x_features.view(x_features.size(0), -1)
+ x_prePCA = _l2_normalize(x_flat, dim=1)
pca = torch.mm(x_prePCA - mean, components)
- return F.normalize(pca, dim=1)
+ return _l2_normalize(pca, dim=1)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 4d10e8536..cb5c69031 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -23,7 +23,7 @@ from torch import nn
from kornia.color import rgb_to_grayscale
from kornia.constants import pi
-from kornia.core.check import KORNIA_CHECK_LAF
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_LAF
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
@@ -169,14 +169,29 @@ class LocalFeature(nn.Module):
Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
- mask: a mask with weights where to apply the response function.
- The shape must be the same as the input image.
+ mask: a mask saying where a detection may be, shape :math:`(B,1,H,W)` with the spatial size of the
+ image. It is forwarded to the detector unchanged; see the detector for its semantics.
Returns:
- Detected local affine frames with shape :math:`(B,N,2,3)`.
- - Response function values for corresponding lafs with shape :math:`(B,N,1)`.
+ - 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::
+
+ valid = lafs.ne(0).any(-1).any(-1) # (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.
+
"""
lafs, responses = self.detector(img, mask)
lafs = scale_laf(lafs, self.scaling_coef)
@@ -431,8 +446,10 @@ class LocalFeatureMatcher(nn.Module):
Keyword Args:
image0: left image with shape :math:`(N, 1, H1, W1)`.
image1: right image with shape :math:`(N, 1, H2, W2)`.
- mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`.
- mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`.
+ mask0 (optional): left image mask. '0' suppresses detection, with shape
+ :math:`(N, H1, W1)` or :math:`(N, 1, H1, W1)`.
+ mask1 (optional): right image mask. '0' suppresses detection, with shape
+ :math:`(N, H2, W2)` or :math:`(N, 1, H2, W2)`.
Returns:
- ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.
@@ -451,17 +468,37 @@ class LocalFeatureMatcher(nn.Module):
if ("lafs0" not in data.keys()) or ("descriptors0" not in data.keys()):
# One can supply pre-extracted local features
- feats_dict0: Dict[str, torch.Tensor] = self.extract_features(data["image0"])
+ mask0 = data.get("mask0")
+ if mask0 is not None and mask0.dim() == 3:
+ mask0 = mask0.unsqueeze(1)
+ feats_dict0: Dict[str, torch.Tensor] = self.extract_features(data["image0"], mask0)
lafs0, descs0 = feats_dict0["lafs"], feats_dict0["descriptors"]
else:
lafs0, descs0 = data["lafs0"], data["descriptors0"]
if ("lafs1" not in data.keys()) or ("descriptors1" not in data.keys()):
- feats_dict1: Dict[str, torch.Tensor] = self.extract_features(data["image1"])
+ mask1 = data.get("mask1")
+ if mask1 is not None and mask1.dim() == 3:
+ mask1 = mask1.unsqueeze(1)
+ feats_dict1: Dict[str, torch.Tensor] = self.extract_features(data["image1"], mask1)
lafs1, descs1 = feats_dict1["lafs"], feats_dict1["descriptors"]
else:
lafs1, descs1 = data["lafs1"], data["descriptors1"]
+ # The padding mask below is read off the LAFs and applied to the descriptors, so the two
+ # must describe the same features; a mismatch would otherwise surface as an opaque
+ # boolean-index error, or silently mis-associate the matches when every index fits.
+ KORNIA_CHECK(
+ lafs0.shape[:2] == descs0.shape[:2],
+ f"lafs0 and descriptors0 must describe the same features, "
+ f"got {tuple(lafs0.shape)} and {tuple(descs0.shape)}",
+ )
+ KORNIA_CHECK(
+ lafs1.shape[:2] == descs1.shape[:2],
+ f"lafs1 and descriptors1 must describe the same features, "
+ f"got {tuple(lafs1.shape)} and {tuple(descs1.shape)}",
+ )
+
keypoints0: torch.Tensor = get_laf_center(lafs0)
keypoints1: torch.Tensor = get_laf_center(lafs1)
@@ -473,14 +510,32 @@ class LocalFeatureMatcher(nn.Module):
out_lafs1: List[torch.Tensor] = []
for batch_idx in range(num_image_pairs):
- dists, idxs = self.matcher(descs0[batch_idx], descs1[batch_idx])
+ # Fixed-shape detectors represent an unfilled slot with a zero LAF. Do not let the
+ # descriptor sampled at that dummy frame become a correspondence (NN/MNN would match
+ # identical padding at the origin). Occupancy cannot be inferred from the response:
+ # a pluggable signed scale-space response may have a genuine maximum at exactly zero.
+ valid0 = lafs0[batch_idx].ne(0).any(dim=-1).any(dim=-1)
+ valid1 = lafs1[batch_idx].ne(0).any(dim=-1).any(dim=-1)
+ current_descs0 = descs0[batch_idx][valid0]
+ current_descs1 = descs1[batch_idx][valid1]
+ current_keypoints0 = keypoints0[batch_idx][valid0]
+ current_keypoints1 = keypoints1[batch_idx][valid1]
+ current_lafs0 = lafs0[batch_idx][valid0]
+ current_lafs1 = lafs1[batch_idx][valid1]
+
+ # `matcher` is an arbitrary module with no obligation to accept a `(0, D)` input, and a
+ # textureless or fully masked image leaves nothing to match anyway.
+ if current_descs0.shape[0] == 0 or current_descs1.shape[0] == 0:
+ continue
+
+ dists, idxs = self.matcher(current_descs0, current_descs1)
if len(idxs) == 0:
continue
- current_keypoints_0 = keypoints0[batch_idx, idxs[:, 0]]
- current_keypoints_1 = keypoints1[batch_idx, idxs[:, 1]]
- current_lafs_0 = lafs0[batch_idx, idxs[:, 0]]
- current_lafs_1 = lafs1[batch_idx, idxs[:, 1]]
+ current_keypoints_0 = current_keypoints0[idxs[:, 0]]
+ current_keypoints_1 = current_keypoints1[idxs[:, 1]]
+ current_lafs_0 = current_lafs0[idxs[:, 0]]
+ current_lafs_1 = current_lafs1[idxs[:, 1]]
out_confidence.append(1.0 - dists)
batch_idxs = batch_idx * torch.ones(len(dists), device=keypoints0.device, dtype=torch.long)
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 61b82881e..6cb17a916 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -210,6 +210,10 @@ class KeyNetDetector(MultiResolutionDetector):
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+ compile_model: wrap the response function and the non-maxima suppression with :func:`torch.compile`.
+ score_threshold: minimum response for a position to count as a detection. Must be non-negative:
+ non-maxima suppression writes an exact zero at every suppressed position, so a negative
+ threshold would admit all of them.
"""
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 4be067926..8ce612e66 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -18,11 +18,10 @@
from typing import Any, ClassVar, Dict, List, Optional, Tuple
import torch
-import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
-from kornia.core.utils import is_mps_tensor_safe
+from kornia.core.utils import _l2_normalize, is_mps_tensor_safe
from kornia.feature.laf import get_laf_center
from kornia.feature.steerers import DiscreteSteerer
@@ -512,8 +511,8 @@ class DescriptorMatcherWithSteerer(nn.Module):
rot1to2 = None
if normalize:
- desc1 = F.normalize(desc1, dim=-1)
- desc2 = F.normalize(desc2, dim=-1)
+ desc1 = _l2_normalize(desc1, dim=-1)
+ desc2 = _l2_normalize(desc2, dim=-1)
if self.steer_mode == "global":
if subset_size is not None:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 82be3e17b..d3df585e9 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -18,11 +18,11 @@
from typing import Any, Dict, List, Tuple, Union
import torch
-import torch.nn.functional as F
from torch import nn
from kornia.constants import pi
from kornia.core.download import load_state_dict_from_url
+from kornia.core.utils import _l2_normalize
from kornia.filters import GaussianBlur2d, SpatialGradient
from kornia.geometry.conversions import cart2pol
from kornia.geometry.grid import create_meshgrid
@@ -392,7 +392,7 @@ class ExplicitSpacialEncoding(nn.Module):
output = emb1 * self.emb2
output = output.sum(dim=(2, 3))
if self.do_l2:
- output = F.normalize(output, dim=1)
+ output = _l2_normalize(output, dim=1)
return output
def __repr__(self) -> str:
@@ -532,7 +532,7 @@ class Whitening(nn.Module):
x = x - self.mean # Center the data.
x = x @ self.evecs # Apply rotation and/or scaling.
x = torch.sign(x) * torch.pow(torch.abs(x), self.pval) # Powerlaw.
- return F.normalize(x, dim=1)
+ return _l2_normalize(x, dim=1)
def __repr__(self) -> str:
return f"{self.__class__.__name__}(xform={self.xform}, in_dims={self.in_dims}, output_dims={self.output_dims})"
@@ -595,7 +595,9 @@ class MKDDescriptor(nn.Module):
# Initialize cartesian/polar embedding with absolute/relative gradients.
self.odims: int = 0
relative_orientations = {polar_s: True, cart_s: False}
- self.feats = {}
+ # A `ModuleDict`, so that `.to(device, dtype)` reaches the embedding buffers; a plain dict
+ # left them float32 and a half-precision input failed at the whitening matmul.
+ self.feats = nn.ModuleDict()
for parametrization in self.parametrizations:
gradient_embedding = EmbedGradients(patch_size=patch_size, relative=relative_orientations[parametrization])
spatial_encoding = ExplicitSpacialEncoding(
@@ -606,6 +608,12 @@ class MKDDescriptor(nn.Module):
self.odims += spatial_encoding.odims
# Compute true output_dims.
self.output_dims: int = min(output_dims, self.odims)
+ # The stages used to live in a plain dict, so a state dict saved by an earlier release has
+ # no `feats.*` keys at all. Those buffers are derived from the constructor arguments, so a
+ # strict load fills them in from this instance rather than failing on them. A state dict
+ # that has *some* `feats.*` keys was saved by this layout and is left alone, so a strict
+ # load still reports one it lost.
+ self._register_load_state_dict_pre_hook(self._fill_missing_stage_buffers)
# Load supervised(lw)/unsupervised(pca) model trained on training_set.
if self.whitening is not None:
@@ -617,6 +625,13 @@ class MKDDescriptor(nn.Module):
self.odims = self.output_dims
self.eval()
+ def _fill_missing_stage_buffers(self, state_dict: Dict[str, torch.Tensor], prefix: str, *args: Any) -> None:
+ if any(key.startswith(prefix + "feats.") for key in state_dict):
+ return
+ for name, buf in self.named_buffers():
+ if name.startswith("feats."):
+ state_dict[prefix + name] = buf.detach().clone()
+
def forward(self, patches: torch.Tensor) -> torch.Tensor:
"""Compute Multiple Kernel Descriptor (MKD) vectors for image patches.
@@ -646,7 +661,7 @@ class MKDDescriptor(nn.Module):
y = torch.cat(features, dim=1)
# l2-F.normalize.
- y = F.normalize(y, dim=1)
+ y = _l2_normalize(y, dim=1)
# Whiten descriptors.
if self.whitening is not None:
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 35db8e4c9..f8a1188ff 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -28,6 +28,7 @@ from kornia.filters import SpatialGradient, get_gaussian_discrete_kernel1d, get_
from kornia.geometry import rad2deg
from .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientation
+from .siftdesc import _gradient_magnitude_orientation
urls: Dict[str, str | list[str]] = {}
urls["orinet"] = [
@@ -113,8 +114,11 @@ class PatchDominantGradientOrientation(nn.Module):
gx: torch.Tensor = grads[:, :, 0]
gy: torch.Tensor = grads[:, :, 1]
- mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps) * weighting
- ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi
+ # float16 is lifted to float32 inside: the squared gradient of a flat patch underflows
+ # and `sqrt(0 + eps)` with an underflowed `eps` is NaN in the backward and, through
+ # `atan2`, in the forward as well. bfloat16 holds both and takes the plain expression.
+ mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)
+ mag = mag * weighting
o_big = float(self.num_ang_bins) * (ori + 1.0 * pi) / (2.0 * pi)
bo0_big = torch.floor(o_big)
@@ -137,7 +141,10 @@ class PatchDominantGradientOrientation(nn.Module):
left = torch.gather(ang_bins, 1, indices_left.reshape(-1, 1)).reshape(-1)
center = values
right = torch.gather(ang_bins, 1, indices_right.reshape(-1, 1)).reshape(-1)
- c_subpix = 0.5 * (left - right) / (left + right - 2.0 * center)
+ # A flat patch has an empty histogram (a zero-gradient pixel contributes no magnitude), and a
+ # uniform one has no peak: the parabolic refinement is `0 / 0` there, so it is skipped.
+ denom = left + right - 2.0 * center
+ c_subpix = torch.where(denom != 0, 0.5 * (left - right) / denom, torch.zeros_like(denom))
angle = -((2.0 * pi * (indices.to(patch.dtype) + c_subpix) / float(self.num_ang_bins)) - pi)
return angle
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index f57c08e0c..14188ecf3 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -23,7 +23,7 @@ import torch.nn.functional as F
from torch import nn
from typing_extensions import TypedDict
-from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.subpix import (
AdaptiveQuadInterp3d,
ConvQuadInterp3d,
@@ -66,11 +66,124 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_le
return max_coords
-def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:
- r"""Downsample a mask based on the given octave shape."""
- mask_shape = octave_shape[-2:]
- mask_octave = F.interpolate(mask, mask_shape, mode="bilinear", align_corners=False)
- return mask_octave.unsqueeze(1)
+def _resize_mask(mask: torch.Tensor, ref: torch.Tensor) -> torch.Tensor:
+ r"""Resample a full-resolution mask onto ``ref``'s spatial size and dtype, conservatively.
+
+ A mask says where a detection may be. A boolean or integer mask is binary -- any non-zero
+ value keeps a position, so a 0/1 and an OpenCV-style 0/255 mask mean the same thing -- and a
+ floating-point mask is used as weights (see :func:`_weight_scores`). The resample is a
+ min-pool: a level pixel takes the smallest mask value among the source pixels it covers, so a
+ zero region suppresses every level pixel it touches and a thin one cannot fall between the
+ samples of an interpolation. The result is cast to ``ref``'s dtype, so the weighting that
+ follows cannot promote the response map to the mask's dtype; a weight the image dtype cannot
+ hold (below ~6e-8 for a float16 image) rounds to zero and suppresses. Weights above one are
+ clamped to one -- a weight never promotes -- so a float 0/255 mask, an OpenCV mask that went
+ through ``.astype(np.float32)``, means the same as the integer one.
+ """
+ if mask.is_floating_point():
+ m = mask.to(torch.float64 if mask.dtype == torch.float64 else torch.float32).clamp_max(1.0)
+ else:
+ m = mask.ne(0).to(torch.float32)
+ h, w = ref.shape[-2], ref.shape[-1]
+ m = _adaptive_min_pool_1d(m, h, dim=-2)
+ m = _adaptive_min_pool_1d(m, w, dim=-1)
+ return m.to(ref.dtype)
+
+
+def _adaptive_min_pool_1d(m: torch.Tensor, out_size: int, dim: int) -> torch.Tensor:
+ r"""Min-pool ``m`` along ``dim`` onto ``out_size`` samples with :func:`adaptive_max_pool2d`'s windows.
+
+ Output sample ``i`` covers the source samples ``floor(i * n / out_size) .. ceil((i + 1) * n / out_size) - 1``,
+ exactly the window of ``torch.nn.functional.adaptive_max_pool2d``, so the result equals
+ ``-adaptive_max_pool2d(-m)`` on CPU. It is spelled as a gather so that every device pools the same windows:
+ on MPS, ``adaptive_max_pool2d`` returns the wrong shape when the output is larger than the input and pools
+ other windows than CPU when the ratio is not an integer, so the resampled mask, and with it the detections,
+ would depend on the device.
+ """
+ dim = dim % m.dim()
+ n = m.shape[dim]
+ if n == out_size:
+ return m
+ # Window bounds are shape arithmetic, so they are Python constants under `torch.compile`.
+ starts = [(i * n) // out_size for i in range(out_size)]
+ ends = [-((-(i + 1) * n) // out_size) for i in range(out_size)]
+ width = max(e - s for s, e in zip(starts, ends))
+ # (out_size, width) source indices per output sample; the positions past a window's end are
+ # clamped onto its last sample, which is inside the window, so they never change the min.
+ idx = [[min(s + j, e - 1) for j in range(width)] for s, e in zip(starts, ends)]
+ index = torch.tensor(idx, device=m.device, dtype=torch.long).reshape(-1)
+ gathered = m.index_select(dim, index)
+ shape = list(m.shape)
+ shape[dim] = out_size
+ shape.insert(dim + 1, width)
+ return gathered.reshape(shape).amin(dim=dim + 1)
+
+
+def _weight_scores(scores: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
+ r"""Scale detection ``scores`` by ``weights`` toward the worst score, so a weight never promotes.
+
+ A weight in ``(0, 1]`` multiplies a non-negative score and *divides* a negative one: the score
+ moves away from the best in both cases, and a down-weighted candidate can never outrank a
+ full-weight candidate whose unweighted score was at least as good. A plain multiply pulls a
+ negative score toward zero, i.e. up the ranking, which inverted the order of a signed
+ response. Positions with a zero or negative weight are excluded from the candidates before
+ this runs; their divisor is replaced by one so no ``inf`` is produced there.
+
+ The quotient of a negative score and a small weight can leave the dtype's range, and ``-inf``
+ is the sentinel an unfilled slot carries into the ranking, so the arithmetic runs in float32
+ for half-precision input and the result is bounded at ``finfo.min`` of the score dtype before
+ the cast back: a weighted detection is finite and so always stays ahead of the padding. Wider
+ dtypes are unchanged wherever the quotient is representable.
+ """
+ dtype = scores.dtype
+ wide = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ s, w = scores.to(wide), weights.to(wide)
+ divisor = torch.where(w > 0, w, torch.ones_like(w))
+ out = torch.where(s >= 0, s * w, s / divisor)
+ return out.clamp_min(torch.finfo(dtype).min).to(dtype)
+
+
+def _create_octave_mask(mask: torch.Tensor, octave_resp: torch.Tensor) -> torch.Tensor:
+ r"""Resample a mask onto the given octave response map, as ``(B, 1, 1, H, W)``."""
+ return _resize_mask(mask, octave_resp).unsqueeze(1)
+
+
+def _check_mask(mask: torch.Tensor, img: torch.Tensor) -> None:
+ r"""Check that ``mask`` is ``(1 or B, 1, H, W)`` for an image ``(B, C, H, W)``.
+
+ The mask is resampled onto every level, so a mask of another spatial size would be stretched
+ silently onto the wrong geometry -- a stale mask from before a resize, or a transposed one.
+ It must be single-channel: it multiplies a single-channel response per level in
+ :class:`MultiResolutionDetector`, and in :class:`ScaleSpaceDetector` it is broadcast over the
+ scale levels, where a channel axis would land on the level axis instead.
+ """
+ KORNIA_CHECK(mask.dim() == 4 and mask.shape[1] == 1, f"mask must be (1 or B, 1, H, W). Got {tuple(mask.shape)}")
+ KORNIA_CHECK(mask.device == img.device, f"mask device {mask.device} must match the image device {img.device}")
+ KORNIA_CHECK(
+ mask.shape[0] in (1, img.shape[0]),
+ f"mask batch {mask.shape[0]} must be 1 or match the image batch {img.shape[0]}",
+ )
+ KORNIA_CHECK(
+ mask.shape[-2:] == img.shape[-2:],
+ f"mask spatial size {tuple(mask.shape[-2:])} must match the image {tuple(img.shape[-2:])}",
+ )
+
+
+def _zero_unfilled(lafs: torch.Tensor, filled: torch.Tensor) -> torch.Tensor:
+ r"""Replace the LAFs of the slots no detection filled with the zero LAF.
+
+ ``filled`` is a ``(B, N)`` boolean mask of the slots a detection actually filled. The
+ affine-shape and orientation modules normalise a frame, and a zero LAF comes out of
+ :class:`LAFAffineShapeEstimator` as a finite 1e-5-scale frame at the origin, so the mask is
+ re-applied after them. ``where`` rather than a multiply, so a module that returns NaN for a
+ zero frame cannot leak it into the padding.
+
+ Both detectors' ``forward`` read the mask off the LAFs that ``detect`` returns: a zero LAF is
+ the padding contract, and it is the one signal a subclass overriding ``detect`` also honours.
+ The response cannot serve: :class:`ScaleSpaceDetector`'s response function is pluggable and
+ may be signed, so an exact zero there is a legitimate maximum.
+ """
+ return torch.where(filled.view(filled.shape[0], -1, 1, 1), lafs, torch.zeros_like(lafs))
class ScaleSpaceDetector(nn.Module):
@@ -194,27 +307,46 @@ class ScaleSpaceDetector(nn.Module):
num_levels: int,
is_iterative_subpix: bool,
px_size: float,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Process one scale-space octave: response β†’ NMS/subpix β†’ top-K β†’ LAF."""
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Process one scale-space octave: response β†’ NMS/subpix β†’ top-K β†’ LAF.
+
+ Returns the top-K responses, their LAFs, and a boolean mask of the slots a detection
+ actually filled. The batched top-K below ranks over the whole volume and returns its
+ ``fill`` sentinel once the octave runs out of candidates, and the border check rejects
+ candidates after the ranking; the mask is what tells those slots apart from a detection,
+ since the response alone cannot.
+ """
dev = octave.device
- dtype = octave.dtype
B, CH, L, H, W = octave.size()
# Run response function
if self.scale_space_response:
- oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, C, Ldog, H, W)
+ oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, 1, Ldog, H, W)
else:
- oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1)).view(
- B, L, CH, H, W
+ level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1))
+ KORNIA_CHECK(
+ level_resp.dim() == 4
+ and level_resp.shape[0] == B * L
+ and level_resp.shape[1] == 1
+ and level_resp.shape[-2:] == (H, W),
+ "resp_module must return one response map per image with shape "
+ f"({B * L}, 1, {H}, {W}). Got {tuple(level_resp.shape)}",
)
+ oct_resp = level_resp.view(B, L, 1, H, W)
# Reorder to (B, CH, L, H, W) for scale-space NMS
oct_resp = oct_resp.permute(0, 2, 1, 3, 4)
+ KORNIA_CHECK(
+ oct_resp.dim() == 5 and oct_resp.shape[0] == B and oct_resp.shape[1] == 1 and oct_resp.shape[-2:] == (H, W),
+ "resp_module must return one scale-space response channel with shape "
+ f"({B}, 1, L, {H}, {W}). Got {tuple(oct_resp.shape)}. For a multi-channel image, convert it to "
+ "grayscale first or use a response function that reduces the channels to one.",
+ )
+ # Iterative sub-pixel modules flatten the full response volume internally. The
+ # level/channel permutation above is contiguous when CH == 1 (the common path), but
+ # not for a response that preserves multiple channels.
+ oct_resp = oct_resp.contiguous()
scale_sigmas = sigmas_oct[:, : oct_resp.shape[2]]
- if mask is not None:
- oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)
- oct_resp = oct_mask * oct_resp
-
# Always precompute NMS masks in one fused pass.
# - For minima_are_also_good: both masks are needed anyway.
# - Otherwise: max_nms_mask is passed to subpix (skips its internal NMS on GPU)
@@ -223,6 +355,23 @@ class ScaleSpaceDetector(nn.Module):
min_nms_mask: torch.Tensor
max_nms_mask, min_nms_mask = nms3d_minmax(oct_resp)
+ # The mask is applied to the candidates, not to the response the NMS reads: multiplying the
+ # response first would carve a hard edge into it, and every response pixel next to a zeroed
+ # neighbour becomes a "maximum" along that edge. The resampled mask is conservative (see
+ # `_resize_mask`), so a zero region drops every candidate it touches; a weight scales the
+ # score of the candidates it keeps.
+ oct_mask: Optional[torch.Tensor] = None
+ oct_keep: Optional[torch.Tensor] = None
+ if mask is not None:
+ resampled = _create_octave_mask(mask, oct_resp)
+ oct_keep = resampled > 0
+ max_nms_mask = max_nms_mask & oct_keep
+ min_nms_mask = min_nms_mask & oct_keep
+ # A boolean or integer mask resamples to exactly 0/1, and the zeros are already dropped
+ # above, so weighting by it is a no-op over the whole volume; only real weights run.
+ if mask.is_floating_point():
+ oct_mask = resampled
+
if self.minima_are_also_good:
if is_iterative_subpix:
coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)
@@ -239,10 +388,14 @@ class ScaleSpaceDetector(nn.Module):
# (nms3d_minmax already sets the masks False at these positions.)
response_max[:, :, 0] = 0.0
response_max[:, :, -1] = 0.0
+ if oct_mask is not None:
+ response_max = _weight_scores(response_max, oct_mask)
if self.minima_are_also_good:
response_min[:, :, 0] = 0.0
response_min[:, :, -1] = 0.0
+ if oct_mask is not None:
+ response_min = _weight_scores(response_min, oct_mask)
take_min_mask = (response_min > response_max) & min_nms_mask
response_max = torch.where(take_min_mask, response_min, response_max)
coord_max = torch.where(take_min_mask.unsqueeze(2), coord_min, coord_max)
@@ -254,15 +407,22 @@ class ScaleSpaceDetector(nn.Module):
# Sparse top-K: gather the small set of NMS candidates first, then run top-K
# on that (~few-thousand) set instead of the full CHxLxHxW volume (~millions).
# nms3d_minmax guarantees cand_mask is False at scale border levels already.
- mask_flat = cand_mask.view(B, -1) # (B, L*H*W)
- resp_flat = response_max.view(B, -1) # (B, L*H*W)
- coord_flat = coord_max.view(B, 3, -1).permute(0, 2, 1) # (B, L*H*W, 3)
+ # Response/candidate tensors are (B, C, L, H, W), while coordinates are
+ # (B, C, 3, L, H, W). Move the xyz axis last before flattening so entry i in
+ # every tensor describes the same (channel, scale, y, x) candidate. Responses
+ # are single-channel by the contract checked above, but custom sub-pixel modules
+ # still have to preserve this axis order.
+ mask_flat = cand_mask.reshape(B, -1) # (B, C*L*H*W)
+ resp_flat = response_max.reshape(B, -1) # (B, C*L*H*W)
+ coord_flat = coord_max.movedim(2, -1).reshape(B, -1, 3) # (B, C*L*H*W, 3)
if B == 1:
nms_idx = mask_flat[0].nonzero(as_tuple=True)[0] # (M,)
resp_cands = resp_flat[0][nms_idx] # (M,)
coord_cands = coord_flat[0][nms_idx] # (M, 3)
k_eff = min(num_feats, nms_idx.shape[0])
+ # Only NMS candidates are gathered here, so every returned slot is one.
+ is_cand = torch.ones(1, k_eff, dtype=torch.bool, device=dev)
if k_eff > 0:
resp_flat_best, local_idx = torch.topk(resp_cands, k=k_eff)
max_coords_best = coord_cands[local_idx].unsqueeze(0) # (1, k_eff, 3)
@@ -271,12 +431,17 @@ class ScaleSpaceDetector(nn.Module):
resp_flat_best = resp_flat.new_zeros(1, 0)
max_coords_best = coord_flat.new_zeros(1, 0, 3)
else:
- # Batched fallback: mask non-candidates to -inf so they lose top-K.
- fill = torch.finfo(dtype).min / 2
- resp_masked = resp_flat.masked_fill(~mask_flat, fill)
+ # Batched fallback: mask non-candidates to -inf so they lose top-K to every finite
+ # response. (A finite sentinel such as `finfo.min / 2` is not below every finite
+ # response, and outranked a genuine extreme maximum.)
+ resp_masked = resp_flat.masked_fill(~mask_flat, float("-inf"))
k_eff = min(num_feats, resp_masked.size(1))
resp_flat_best, idxs = torch.topk(resp_masked, k=k_eff, dim=1)
max_coords_best = torch.gather(coord_flat, 1, idxs.unsqueeze(-1).expand(-1, -1, 3))
+ # `topk` cannot rank among the masked-out positions -- they all carry the same
+ # `fill` -- so an image with fewer than `num_feats` maxima gets an arbitrary subset
+ # of non-candidates back. Carry the candidacy of each selected slot forward.
+ is_cand = torch.gather(mask_flat, 1, idxs)
B, N = resp_flat_best.size()
@@ -308,24 +473,41 @@ class ScaleSpaceDetector(nn.Module):
& (cy - half_s >= 5)
& (cy + half_s <= y_max)
)
- resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)
+ if oct_keep is not None:
+ # The mask was checked at the integer NMS site, and the sub-pixel step has since moved
+ # the centre -- across the mask boundary, when the true peak lies just inside the zero
+ # region. Re-check the refined centre against the resampled mask, conservatively: every
+ # octave pixel the centre touches (its floor and ceil in x and y) has to be allowed, as a
+ # zero region already suppresses every candidate within one octave pixel of it.
+ keep_flat = oct_keep.reshape(oct_keep.shape[0], -1) # (1 or B, H*W)
+ if keep_flat.shape[0] != B:
+ keep_flat = keep_flat.expand(B, -1)
+ x0 = cx.floor().long().clamp_(0, w - 1)
+ x1 = cx.ceil().long().clamp_(0, w - 1)
+ y0 = cy.floor().long().clamp_(0, h - 1)
+ y1 = cy.ceil().long().clamp_(0, h - 1)
+ for yy in (y0, y1):
+ for xx in (x0, x1):
+ good_mask = good_mask & torch.gather(keep_flat, 1, yy * w + xx)
+ # A slot is filled by a candidate whose frame lies inside the image and the mask. Everything
+ # else -- a batched top-K sentinel, or a candidate the border or mask check rejects --
+ # carries `-inf` from here so that it loses the cross-octave ranking in `_detect` to every
+ # real detection, however negative; `_detect` zeroes its response and LAF once ranked.
+ filled = is_cand & good_mask
+ resp_flat_best = resp_flat_best.masked_fill(~filled, float("-inf"))
current_lafs.mul_(px_size)
- return resp_flat_best, current_lafs
+ return resp_flat_best, current_lafs, filled
- def detect(
+ def _detect(
self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Detect local features in an image batch.
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Run the detection and also return the boolean mask of the slots a detection filled.
- Args:
- img: Input image tensor with shape `(B, C, H, W)`.
- num_feats: Number of features requested from the detector.
- mask: Optional mask tensor used to restrict valid image locations.
-
- Returns:
- Tuple containing detection scores and local affine frames. Local affine frames are usually shaped `(B, N, 2,
- 3)`, where `N` is the selected feature count.
+ ``forward`` needs the mask after ``aff`` and ``ori`` have run, and it cannot be recovered
+ from the responses, so :meth:`detect` is a two-value view of this.
"""
+ if mask is not None:
+ _check_mask(mask, img)
dev = img.device
dtype: torch.dtype = img.dtype
sp, sigmas, _ = self.scale_pyr(img)
@@ -351,26 +533,59 @@ class ScaleSpaceDetector(nn.Module):
# tables per call, and concurrent CUDA allocations contend for the same
# device memory allocator lock. Tested: sequential β‰ˆ parallel on GPU.
n_oct = len(sp)
- results: List[Tuple[torch.Tensor, torch.Tensor]] = [
+ results: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = [
self._process_octave(
sp[i], sigmas[i], num_feats, mask, rotmat, num_levels, is_iterative_subpix, px_sizes[i]
)
for i in range(n_oct)
]
- # Sort and keep best n across all octaves.
- # Sparse per-octave top-K may yield fewer total candidates than num_feats
- # (e.g. small images with very few NMS maxima). topk then pads with zeros
- # to preserve the shape contract [B, num_feats, ...].
+ # Sort and keep best n across all octaves. Sparse per-octave top-K may yield fewer total
+ # candidates than num_feats (e.g. small images with very few NMS maxima); the result is
+ # padded to preserve the shape contract [B, num_feats, ...]. Every unfilled slot -- the
+ # padding, a batched top-K sentinel, a border- or mask-rejected candidate -- carries `-inf`
+ # through the ranking so that a genuine detection, however negative, still sorts ahead of
+ # it, and is zeroed only afterwards. (`_weight_scores` keeps a weighted score finite.)
responses = torch.cat([r[0] for r in results], 1)
lafs = torch.cat([r[1] for r in results], 1)
+ filled = torch.cat([r[2] for r in results], 1)
n_candidates = responses.size(1)
if n_candidates < num_feats:
pad = num_feats - n_candidates
- responses = F.pad(responses, (0, pad))
+ responses = F.pad(responses, (0, pad), value=float("-inf"))
lafs = F.pad(lafs, (0, 0, 0, 0, 0, pad))
+ filled = F.pad(filled, (0, pad))
responses, idxs = torch.topk(responses, k=num_feats, dim=1)
lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).expand(-1, -1, 2, 3))
+ filled = torch.gather(filled, 1, idxs)
+ responses = torch.where(filled, responses, torch.zeros_like(responses))
+ return responses, _zero_unfilled(lafs, filled), filled
+
+ def detect(
+ self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Detect local features in an image batch.
+
+ Args:
+ img: Input image tensor with shape `(B, C, H, W)`.
+ num_feats: Number of features requested from the detector.
+ mask: Optional mask with shape `(1 or B, 1, H, W)` saying where a detection may be. A boolean or integer
+ mask is binary (any non-zero value keeps a position), a floating-point mask is used as weights on the
+ detection scores: a weight in `(0, 1]` scales a score toward the worst (a non-negative score is
+ multiplied by it, a negative one divided), so a down-weighted candidate never outranks a full-weight
+ one, and a zero or negative weight suppresses. Weights above one are clamped to one, so a float
+ 0/255 mask means what the integer one means. The weights are cast to the image dtype. The mask is
+ resampled onto every octave conservatively, so a zero region suppresses every candidate within one
+ octave pixel of it.
+
+ Returns:
+ Tuple containing detection scores and local affine frames, shaped `(B, num_feats)` and `(B, num_feats,
+ 2, 3)`. A slot that no detection filled -- there were fewer candidates than requested, or a candidate's
+ frame reached outside the image -- carries a zero response and a zero LAF, and sorts after every real
+ detection. The converse does not hold: a signed response function can peak at exactly zero, and that
+ slot keeps its frame.
+ """
+ responses, lafs, _ = self._detect(img, num_feats, mask)
return responses, lafs
def forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -381,18 +596,23 @@ class ScaleSpaceDetector(nn.Module):
Args:
img: image to extract features with shape [BxCxHxW]
- mask: a mask with weights where to apply the response function. The shape must be the same as
- the input image.
+ mask: a mask saying where a detection may be, shape [1x1xHxW] or [Bx1xHxW]. A boolean or integer mask
+ is binary, a floating-point mask weights the detection scores; see :meth:`detect`.
Returns:
- lafs: shape [BxNx2x3]. Detected local affine frames.
- responses: shape [BxNx1]. Response function values for corresponding lafs
+ Tuple of ``lafs`` with shape [BxNx2x3], the detected local affine frames, and ``responses`` with shape
+ [BxN], the response function values for the corresponding lafs. When an image yields fewer maxima than
+ ``num_features``, the remaining slots hold a zero response and a zero LAF, whichever affine-shape and
+ orientation modules are configured.
"""
+ # `detect` is the public extension point used by subclasses. Infer occupancy from its
+ # zero-LAF padding contract rather than bypassing an override through `_detect`.
responses, lafs = self.detect(img, self.num_features, mask)
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
lafs = self.aff(lafs, img)
lafs = self.ori(lafs, img)
- return lafs, responses
+ return _zero_unfilled(lafs, filled), responses
class Detector_config(TypedDict):
@@ -431,6 +651,10 @@ class MultiResolutionDetector(nn.Module):
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+ compile_model: wrap the response function and the non-maxima suppression with :func:`torch.compile`.
+ score_threshold: minimum response for a position to count as a detection. Must be non-negative:
+ non-maxima suppression writes an exact zero at every suppressed position, so a negative
+ threshold would admit all of them.
"""
@@ -453,6 +677,11 @@ class MultiResolutionDetector(nn.Module):
self.scale_factor_levels = config["scale_factor_levels"]
self.mr_size = config["s_mult"]
self.nms_size = config["nms_size"]
+ if score_threshold < 0:
+ # Non-maxima suppression encodes a suppressed position as an exact zero, so a
+ # negative threshold admits every suppressed pixel in the image as a "detection"
+ # and collides with the zero response that marks an unfilled slot.
+ raise ValueError(f"score_threshold must be non-negative. Got {score_threshold}")
self.score_threshold = score_threshold
nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))
self.num_features = num_features
@@ -481,53 +710,127 @@ class MultiResolutionDetector(nn.Module):
return mask * score_map
def detect_features_on_single_level(
- self, level_img: torch.Tensor, num_kp: int, factor: Tuple[float, float]
+ self,
+ level_img: torch.Tensor,
+ num_kp: int,
+ factor: Tuple[float, float],
+ *,
+ mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Detect keypoints on one image-pyramid level.
+ The response function may consume a multi-channel image -- for example, a learned color detector -- but must
+ return one response map. A LAF has no response-channel identity, so independent per-channel detections are
+ ambiguous and rejected. :class:`ScaleSpaceDetector` follows the same contract.
+
Args:
level_img: Image tensor for a single pyramid level.
num_kp: Number of keypoints requested from this pyramid level.
factor: Scale factor mapping coordinates from the current pyramid level back to the original image
resolution.
+ mask: Optional mask with shape :math:`(1, 1, H, W)` at the *original* image resolution, saying where a
+ detection may be. It is resampled onto this level conservatively and applied to the non-maxima
+ suppression output, so a zero region drops every maximum within one level pixel of it and a
+ floating-point weight scales the score. Keyword-only.
Returns:
- Tuple containing scores and local affine frames detected at the requested pyramid level.
+ Tuple containing scores and local affine frames detected at the requested pyramid level, with
+ ``min(num_kp, H * W)`` slots. When the level holds fewer above-threshold maxima than that, the remaining
+ slots are padded with a zero response and a zero LAF.
"""
- det_map = self.nms(self.remove_borders(self.model(level_img)))
- _, _, _h, w = det_map.shape
- det_flat = det_map.view(-1) # (H*W,) β€” B=1, C=1 guaranteed by MultiResolutionDetector
+ resp_map = self.model(level_img)
+ KORNIA_CHECK(
+ resp_map.dim() == 4 and resp_map.shape[0] == 1 and resp_map.shape[1] == 1,
+ f"model must return one response map with shape (1, 1, H, W). Got {tuple(resp_map.shape)}. "
+ "For a multi-channel image, convert it to grayscale first or use a response function that "
+ "reduces the channels to one map.",
+ )
+ # A response index is decoded as a level pixel with no offset or stride, so a map of another
+ # size -- a valid-convolution net -- would put every keypoint off its peak and have the mask
+ # resampled onto the wrong geometry. Nothing can infer the offset from the shape.
+ KORNIA_CHECK(
+ resp_map.shape[-2:] == level_img.shape[-2:],
+ f"model must return a response map with the level's spatial size {tuple(level_img.shape[-2:])}. "
+ f"Got {tuple(resp_map.shape[-2:])}; pad the response function so that its output matches its input.",
+ )
+ det_map = self.nms(self.remove_borders(resp_map))
+ # The mask is applied to the maxima, not to the response the NMS reads: a hard edge in the
+ # response would turn every pixel beside a zeroed neighbour into a "maximum".
+ if mask is not None:
+ weights = _resize_mask(mask, det_map)
+ # A boolean or integer mask resamples to exactly 0/1: dropping is all it can do. A float
+ # mask is gated the same way `ScaleSpaceDetector` gates its candidates, `weight > 0`, which
+ # also drops a NaN weight: `s * NaN` sorts first in `topk` and would consume a slot.
+ if mask.is_floating_point():
+ det_map = _weight_scores(det_map, weights).masked_fill(~(weights > 0), 0.0)
+ else:
+ det_map = det_map * weights
+ w = det_map.shape[-1]
+ det_flat = det_map.view(-1) # (H*W,)
# Mask out non-maxima (zeroed by NMS) and below-threshold scores, then topk.
# Using masked_fill + topk instead of nonzero: avoids data-dependent output shapes,
# supports score_threshold, and is compatible with torch.compile.
- fill = torch.finfo(det_flat.dtype).min / 2
- det_masked = det_flat.masked_fill(det_flat <= self.score_threshold, fill)
+ det_masked = det_flat.masked_fill(det_flat <= self.score_threshold, float("-inf"))
k = min(num_kp, det_flat.numel())
top_scores, top_flat_idx = torch.topk(det_masked, k=k)
- # Convert flat indices to (y, x) pixel coordinates.
+ # `topk` cannot rank among the masked-out positions β€” they all carry the same `fill` β€”
+ # so once this level runs out of real candidates it returns an arbitrary tie-break subset
+ # of them, in practice the lowest flat indices, i.e. the border strip `remove_borders` has
+ # just zeroed. Neutralise those slots rather than handing the sentinel back: zero response
+ # and zero LAF, which is how `ScaleSpaceDetector.detect` pads a short result.
+ valid = top_scores > self.score_threshold
+ top_scores = torch.where(valid, top_scores, torch.zeros_like(top_scores))
+
+ # Convert flat indices to (y, x) pixel coordinates and project them to the original
+ # resolution. The arithmetic runs in at least float32 -- a half-precision image cannot hold
+ # a pixel index times a scale factor exactly -- and only the finished coordinate is cast
+ # to the image dtype, which is exact for every integer a half-precision type can hold.
yx = torch.stack([top_flat_idx // w, top_flat_idx % w], dim=1) # (k, 2)
-
- fx = level_img.new_tensor([factor[0], factor[1]])
- xy_projected = yx.view(1, k, 2).flip(2).float() * fx
+ wide = torch.float64 if level_img.dtype == torch.float64 else torch.float32
+ fx = torch.tensor([factor[0], factor[1]], device=level_img.device, dtype=wide)
+ xy_projected = (yx.view(1, k, 2).flip(2).to(wide) * fx).to(level_img.dtype)
scale_val = 0.5 * (factor[0] + factor[1]) * self.mr_size
scale = level_img.new_full((1, k, 1, 1), scale_val)
lafs = laf_from_center_scale_ori(xy_projected, scale, level_img.new_zeros(1, k, 1))
+ lafs = lafs * valid.view(1, k, 1, 1).to(lafs.dtype)
return top_scores, lafs
+ def _detect_level(
+ self, level_img: torch.Tensor, num_kp: int, factor: Tuple[float, float], mask: Optional[torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ # `mask` is passed only when there is one, so a subclass that overrides the public method
+ # with the historical three-argument signature keeps working for the unmasked call.
+ if mask is None:
+ return self.detect_features_on_single_level(level_img, num_kp, factor)
+ return self.detect_features_on_single_level(level_img, num_kp, factor, mask=mask)
+
def detect(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
- # Compute points per level
"""Detect local features in an image batch.
Args:
- img: Input image tensor with shape `(B, C, H, W)`.
- mask: Optional mask tensor used to restrict valid image locations.
+ img: Input image tensor with shape `(1, C, H, W)`.
+ mask: Optional mask with shape `(1, 1, H, W)` saying where a detection may be. A boolean or integer
+ mask is binary (any non-zero value keeps a position), a floating-point mask is used as weights on
+ the detection scores: a weight in `(0, 1]` scales a score toward the worst, so a down-weighted
+ maximum never outranks a full-weight one, and a zero or negative weight suppresses. Weights above
+ one are clamped to one, so a float 0/255 mask means what the integer one means. The weights are
+ cast to the image dtype. The mask is resampled onto every pyramid level conservatively, so a zero
+ region suppresses every maximum within one level pixel of it.
Returns:
- Tuple containing detection scores and local affine frames. Local affine frames are usually shaped `(B, N, 2,
- 3)`, where `N` is the selected feature count.
+ Tuple containing detection scores and local affine frames, shaped `(1, num_features)` and
+ `(1, num_features, 2, 3)`. The shape holds even when the image yields fewer above-threshold maxima
+ than requested: those slots carry a zero response and a zero LAF, and sort after every real detection.
+ LAF centres are pixel coordinates cast to the image dtype, so a half-precision image gives centres at
+ that dtype's integer resolution: exact up to 256 in bfloat16 and up to 2048 in float16, and coarser
+ beyond.
"""
+ KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
+ if mask is not None:
+ _check_mask(mask, img)
+ # Compute points per level
num_features_per_level: List[float] = []
tmp = 0.0
factor_points = self.scale_factor_levels**2
@@ -536,7 +839,16 @@ class MultiResolutionDetector(nn.Module):
tmp += factor_points ** (-1 * (idx_level - self.num_upscale_levels))
nf = self.num_features * factor_points ** (-1 * (idx_level - self.num_upscale_levels))
num_features_per_level.append(nf)
- num_features_per_level = [int(x / tmp) for x in num_features_per_level]
+ shares: List[float] = [x / tmp for x in num_features_per_level]
+ num_features_per_level = [int(x) for x in shares]
+ # Each quota truncates independently, so a small `num_features` can round the whole
+ # apportionment to zero: with the default configuration that happens at `num_features=1`,
+ # where the six shares are 0.508 .. 0.016. Every level would then be queried for zero
+ # candidates and the result padded with a dummy, on an image full of real maxima. Hand the
+ # one slot to the level with the largest share. This fires only when truncation lost
+ # everything -- an apportionment that already gives out a slot is left exactly as it was.
+ if self.num_features > 0 and sum(num_features_per_level) == 0:
+ num_features_per_level[max(range(len(shares)), key=shares.__getitem__)] = 1
_, _, h, w = img.shape
img_up = img
@@ -554,7 +866,7 @@ class MultiResolutionDetector(nn.Module):
up_factor_kpts = (float(w) / float(nw), float(h) / float(nh))
img_up = resize(img_up, (nh, nw), interpolation="bilinear", align_corners=False)
- cur_scores, cur_lafs = self.detect_features_on_single_level(img_up, num_points_level, up_factor_kpts)
+ cur_scores, cur_lafs = self._detect_level(img_up, num_points_level, up_factor_kpts, mask)
all_responses.append(cur_scores.view(1, -1))
all_lafs.append(cur_lafs)
@@ -572,14 +884,26 @@ class MultiResolutionDetector(nn.Module):
if idx_level > 0 or (self.num_upscale_levels > 0):
num_points_level = sum(num_features_per_level[: idx_level + 1 + self.num_upscale_levels])
- cur_scores, cur_lafs = self.detect_features_on_single_level(cur_img, num_points_level, factor)
+ cur_scores, cur_lafs = self._detect_level(cur_img, num_points_level, factor, mask)
all_responses.append(cur_scores.view(1, -1))
all_lafs.append(cur_lafs)
responses = torch.cat(all_responses, 1)
lafs = torch.cat(all_lafs, 1)
- if lafs.shape[1] > self.num_features:
- responses, idxs = torch.topk(responses, k=self.num_features, dim=1)
- lafs = torch.gather(lafs, 1, idxs[..., None, None].expand(-1, -1, 2, 3))
+ # The levels can produce fewer slots than requested β€” a level is capped at its own pixel
+ # count, and the per-level quotas round down, to zero for a small `num_features`. Pad up
+ # so the returned shape is always `num_features`, the same way `ScaleSpaceDetector.detect`
+ # does; the padding is the zero response and zero LAF used everywhere else here.
+ if lafs.shape[1] < self.num_features:
+ pad = self.num_features - lafs.shape[1]
+ responses = F.pad(responses, (0, pad))
+ lafs = F.pad(lafs, (0, 0, 0, 0, 0, pad))
+ # Rank unconditionally. The levels are concatenated in level order, and a level that under-
+ # fills its own quota pads in place, so without this a short result interleaves the real
+ # detections with the padding instead of listing them first, unlike every other path here
+ # and unlike `ScaleSpaceDetector.detect`. Detections score strictly above the non-negative
+ # threshold, so they sort ahead of the zero-response padding.
+ responses, idxs = torch.topk(responses, k=self.num_features, dim=1)
+ lafs = torch.gather(lafs, 1, idxs[..., None, None].expand(-1, -1, 2, 3))
return responses, lafs
def forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -590,20 +914,25 @@ class MultiResolutionDetector(nn.Module):
Args:
img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
- because the number of detections is different on each image.
- mask: a mask with weights where to apply the response function. The shape must be the same as
- the input image.
+ because the number of detections is different on each image.
+ mask: a mask saying where a detection may be, shape [1x1xHxW]. A boolean or integer mask is binary, a
+ floating-point mask weights the detection scores; see :meth:`detect`.
Returns:
- lafs: shape [1xNx2x3]. Detected local affine frames.
- responses: shape [1xNx1]. Response function values for corresponding lafs
+ Tuple of ``lafs`` with shape [1xNx2x3], the detected local affine frames, and ``responses`` with shape
+ [1xN], the response function values for the corresponding lafs. When the image yields fewer
+ above-threshold maxima than ``num_features``, the remaining slots hold a zero response and a zero LAF,
+ whichever affine-shape and orientation modules are configured.
"""
KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
responses, lafs = self.detect(img, mask)
+ # Occupancy comes from `detect`'s zero-LAF padding contract, the same way as in
+ # `ScaleSpaceDetector.forward`, so an override of `detect` is honoured as well.
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
lafs = self.aff(lafs, img)
lafs = self.ori(lafs, img)
- return lafs, responses
+ return _zero_unfilled(lafs, filled), responses
_DEFAULT_DETECTOR_CONFIG: Detector_config = {
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 311ff2851..fd70ab417 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -23,6 +23,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.utils import _l2_normalize
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
@@ -38,6 +39,38 @@ def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
return torch.eye(numel).view(numel, kd, ky, kx)
+def _gradient_magnitude_orientation(
+ gx: torch.Tensor, gy: torch.Tensor, eps: float
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Per-pixel gradient magnitude and orientation in ``[2pi, 4pi)``.
+
+ ``eps`` keeps ``sqrt`` and ``atan2`` away from their singular point at a zero gradient, where
+ both have an undefined backward. A float16 input is lifted to float32 for this step: the
+ 1e-10 guard is not representable in float16, and a squared float16 gradient underflows long
+ before that, so a flat pair of pixels -- ordinary with a 10-bit mantissa -- would send NaN
+ into the input gradient. The result is cast back. bfloat16 has float32's exponent range, so
+ both the guard and the squares are representable there and it takes the same expression as
+ float32 and float64.
+
+ A pixel with an exactly zero gradient has no orientation and contributes nothing: its magnitude
+ is zero rather than the guard's ``sqrt(eps)``, and its orientation is ``2pi`` (what the guarded
+ ``atan2`` returns) with a zero derivative rather than ``atan2``'s ``1 / eps``. Both were guard
+ artefacts: the ``sqrt(eps)`` magnitude made a flat patch's descriptor a unit vector built from
+ ``eps`` in float32 and a subnormal one in float16, whose ``1 / norm`` gradient overflowed through
+ the float16 cast into a NaN input gradient. A flat patch now has a zero descriptor and a zero
+ gradient in every dtype; every other pixel is unchanged.
+ """
+ dtype = gx.dtype
+ if dtype == torch.float16:
+ gx = gx.float()
+ gy = gy.float()
+ sq = gx * gx + gy * gy
+ nonzero = sq > 0
+ mag = torch.where(nonzero, torch.sqrt(sq + eps), torch.zeros_like(sq))
+ ori = torch.where(nonzero, torch.atan2(gy, gx + eps) + 2.0 * pi, torch.full_like(sq, 2.0 * pi))
+ return mag.to(dtype), ori.to(dtype)
+
+
def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
r"""Return a weighted pooling kernel for SIFT descriptor.
@@ -183,8 +216,7 @@ class SIFTDescriptor(nn.Module):
gx = grads[:, :, 0]
gy = grads[:, :, 1]
- mag = torch.sqrt(gx * gx + gy * gy + self.eps)
- ori = torch.atan2(gy, gx + self.eps) + 2.0 * pi
+ mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)
mag = mag * self.gk.expand_as(mag).type_as(mag).to(mag.device)
o_big = float(self.num_ang_bins) * ori / (2.0 * pi)
@@ -203,14 +235,30 @@ class SIFTDescriptor(nn.Module):
1,
)
ang_bins = ang_bins.view(B, -1)
- ang_bins = F.normalize(ang_bins, p=2)
+ # A constant patch has an all-zero gradient and therefore a zero-norm descriptor; the
+ # default `eps` is not representable in float16, where it would come back NaN.
+ ang_bins = _l2_normalize(ang_bins, dim=1)
ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))
- ang_bins = F.normalize(ang_bins, p=2)
+ ang_bins = _l2_normalize(ang_bins, dim=1)
if self.rootsift:
- ang_bins = torch.sqrt(F.normalize(ang_bins, p=1) + self.eps)
+ ang_bins = _rootsift(ang_bins, self.eps)
return ang_bins
+def _rootsift(desc: torch.Tensor, eps: float) -> torch.Tensor:
+ r"""L1-normalise and take the square root, the RootSIFT step, with a dtype-safe ``eps``.
+
+ ``sqrt`` has an infinite backward at zero, and most bins of a SIFT histogram are zero, so ``eps`` keeps
+ the gradient finite. A float16 input cannot carry the 1e-10 guard -- it underflows to zero -- and the
+ smallest float16 normal, 6.1e-5, is not neutral: every empty bin would read ``sqrt(6.1e-5) = 0.0078``
+ and push the descriptor norm to ~1.004. The step is therefore computed in float32 for a float16 input
+ and cast back; float32 and float64 inputs take the same expression as before, unchanged.
+ """
+ if desc.dtype == torch.float16:
+ return torch.sqrt(F.normalize(desc.float(), p=1, eps=1e-12) + eps).to(desc.dtype)
+ return torch.sqrt(F.normalize(desc, p=1, eps=1e-12) + eps)
+
+
def sift_describe(
input: torch.Tensor,
patch_size: int = 41,
@@ -343,8 +391,7 @@ class DenseSIFTDescriptor(nn.Module):
# unpack the edges
gx = grads[:, :, 0]
gy = grads[:, :, 1]
- mag = torch.sqrt(gx * gx + gy * gy + self.eps)
- ori = torch.atan2(gy, gx + self.eps) + 2.0 * pi
+ mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)
o_big = float(self.num_ang_bins) * ori / (2.0 * pi)
bo0_big_ = torch.floor(o_big)
@@ -364,8 +411,8 @@ class DenseSIFTDescriptor(nn.Module):
)
out_no_norm = self.PoolingConv(ang_bins)
- out = F.normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))
- out = F.normalize(out, dim=1, p=2)
+ out = _l2_normalize(out_no_norm, dim=1).clamp_(0, float(self.clipval))
+ out = _l2_normalize(out, dim=1)
if self.rootsift:
- out = torch.sqrt(F.normalize(out, p=1) + self.eps)
+ out = _rootsift(out, self.eps)
return out
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index f3541906d..7091e0fb9 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -18,9 +18,10 @@
import math
import torch
-import torch.nn.functional as F
from torch import nn
+from kornia.core.utils import _l2_normalize
+
class DiscreteSteerer(nn.Module):
"""nn.Module for discrete rotation steerers.
@@ -74,7 +75,7 @@ class DiscreteSteerer(nn.Module):
for _ in range(steerer_power):
descriptions = self.forward(descriptions)
if normalize:
- descriptions = F.normalize(descriptions, dim=-1)
+ descriptions = _l2_normalize(descriptions, dim=-1)
return descriptions
@classmethod
diff --git a/testing/base.py b/testing/base.py
index dffaa0a01..7db2093bc 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -137,6 +137,67 @@ def supports_2d_border_padding(device: torch.device) -> bool:
return _supports_2d_border_padding_probe(device.type)
+_UNIMPLEMENTED_KERNEL_MSG = "not implemented for"
+
+
+@cache
+def _supports_replicate_padding_probe(device_type: str, dtype: torch.dtype) -> bool:
+ try:
+ # Allocated outside the `try` below: a device that cannot hold `dtype` at all (MPS and
+ # float64) raises TypeError here, which is still "unsupported" and must not escape a
+ # helper whose whole contract is to return a bool.
+ probe = torch.zeros(1, 1, 2, 2, device=device_type, dtype=dtype)
+ except TypeError:
+ return False
+ try:
+ F.pad(probe, (1, 1, 1, 1), mode="replicate")
+ except RuntimeError as e:
+ if _UNIMPLEMENTED_KERNEL_MSG in str(e):
+ return False
+ raise
+ return True
+
+
+def supports_replicate_padding(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a 2D ``mode="replicate"`` pad kernel for ``dtype``.
+
+ :func:`kornia.filters.spatial_gradient` pads that way, so everything built on it inherits the
+ gap: both SIFT descriptors, and ``BlobHessian`` with the detectors above it. torch 2.5.1 has no
+ float16 CPU ``replication_pad2d`` (bfloat16 is fine), so a test that hardcodes float16 rather
+ than reading the injected dtype fails there on every job. Probed at runtime and cached per
+ (device type, dtype), so it auto-enables once PyTorch fills the kernel in.
+ """
+ return _supports_replicate_padding_probe(device.type, dtype)
+
+
+@cache
+def _supports_grid_sample_probe(device_type: str, dtype: torch.dtype) -> bool:
+ try:
+ probe = torch.zeros(1, 1, 2, 2, device=device_type, dtype=dtype)
+ grid = torch.zeros(1, 2, 2, 2, device=device_type, dtype=dtype)
+ except TypeError:
+ return False
+ try:
+ F.grid_sample(probe, grid, align_corners=False)
+ except RuntimeError as e:
+ if _UNIMPLEMENTED_KERNEL_MSG in str(e):
+ return False
+ raise
+ return True
+
+
+def supports_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a 2D ``grid_sample`` kernel for ``dtype``.
+
+ Patch extraction (:func:`kornia.feature.extract_patches_from_pyramid`, and so every LAF
+ orienter, affine-shape estimator and descriptor pipeline built on it) samples that way.
+ torch 2.5.1 has no float16 or bfloat16 CPU ``grid_sampler_2d``, so a test that hardcodes a
+ half dtype rather than reading the injected one fails there on every job. Probed at runtime
+ and cached per (device type, dtype), like :func:`supports_replicate_padding`.
+ """
+ return _supports_grid_sample_probe(device.type, dtype)
+
+
class BaseTester:
@staticmethod
def assert_close(
diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.py
index dbc4657a6..321045715 100644
--- a/tests/feature/test_hardnet.py
+++ b/tests/feature/test_hardnet.py
@@ -80,3 +80,18 @@ class TestHardNet8(BaseTester):
model = HardNet8().to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(HardNet8().to(patches.device, patches.dtype).eval())
self.assert_close(model(patches), model_jit(patches))
+
+
+class TestHardNetConstantPatchIsFinite(BaseTester):
+ """A constant patch drives the features to zero; the L2 normalisation must not give NaN.
+
+ `F.normalize`'s default eps of 1e-12 rounds to zero in float16, so `0 / 0` reached the
+ descriptor. A detector that pads a short result feeds exactly this patch through a zero LAF.
+ """
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ @pytest.mark.parametrize("model", [HardNet, HardNet8])
+ def test_constant_patch(self, device, desc_dtype, model):
+ patches = torch.zeros(2, 1, 32, 32, device=device, dtype=desc_dtype)
+ out = model().to(device, desc_dtype)(patches)
+ assert torch.isfinite(out).all()
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index b99c1a1a4..d487f5c49 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -41,7 +41,7 @@ from kornia.feature import (
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_replicate_padding
from testing.casts import dict_to
@@ -165,6 +165,22 @@ class TestLocalFeatureMatcherEmptyPath(BaseTester):
assert out["lafs0"][0].shape == (0, 2, 3)
assert out["keypoints0"].shape == (0, 2)
+ def test_an_empty_side_never_reaches_the_matcher(self, device, dtype):
+ # Filtering the zero-LAF padding can leave a side with no descriptor at all. `matcher` is an
+ # arbitrary module with no obligation to accept a `(0, D)` input, so a textureless pair called
+ # it with one and could raise; the pair is skipped instead, which is what `no_match_output` is for.
+ class RejectsEmpty(torch.nn.Module):
+ def forward(self, d0: torch.Tensor, d1: torch.Tensor):
+ if d0.shape[0] == 0 or d1.shape[0] == 0:
+ raise RuntimeError("empty descriptors")
+ return kornia.feature.match_snn(d0, d1, 0.9)
+
+ matcher = kornia.feature.LocalFeatureMatcher(kornia.feature.SIFTFeature(50), RejectsEmpty()).to(device, dtype)
+ img = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ out = matcher({"image0": img, "image1": img})
+ assert out["keypoints0"].shape == (0, 2)
+ assert out["lafs0"].shape == (1, 0, 2, 3)
+
class TestLAFDescriptor(BaseTester):
def test_same(self, device, dtype):
@@ -274,6 +290,24 @@ class TestSIFTFeature(BaseTester):
self.gradcheck(local_feature, img, eps=1e-4, atol=1e-4, fast_mode=False)
+class TestSIFTFeatureHalfPrecision(BaseTester):
+ def test_lafs_and_descriptors_are_finite(self, device):
+ # The orienter's unguarded `sqrt`/`atan2` gave a NaN LAF at a *filled* slot, which the
+ # padding mask cannot cover, and 128 NaN descriptor values in that row with it.
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_replicate_padding(device, torch.float16):
+ pytest.skip("no replicate-padding kernel for float16 on this device")
+ torch.manual_seed(0)
+ img = torch.rand(1, 1, 64, 64, device=device, dtype=torch.float16)
+ with torch.no_grad():
+ lafs, _, descs = SIFTFeature(50).to(device, torch.float16)(img)
+ assert lafs.dtype == torch.float16 and descs.dtype == torch.float16
+ assert int(lafs[0].ne(0).any(dim=-1).any(dim=-1).sum()) > 0
+ assert torch.isfinite(lafs).all()
+ assert torch.isfinite(descs).all()
+
+
class TestKeyNetHardNetFeature(BaseTester):
# The real test is in TestLocalFeatureMatcher
def test_smoke(self, device, dtype):
@@ -310,6 +344,49 @@ class TestLocalFeatureMatcher(BaseTester):
matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("snn", 0.8)).to(device)
assert matcher is not None
+ @pytest.mark.parametrize("match_type", ["nn", "mnn"])
+ def test_detector_padding_is_not_matched(self, device, dtype, match_type):
+ # A fixed-shape detector with no maxima returns zero LAFs. Their descriptors are finite,
+ # but NN/MNN would otherwise report them as false correspondences at the image origin.
+ feat = SIFTFeature(8, upright=True, score_threshold=1e6).to(device, dtype)
+ matcher = LocalFeatureMatcher(feat, DescriptorMatcher(match_type, 0.8)).to(device, dtype)
+ image0 = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ image1 = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ with torch.no_grad():
+ out = matcher({"image0": image0, "image1": image1})
+ assert out["keypoints0"].shape == (0, 2)
+ assert out["keypoints1"].shape == (0, 2)
+ assert out["lafs0"].shape == (1, 0, 2, 3)
+ assert out["lafs1"].shape == (1, 0, 2, 3)
+
+ def test_laf_and_descriptor_counts_must_agree(self, device, dtype):
+ # The padding mask is derived from the LAFs and applied to the descriptors, so a count
+ # mismatch used to surface as an opaque boolean-index `IndexError` deep in the loop.
+ matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("nn", 0.8)).to(device, dtype)
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ lafs = torch.rand(1, 3, 2, 3, device=device, dtype=dtype)
+ descs = torch.rand(1, 5, 128, device=device, dtype=dtype)
+ images = {"image0": img, "image1": img}
+ data = {**images, "lafs0": lafs, "descriptors0": descs, "lafs1": lafs, "descriptors1": descs[:, :3]}
+ with pytest.raises(Exception, match=r"lafs0 and descriptors0"):
+ matcher(data)
+ data = {**images, "lafs0": lafs, "descriptors0": descs[:, :3], "lafs1": lafs, "descriptors1": descs}
+ with pytest.raises(Exception, match=r"lafs1 and descriptors1"):
+ matcher(data)
+
+ def test_masks_are_forwarded_to_the_detector(self, device, dtype):
+ feat = SIFTFeature(8, upright=True).to(device, dtype)
+ matcher = LocalFeatureMatcher(feat, DescriptorMatcher("nn", 0.8)).to(device, dtype)
+ image0 = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ image1 = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ # LocalFeatureMatcher historically documents masks without a channel dimension; it adds
+ # that singleton axis before forwarding to the detector's (B, 1, H, W) mask contract.
+ mask = torch.zeros(1, 64, 64, device=device, dtype=torch.bool)
+ with torch.no_grad():
+ out = matcher({"image0": image0, "image1": image1, "mask0": mask, "mask1": mask})
+ assert out["keypoints0"].shape == (0, 2)
+ assert out["keypoints1"].shape == (0, 2)
+
@pytest.mark.slow
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_nomatch(self, device, dtype, data):
diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.py
index 2ecea284f..3d1921cb4 100644
--- a/tests/feature/test_local_features_orientation.py
+++ b/tests/feature/test_local_features_orientation.py
@@ -21,7 +21,7 @@ import torch
from kornia.feature.orientation import LAFOrienter, OriNet, PassLAF, PatchDominantGradientOrientation
from kornia.geometry.conversions import rad2deg
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_grid_sample, supports_replicate_padding
class TestPassLAF(BaseTester):
@@ -98,6 +98,66 @@ class TestPatchDominantGradientOrientation(BaseTester):
self.assert_close(model(patches), model_jit(patches))
+class TestOrientationHalfPrecisionIsFinite(BaseTester):
+ """A flat patch has a zero gradient; `sqrt(gx*gx + gy*gy + eps)` must not give NaN in float16.
+
+ The 1e-10 guard underflows to zero in float16 and so does a squared float16 gradient, so
+ the descriptor-side helper lifts the step to float32. The orienter took the same expression
+ unguarded and sent a NaN LAF into the descriptor at a *filled* slot.
+ """
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_flat_patch(self, device, half_dtype):
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_replicate_padding(device, half_dtype):
+ # `spatial_gradient` pads with mode="replicate"; torch 2.5.1 has no float16 CPU kernel.
+ pytest.skip(f"no replicate-pad kernel for {half_dtype} on {device.type}")
+ patches = torch.zeros(2, 1, 32, 32, device=device, dtype=half_dtype)
+ out = PatchDominantGradientOrientation(32).to(device, half_dtype)(patches)
+ assert out.dtype == half_dtype
+ assert torch.isfinite(out).all()
+
+ @pytest.mark.parametrize("ori_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ def test_flat_patch_backward_is_finite(self, device, ori_dtype):
+ # A flat patch has no orientation; `atan2`'s `1 / eps` derivative there is an artefact that
+ # overflowed to `inf` through the float16 cast and reached the patch as NaN (all 1024 pixels).
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_replicate_padding(device, ori_dtype):
+ pytest.skip(f"no replicate-pad kernel for {ori_dtype} on {device.type}")
+ patches = torch.zeros(2, 1, 32, 32, device=device, dtype=ori_dtype, requires_grad=True)
+ out = PatchDominantGradientOrientation(32).to(device, ori_dtype)(patches)
+ out.sum().backward()
+ assert patches.grad is not None and torch.isfinite(patches.grad).all()
+ assert bool((patches.grad == 0).all()), patches.grad.abs().max().item()
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_flat_image_laf(self, device, half_dtype):
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not (supports_replicate_padding(device, half_dtype) and supports_grid_sample(device, half_dtype)):
+ # The orienter extracts patches with `grid_sample` and differentiates them with a
+ # replicate pad; torch 2.5.1 has neither CPU kernel for float16, nor `grid_sample` for bfloat16.
+ pytest.skip(f"no half-precision patch-extraction kernels for {half_dtype} on {device.type}")
+ img = torch.full((1, 1, 32, 32), 0.5, device=device, dtype=half_dtype)
+ laf = torch.tensor([[[[5.0, 0.0, 16.0], [0.0, 5.0, 16.0]]]], device=device, dtype=half_dtype)
+ out = LAFOrienter(19).to(device, half_dtype)(laf, img)
+ assert out.dtype == half_dtype
+ assert torch.isfinite(out).all()
+
+ def test_half_precision_matches_float32(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_replicate_padding(device, torch.float16):
+ pytest.skip(f"no float16 replicate-pad kernel on {device.type}")
+ torch.manual_seed(0)
+ patches = torch.rand(4, 1, 32, 32, device=device)
+ ref = PatchDominantGradientOrientation(32).to(device)(patches)
+ out = PatchDominantGradientOrientation(32).to(device, torch.float16)(patches.half())
+ self.assert_close(out.float(), ref, atol=5e-2, rtol=0)
+
+
class TestOrientationKernelBuffer(BaseTester):
"""`weighting` must be a real buffer so `.to()` moves it, and `forward` must not rebind it (#4069)."""
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index ff351f63f..29e5feadf 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -608,6 +608,21 @@ class TestMatchSteererGlobal(BaseTester):
assert idxs.shape[1] == 2
assert idxs.shape[0] == dists.shape[0]
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ def test_normalize_is_finite_on_a_zero_descriptor(self, device, desc_dtype):
+ # `F.normalize`'s default eps underflows in float16, so a zero row -- the descriptor of a
+ # padded slot -- became NaN, and `cdist` then poisoned its whole row and column.
+ torch.manual_seed(0)
+ desc1 = torch.rand(5, 8, device=device, dtype=desc_dtype)
+ desc2 = torch.rand(6, 8, device=device, dtype=desc_dtype)
+ desc1[1] = 0
+ desc2[4] = 0
+ steerer = DiscreteSteerer(torch.eye(8, device=device, dtype=desc_dtype))
+ matcher = DescriptorMatcherWithSteerer(steerer=steerer, steerer_order=2, steer_mode="global", match_mode="mnn")
+ dists, idxs, _ = matcher(desc1, desc2, normalize=True)
+ assert torch.isfinite(dists).all()
+ assert idxs.shape[0] >= 1
+
def test_matching(self, device):
desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
diff --git a/tests/feature/test_mkd.py b/tests/feature/test_mkd.py
index 0419d981e..31c5e1e31 100644
--- a/tests/feature/test_mkd.py
+++ b/tests/feature/test_mkd.py
@@ -424,6 +424,37 @@ class TestMKDDescriptor(BaseTester):
output_dims = min(self.dims[kernel_type], 128)
assert out.shape == (1, output_dims)
+ def test_state_dict_from_before_the_moduledict_loads_strictly(self, device):
+ # The stages used to live in a plain dict, so a saved state dict has no `feats.*` keys.
+ # Those buffers are derived from the constructor arguments, so a strict load fills them in.
+ mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
+ old = {k: v for k, v in mkd.state_dict().items() if not k.startswith("feats.")}
+ assert len(old) < len(mkd.state_dict())
+ fresh = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
+ fresh.load_state_dict(old, strict=True)
+ inp = torch.rand(2, 1, 19, 19, device=device)
+ self.assert_close(fresh(inp), mkd(inp))
+ # A saved `feats.*` key is still honoured over the freshly computed buffer.
+ new = mkd.state_dict()
+ key = next(k for k in new if k.startswith("feats."))
+ new[key] = torch.zeros_like(new[key])
+ fresh.load_state_dict(new, strict=True)
+ assert bool((fresh.state_dict()[key] == 0).all())
+
+ def test_partial_stage_state_dict_fails_strictly(self, device):
+ # The legacy fill is for a state dict with *no* `feats.*` keys. One saved by this release
+ # that lost a single stage buffer is a corrupt checkpoint, and a strict load has to say so
+ # rather than silently fill the hole from the live instance.
+ mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
+ partial = mkd.state_dict()
+ key = next(k for k in partial if k.startswith("feats."))
+ del partial[key]
+ fresh = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
+ with pytest.raises(RuntimeError, match=key.replace(".", r"\.")):
+ fresh.load_state_dict(partial, strict=True)
+ # non-strict still loads, as it does for any missing key
+ fresh.load_state_dict(partial, strict=False)
+
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 01c4cfca1..0dff976f0 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -15,18 +15,21 @@
# limitations under the License.
#
+import pytest
import torch
import kornia
+from kornia.core.check import ShapeError
from kornia.feature.scale_space_detector import (
_MAX_ABS_SIN_12,
MultiResolutionDetector,
ScaleSpaceDetector,
+ _resize_mask,
get_default_detector_config,
)
from kornia.geometry.subpix import ConvQuadInterp3d
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_replicate_padding
class TestScaleSpaceDetector(BaseTester):
@@ -54,8 +57,11 @@ class TestScaleSpaceDetector(BaseTester):
lafs, resps = det(inp)
expected_laf = torch.tensor([[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]], device=device, dtype=dtype)
expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)
- self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
- self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
+ # The scale is `sigma * 2 ** (level / num_levels)` after a sub-pixel refinement; float16
+ # resolves it to ~3e-3 and bfloat16, with its 8-bit mantissa, to ~3e-2.
+ rtol = {torch.float16: 5e-3, torch.bfloat16: 4e-2}.get(dtype, 1e-3)
+ self.assert_close(lafs, expected_laf, rtol=rtol, atol=1e-03)
+ self.assert_close(resps, expected_resp, rtol=rtol, atol=1e-03)
def test_toy_mask(self, device, dtype):
inp = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)
@@ -69,8 +75,337 @@ class TestScaleSpaceDetector(BaseTester):
lafs, resps = det(inp, mask)
expected_laf = torch.tensor([[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]], device=device, dtype=dtype)
expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)
- self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
- self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
+ # The scale is `sigma * 2 ** (level / num_levels)` after a sub-pixel refinement; float16
+ # resolves it to ~3e-3 and bfloat16, with its 8-bit mantissa, to ~3e-2.
+ rtol = {torch.float16: 5e-3, torch.bfloat16: 4e-2}.get(dtype, 1e-3)
+ self.assert_close(lafs, expected_laf, rtol=rtol, atol=1e-03)
+ self.assert_close(resps, expected_resp, rtol=rtol, atol=1e-03)
+
+ def test_mask_does_not_promote_the_response_dtype(self, device, dtype):
+ # The mask is resampled and cast onto the response map, so a mask in a different dtype
+ # cannot pull the detector's output away from the image dtype.
+ inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ other = torch.float64 if dtype != torch.float64 else torch.float32
+ if device.type == "mps" and other == torch.float64: # MPS has no float64
+ other = torch.float32 if dtype != torch.float32 else torch.float16
+ assert other != dtype
+ mask = torch.ones(1, 1, 32, 32, device=device, dtype=other)
+ det = ScaleSpaceDetector(5).to(device, dtype)
+ lafs, resps = det(inp, mask)
+ assert lafs.dtype == dtype
+ assert resps.dtype == dtype
+
+ def test_mask_spatial_size_must_match_the_image(self, device, dtype):
+ # `_create_octave_mask` resamples the mask onto every octave, so without this check a
+ # mask of any size is stretched silently onto the wrong geometry.
+ det = ScaleSpaceDetector(5).to(device, dtype)
+ inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ with pytest.raises(Exception, match="spatial size"):
+ det(inp, torch.ones(1, 1, 8, 8, device=device, dtype=dtype))
+ with pytest.raises(Exception, match="spatial size"):
+ det(inp, torch.ones(1, 1, 32, 16, device=device, dtype=dtype))
+
+ def test_mask_must_be_single_channel(self, device, dtype):
+ # `_create_octave_mask` broadcasts the mask over the scale levels, so a channel axis would
+ # land on the level axis: an error when the counts differ, the wrong weighting when they match.
+ det = ScaleSpaceDetector(5).to(device, dtype)
+ inp = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)
+ with pytest.raises(Exception, match="1, H, W"):
+ det(inp, torch.ones(2, 3, 32, 32, device=device, dtype=dtype))
+ with pytest.raises(Exception, match="batch"):
+ det(inp, torch.ones(3, 1, 32, 32, device=device, dtype=dtype))
+ for b in (1, 2):
+ lafs, _ = det(inp, torch.ones(b, 1, 32, 32, device=device, dtype=dtype))
+ assert lafs.shape == torch.Size([2, 5, 2, 3])
+
+ def test_unfilled_slots_carry_a_zero_laf(self, device, dtype):
+ # A slot that no detection filled -- the padding, or a candidate whose frame reaches
+ # outside the image -- has a zero response and a zero LAF, and every real detection sorts
+ # ahead of it. On `main` a border-rejected candidate kept its coordinates beside a zero
+ # response, i.e. a keypoint that was never detected.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(50).to(device, dtype)
+ resps, lafs = det.detect(inp, 50)
+ zero_laf = (lafs[0] == 0).all(dim=-1).all(dim=-1)
+ empty = resps[0] == 0
+ assert bool(zero_laf.any()), "expected this image to under-fill 50 slots"
+ assert bool((~zero_laf).any()), "expected this image to yield real detections"
+ assert torch.equal(zero_laf, empty)
+ n_real = int((~zero_laf).sum())
+ assert bool((~zero_laf[:n_real]).all()), "real detections must come first"
+ lafs_fwd, resps_fwd = det(inp)
+ assert torch.equal(resps_fwd, resps) and torch.equal(lafs_fwd, lafs)
+
+ def test_negative_detections_sort_before_the_padding(self, device, dtype):
+ # A signed response function can have every maximum below zero. The padding must still
+ # come last: it is ranked with a sentinel and zeroed only afterwards.
+ class NegatedHessian(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.resp = kornia.feature.BlobHessian()
+
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ return self.resp(x) - 1.0
+
+ if dtype in (torch.float16, torch.bfloat16):
+ # The shifted response is flat at half precision and yields no maxima at all.
+ pytest.skip("a Hessian response offset by 1.0 has no resolution left in half precision")
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(50, resp_module=NegatedHessian()).to(device, dtype)
+ lafs, resps = det(inp)
+ filled = lafs[0].ne(0).any(dim=-1).any(dim=-1)
+ n_real = int(filled.sum())
+ assert 0 < n_real < 50, f"expected a partially filled result, got {n_real}"
+ assert bool(filled[:n_real].all()) and not bool(filled[n_real:].any())
+ assert (resps[0, :n_real] < 0).all()
+ assert (resps[0, n_real:] == 0).all()
+
+ def test_float_mask_never_promotes_a_down_weighted_negative_response(self, device, dtype):
+ # A weight scales a score toward the worst, not toward zero: a negative score is divided
+ # by the weight, a positive one multiplied. A plain multiply pulled a down-weighted negative
+ # score toward zero and ranked it above every full-weight one.
+ class SignedSpikes(torch.nn.Module):
+ # Four maxima on a -1 floor, all negative: two in the left half, two in the right.
+ spikes = {(24, 24): -0.20, (24, 72): -0.25, (72, 24): -0.40, (72, 72): -0.30}
+
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ out = -torch.ones_like(x)
+ if out.shape[-1] == 96: # the full-resolution octave only; the coarser ones stay flat
+ for (y, xx), v in self.spikes.items():
+ out[:, :, out.shape[2] // 2, y, xx] = v
+ return out
+
+ det = ScaleSpaceDetector(4, resp_module=SignedSpikes(), scale_space_response=True, mr_size=3.0).to(
+ device, dtype
+ )
+ img = torch.zeros(1, 1, 96, 96, device=device, dtype=dtype)
+ lafs_plain, resps_plain = det(img)
+ assert bool(lafs_plain.ne(0).any(dim=-1).any(dim=-1).all()), "expected all four spikes"
+ assert resps_plain[0].tolist() == sorted(resps_plain[0].tolist(), reverse=True)
+ mask = torch.ones(1, 1, 96, 96, device=device, dtype=dtype)
+ mask[..., 48:] = 0.5 # the right half is down-weighted
+ lafs, resps = det(img, mask)
+ xs = lafs[0, :, 0, 2]
+ right = xs >= 48
+ # Same four frames; the full-weight (left, x=24) ones keep their score, the down-weighted
+ # (right, x=72) ones get worse, and the down-weighted best (-0.25) no longer ranks above the
+ # full-weight runner-up (-0.40) -- a multiply would have reported it as -0.125 and put it first.
+ assert int(right.sum()) == 2
+ self.assert_close(resps[0][~right], torch.tensor([-0.20, -0.40], device=device, dtype=dtype))
+ self.assert_close(resps[0][right], torch.tensor([-0.50, -0.60], device=device, dtype=dtype))
+ assert resps[0].tolist() == sorted(resps[0].tolist(), reverse=True)
+ assert xs[0] < 48 and xs[1] < 48, f"a down-weighted candidate outranked a full-weight one: {xs.tolist()}"
+
+ def test_a_weighted_negative_response_never_sorts_below_the_padding(self, device, dtype):
+ # A weight *divides* a negative score, and a small weight can push the quotient past the
+ # dtype's range: -inf ties with the `-inf` an unfilled slot carries into the ranking, so a
+ # non-detection could outrank a real one. The weighted score is kept finite instead.
+ floor = -float(torch.finfo(dtype).max) / 4
+ spike = -float(torch.finfo(dtype).max) / 8
+
+ class HugeNegativeSpikes(torch.nn.Module):
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ out = torch.full_like(x, floor)
+ if out.shape[-1] == 96:
+ for y, xx in ((24, 24), (24, 72), (72, 24), (72, 72)):
+ out[:, :, out.shape[2] // 2, y, xx] = spike
+ return out
+
+ det = ScaleSpaceDetector(4, resp_module=HugeNegativeSpikes(), scale_space_response=True, mr_size=3.0).to(
+ device, dtype
+ )
+ img = torch.zeros(1, 1, 96, 96, device=device, dtype=dtype)
+ mask = torch.full((1, 1, 96, 96), 1e-3, device=device, dtype=dtype)
+ lafs, resps = det(img, mask)
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ assert int(filled.sum()) == 4, "expected all four spikes"
+ assert torch.isfinite(resps).all(), f"a weighted score overflowed: {resps.tolist()}"
+
+ def test_an_extreme_finite_response_still_outranks_the_padding(self, device, dtype):
+ # `finfo.min / 2` is not below every finite response: four maxima at `-2e38` (float32) on a
+ # `finfo.min` floor are real detections, and the single-image path returned all four while
+ # the batched top-K preferred the sentinel and returned none. Padding is ranked with `-inf`,
+ # and a finite response, however extreme, sorts ahead of it on both paths.
+ floor = float(torch.finfo(dtype).min)
+ spike = -float(torch.finfo(dtype).max) * 0.6
+
+ class ExtremeSpikes(torch.nn.Module):
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ out = torch.full_like(x, floor)
+ if out.shape[-1] == 96:
+ for y, xx in ((24, 24), (24, 72), (72, 24), (72, 72)):
+ out[:, :, out.shape[2] // 2, y, xx] = spike
+ return out
+
+ det = ScaleSpaceDetector(4, resp_module=ExtremeSpikes(), scale_space_response=True, mr_size=3.0).to(
+ device, dtype
+ )
+ img = torch.zeros(2, 1, 96, 96, device=device, dtype=dtype)
+ lafs1, resps1 = det(img[:1])
+ lafs2, resps2 = det(img)
+ filled1 = lafs1.ne(0).any(dim=-1).any(dim=-1)
+ filled2 = lafs2.ne(0).any(dim=-1).any(dim=-1)
+ assert int(filled1.sum()) == 4, f"single-image path lost a detection: {resps1.tolist()}"
+ assert int(filled2[0].sum()) == 4 and int(filled2[1].sum()) == 4, f"batched path lost one: {resps2.tolist()}"
+ assert torch.isfinite(resps2).all()
+ self.assert_close(resps2[0], resps1[0])
+
+ def test_subpixel_refinement_cannot_cross_the_mask(self, device, dtype):
+ # The mask is checked at the integer NMS site, but the sub-pixel step moves the centre. A
+ # parabola peaked at x = 31.6 has its discrete maximum at x = 32; a mask allowing only
+ # x >= 32 passed that site and returned a centre of 31.6, inside the zero region. The refined
+ # centre is re-checked against the resampled mask conservatively (every pixel it touches).
+ class Parabola(torch.nn.Module):
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ B, L, H, W = x.shape[0], x.shape[2], x.shape[-2], x.shape[-1]
+ xs = torch.arange(W, device=x.device, dtype=x.dtype).view(1, 1, 1, 1, W)
+ ys = torch.arange(H, device=x.device, dtype=x.dtype).view(1, 1, 1, H, 1)
+ ls = torch.arange(L, device=x.device, dtype=x.dtype).view(1, 1, L, 1, 1)
+ return (10.0 - (xs - 31.6) ** 2 - (ys - 48.0) ** 2 - (ls - L // 2) ** 2).expand(B, 1, L, H, W).clone()
+
+ det = ScaleSpaceDetector(1, resp_module=Parabola(), scale_space_response=True, mr_size=1.0).to(device, dtype)
+ img = torch.zeros(1, 1, 96, 96, device=device, dtype=dtype)
+ mask = torch.zeros(1, 1, 96, 96, device=device, dtype=torch.bool)
+ mask[..., 32:] = True
+ lafs, resps = det(img, mask)
+ assert bool((lafs == 0).all()) and bool((resps == 0).all()), (
+ f"a refined centre at {lafs[0, 0, :, 2].tolist()} lies in the masked-out region"
+ )
+ # Control: the same peak is returned, refined, when the mask allows the pixels it touches.
+ mask[..., 31:] = True
+ lafs, resps = det(img, mask)
+ assert bool(resps[0, 0] > 0)
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([31.6, 48.0], device=device, dtype=dtype), atol=0.2, rtol=0)
+
+ def test_fill_sentinel_follows_the_response_dtype(self, device, dtype):
+ # The top-K sentinel is written into the *response* tensor, so it must fit that dtype: a
+ # response module that emits a narrower dtype than the image -- a learned response under
+ # autocast -- raised "value cannot be converted to type at::Half without overflow".
+ class NarrowResponse(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.resp = kornia.feature.BlobHessian()
+
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ return self.resp(x, sigmas).to(torch.float16)
+
+ torch.manual_seed(0)
+ inp = torch.rand(2, 1, 64, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(20, resp_module=NarrowResponse()).to(device, dtype)
+ for b in (1, 2):
+ lafs, resps = det(inp[:b])
+ assert resps.dtype == torch.float16
+ assert torch.isfinite(resps).all()
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ assert 0 < int(filled[0].sum()) < 20
+ assert bool((resps[~filled] == 0).all())
+
+ def test_float_weights_above_one_are_clamped(self, device, dtype):
+ # A float 0/255 mask -- an OpenCV mask after `.astype(np.float32)` -- is weights, and a weight
+ # above one scaled every score by 255. Weights are clamped to one, so it means what the
+ # integer 0/255 mask means.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(50).to(device, dtype)
+ lafs_b, resps_b = det(inp, torch.ones(1, 1, 64, 64, device=device, dtype=torch.bool))
+ lafs_f, resps_f = det(inp, torch.full((1, 1, 64, 64), 255.0, device=device, dtype=dtype))
+ assert torch.equal(resps_f, resps_b) and torch.equal(lafs_f, lafs_b)
+
+ def test_a_zero_response_maximum_keeps_its_laf(self, device, dtype):
+ # The response function is pluggable and may be signed, so an exact zero can be a genuine
+ # maximum rather than an unfilled slot. Classifying the padding by `response == 0` erased
+ # all three detections here.
+ class SignedResponse(torch.nn.Module):
+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ out = -torch.ones_like(x)
+ out[:, :, out.shape[2] // 2, out.shape[-2] // 2, out.shape[-1] // 2] = 0.0
+ return out
+
+ # `mr_size=3` keeps the coarsest octave's frame inside the 96 px image; at the default 6 it
+ # is 76.8 px wide, and a candidate whose frame leaves the image is not a detection.
+ det = ScaleSpaceDetector(5, resp_module=SignedResponse(), scale_space_response=True, mr_size=3.0).to(
+ device, dtype
+ )
+ lafs, resps = det(torch.zeros(1, 1, 96, 96, device=device, dtype=dtype))
+ assert (resps == 0).all()
+ centers = lafs[0, :, :, 2]
+ found = (centers == 48).all(dim=-1)
+ assert int(found.sum()) == 3, f"expected the three centre maxima, got {centers.tolist()}"
+
+ def test_batched_underfill_does_not_leak_the_topk_sentinel(self, device, dtype):
+ # For B > 1 the octave top-K ranks over the whole volume with non-candidates masked to
+ # `finfo.min / 2`. An image with fewer maxima than requested gets those sentinels back;
+ # they are not detections and must not reach the caller as a response or as a LAF.
+ torch.manual_seed(0)
+ inp = torch.rand(2, 1, 64, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector().to(device, dtype)
+ lafs, resps = det(inp)
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ assert 0 < int(filled[0].sum()) < det.num_features, "expected a partially filled result"
+ assert bool((resps[~filled] == 0).all()), f"sentinel leaked: min response {resps.min().item()}"
+ assert (resps > torch.finfo(dtype).min / 4).all()
+ # and the single-image path agrees, which it did not before. Up to tolerance, not bit-for-bit:
+ # the response convolutions pick batch-size-dependent kernels on some CPUs (ubuntu CI), so the
+ # same candidates carry last-ULP-different scores.
+ lafs1, resps1 = det(inp[:1])
+ self.assert_close(resps1[0], resps[0])
+ self.assert_close(lafs1[0], lafs[0])
+
+ def test_padding_survives_the_affine_and_orientation_modules(self, device, dtype):
+ # Same contract as `MultiResolutionDetector.forward`: the shape and orientation modules
+ # normalise a zero frame into a finite one, so the padding is re-applied after them.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("LAFAffineShapeEstimator uses linalg.inv, which has no half-precision kernel")
+ det = ScaleSpaceDetector(
+ 10, aff_module=kornia.feature.LAFAffineShapeEstimator(19), ori_module=kornia.feature.LAFOrienter(19)
+ ).to(device, dtype)
+ lafs, resps = det(torch.zeros(1, 1, 64, 64, device=device, dtype=dtype))
+ assert (resps == 0).all()
+ assert (lafs == 0).all()
+
+ def test_forward_uses_overridden_detect(self, device, dtype):
+ class CustomDetector(ScaleSpaceDetector):
+ def detect(self, img, num_feats, mask=None):
+ responses = img.new_full((img.shape[0], num_feats), 123.0)
+ lafs = img.new_full((img.shape[0], num_feats, 2, 3), 7.0)
+ return responses, lafs
+
+ inp = torch.zeros(2, 1, 32, 32, device=device, dtype=dtype)
+ det = CustomDetector(3).to(device, dtype)
+ lafs, responses = det(inp)
+ assert torch.equal(responses, inp.new_full((2, 3), 123.0))
+ assert torch.equal(lafs, inp.new_full((2, 3, 2, 3), 7.0))
+
+ @pytest.mark.parametrize("subpix", ["adaptive", "conv"])
+ def test_color_input_with_single_channel_response(self, device, dtype, subpix):
+ class ColorResponse(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.response = kornia.feature.BlobHessian()
+
+ def forward(self, x: torch.Tensor, _sigmas: torch.Tensor) -> torch.Tensor:
+ return self.response(x.mean(dim=1, keepdim=True))
+
+ torch.manual_seed(3)
+ inp = torch.rand(1, 3, 96, 96, device=device, dtype=dtype)
+ kwargs = {} if subpix == "adaptive" else {"subpix_module": ConvQuadInterp3d(10)}
+ det = ScaleSpaceDetector(20, resp_module=ColorResponse(), **kwargs).to(device, dtype)
+ lafs, responses = det(inp)
+ assert lafs.shape == torch.Size([1, 20, 2, 3])
+ assert responses.shape == torch.Size([1, 20])
+ valid = lafs.ne(0).any(dim=-1).any(dim=-1)
+ centers = lafs[..., 2][valid]
+ assert bool(valid.any())
+ assert (centers[:, 0] >= 0).all() and (centers[:, 0] <= 95).all()
+ assert (centers[:, 1] >= 0).all() and (centers[:, 1] <= 95).all()
+
+ def test_multichannel_response_is_rejected(self, device, dtype):
+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
+ detector = ScaleSpaceDetector(20, resp_module=kornia.feature.BlobHessian()).to(device, dtype)
+ with pytest.raises(Exception, match="one response map"):
+ detector(inp)
def test_minima_are_also_good(self, device, dtype):
# Image with a bright blob (local max) and dark blob (local min).
@@ -194,8 +529,8 @@ class TestMultiResolutionDetector(BaseTester):
assert lafs.shape == torch.Size([1, 20, 2, 3])
def test_score_threshold_reduces_detections(self, device, dtype):
- # A very high score_threshold should leave no real detections: all returned responses
- # will be the sentinel fill value (very negative), while shape remains fixed.
+ # A very high score_threshold should leave no real detections: every slot is padding,
+ # which reads as an exactly zero response, while the shape remains fixed.
inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
det_no_thresh = self._make_detector(num_features=50).to(device, dtype)
det_high_thresh = MultiResolutionDetector(
@@ -204,10 +539,347 @@ class TestMultiResolutionDetector(BaseTester):
lafs_no_thresh, resps_no_thresh = det_no_thresh(inp)
lafs_high_thresh, resps_high_thresh = det_high_thresh(inp)
assert lafs_high_thresh.shape == lafs_no_thresh.shape
- # With an impossibly high threshold all slots contain the fill sentinel (< 0),
- # while real detections always have positive responses.
+ # With an impossibly high threshold every slot is padding: a zero response and a zero
+ # LAF. Real detections always have positive responses.
assert resps_no_thresh.max().item() > 0
- assert (resps_high_thresh <= 0).all()
+ assert (resps_high_thresh == 0).all()
+ assert (lafs_high_thresh == 0).all()
+
+ def test_short_result_is_padded_with_zeros(self, device, dtype):
+ # A level with fewer above-threshold maxima than its quota must not return the
+ # `torch.finfo(dtype).min / 2` top-K sentinel, nor the arbitrary border coordinates
+ # `topk` picks once every remaining candidate is tied at that value.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector(num_features=100).to(device, dtype)
+ lafs, resps = det(inp)
+
+ assert resps.shape == torch.Size([1, 100])
+ assert (resps >= 0).all()
+ padding = resps[0] == 0
+ assert bool(padding.any()), "expected this image to under-fill 100 slots"
+ assert (lafs[0][padding] == 0).all()
+ assert (resps[0][~padding] > 0).all()
+
+ def test_mask_suppresses_detections(self, device, dtype):
+ # Two blobs: a bright one top-left, a dimmer one bottom-right. Unmasked, the bright
+ # blob wins; with a mask covering only the bottom-right quadrant the dim blob must be
+ # the best -- and nothing may be detected outside the mask.
+ inp = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ inp[:, :, 14:19, 14:19] = 1.0
+ inp[:, :, 46:51, 46:51] = 0.5
+ mask = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ mask[:, :, 32:, 32:] = 1.0
+
+ det = self._make_detector(num_features=10).to(device, dtype)
+ lafs_free, resps_free = det(inp)
+ lafs_masked, resps_masked = det(inp, mask)
+
+ assert lafs_free[0, int(resps_free[0].argmax()), 0, 2].item() < 32
+ assert lafs_masked[0, int(resps_masked[0].argmax()), 0, 2].item() > 32
+ found = resps_masked[0] != 0
+ assert bool(found.any())
+ # The mask is resampled conservatively onto every level, so nothing is detected on the
+ # zero side of its edge at any level.
+ assert (lafs_masked[0][found][:, :, 2] >= 32).all()
+
+ def test_mask_edge_does_not_create_maxima(self, device, dtype):
+ # A blob wholly inside the zero region, next to the mask edge. Multiplying the response by
+ # a resampled mask before non-maxima suppression carved an edge into it, and the bilinear
+ # ramp of that edge was a "maximum" on the suppressed side (kornia#4102).
+ inp = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ inp[:, :, 30:34, 28:32] = 1.0
+ mask = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ mask[:, :, :, 32:] = 1.0
+ det = self._make_detector(num_features=5).to(device, dtype)
+ lafs, resps = det(inp, mask)
+ assert (resps == 0).all(), f"detected on the masked side: {lafs[0][resps[0] != 0][:, 0, 2].tolist()}"
+ assert (lafs == 0).all()
+
+ def test_thin_masked_stripe_survives_downsampling(self, device, dtype):
+ # A two-pixel zero stripe is narrower than the sampling step of a coarse level, so an
+ # interpolated mask reads 1.0 there and the stripe is gone; the conservative resample keeps
+ # every level pixel it touches at zero.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 256, 256, device=device, dtype=dtype)
+ mask = torch.ones(1, 1, 256, 256, device=device, dtype=dtype)
+ mask[:, :, :, 120:122] = 0.0
+ det = self._make_detector(num_features=2000).to(device, dtype)
+ lafs, resps = det(inp, mask)
+ xs = lafs[0][resps[0] != 0][:, 0, 2]
+ assert xs.numel() > 100
+ assert not bool(((xs >= 120) & (xs < 122)).any()), sorted(xs[(xs >= 119) & (xs < 123)].tolist())
+
+ @pytest.mark.parametrize("src, dst", [((100, 100), (45, 45)), ((38, 38), (90, 90)), ((7, 9), (3, 4))])
+ def test_mask_resample_is_the_cpu_adaptive_min_pool_on_every_device(self, device, dtype, src, dst):
+ # `F.adaptive_max_pool2d` on MPS returns the wrong shape when the output is larger than the
+ # input (the KeyNet up-level, the double-image octave) and pools other windows than CPU for
+ # a non-integer ratio, so the resampled mask would depend on the device. The hand-rolled
+ # resample pins the CPU windows on every device.
+ torch.manual_seed(0)
+ mask = torch.rand(2, 1, *src, device=device, dtype=dtype)
+ ref = torch.empty(1, 1, *dst, device=device, dtype=dtype)
+ expected = -torch.nn.functional.adaptive_max_pool2d(-mask.cpu().float(), dst)
+ got = _resize_mask(mask, ref)
+ assert got.shape == (2, 1, *dst)
+ assert got.dtype == dtype
+ self.assert_close(got.cpu().float(), expected.to(got.cpu().float().dtype))
+
+ def test_float_weights_above_one_are_clamped(self, device, dtype):
+ # The weighting runs before the `score_threshold` test, so a weight above one lifted
+ # sub-threshold maxima over it. A float 0/255 mask now means what the integer one means.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector().to(device, dtype)
+ lafs_b, resps_b = det(inp, torch.ones(1, 1, 64, 64, device=device, dtype=torch.bool))
+ lafs_f, resps_f = det(inp, torch.full((1, 1, 64, 64), 255.0, device=device, dtype=dtype))
+ assert torch.equal(resps_f, resps_b) and torch.equal(lafs_f, lafs_b)
+
+ def test_float_mask_weights_the_score_and_keeps_the_candidates(self, device, dtype):
+ # A graded mask used to be multiplied into the response before the NMS and the sub-pixel
+ # step, which moved maxima and their refined positions. It now weights only the score of a
+ # maximum found in the unweighted response: same detections, same positions, ranked by weight.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector(num_features=2000).to(device, dtype)
+ lafs_plain, resps_plain = det(inp)
+ ramp = torch.linspace(0.2, 1.0, 64, device=device, dtype=dtype).view(1, 1, 1, 64).expand(1, 1, 64, 64)
+ lafs, resps = det(inp, ramp.contiguous())
+ keep_plain, keep = resps_plain[0] != 0, resps[0] != 0
+ assert int(keep.sum()) == int(keep_plain.sum()) > 20
+ # Same set of frames, up to the order the weighted score imposes.
+
+ def order(t: torch.Tensor) -> torch.Tensor:
+ key = t[:, 0, 2].cpu().double() * 1000 + t[:, 1, 2].cpu().double()
+ return t[torch.sort(key).indices.to(t.device)]
+
+ self.assert_close(order(lafs[0][keep]), order(lafs_plain[0][keep_plain]))
+ ratio = resps[0][keep] / resps_plain[0][keep]
+ assert float(ratio.min()) >= 0.2 - 1e-2 and float(ratio.max()) <= 1.0 + 1e-2
+ assert not torch.allclose(resps[0][keep], resps_plain[0][keep_plain])
+
+ def test_response_map_must_match_the_level_size(self, device, dtype):
+ # A response index is decoded as a level pixel with no offset, so a valid-convolution net
+ # that returns a smaller map put every keypoint one pixel up and left of its peak and had
+ # the mask resampled onto the shifted geometry. Nothing can infer the offset from the shape,
+ # so a map of another size is rejected rather than silently misplaced.
+ kernel = torch.ones(1, 1, 3, 3, device=device, dtype=dtype) / 9
+ det = MultiResolutionDetector(lambda x: torch.nn.functional.conv2d(x, kernel), num_features=8).to(device, dtype)
+ with pytest.raises(Exception, match=r"spatial size"):
+ det(torch.rand(1, 1, 64, 64, device=device, dtype=dtype))
+
+ def test_a_nan_weight_does_not_consume_a_slot(self, device, dtype):
+ # `s * NaN` sorts first in `topk`, so one NaN pixel in a float mask took a slot on every
+ # pyramid level and displaced a real maximum (18 filled slots became 13); `ScaleSpaceDetector`
+ # gates its candidates with `weight > 0`, which drops NaN, and this detector does the same.
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector(num_features=20).to(device, dtype)
+ lafs_ref, _ = det(inp)
+ mask = torch.ones(1, 1, 64, 64, device=device, dtype=dtype)
+ mask[0, 0, 30, 30] = float("nan")
+ lafs, resps = det(inp, mask)
+ filled_ref = lafs_ref.ne(0).any(dim=-1).any(dim=-1)
+ filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ assert torch.isfinite(resps).all()
+ # the NaN pixel suppresses its neighbourhood on every level, nothing more
+ assert int(filled_ref.sum()) - 4 <= int(filled.sum()) <= int(filled_ref.sum())
+
+ def test_mask_spatial_size_must_match_the_image(self, device, dtype):
+ # `KORNIA_CHECK_SHAPE`'s named dims are free per call, so on their own they let a mask
+ # of any size through to be stretched onto the image; the explicit check is what rejects it.
+ det = self._make_detector(num_features=10).to(device, dtype)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ with pytest.raises(Exception, match="spatial size"):
+ det(inp, torch.ones(1, 1, 32, 32, device=device, dtype=dtype))
+ with pytest.raises(Exception, match="spatial size"):
+ det(inp, torch.ones(1, 1, 64, 32, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("mask_kind", ["bool", "uint8_255", "int32_100"])
+ def test_binary_masks_match_float_mask(self, device, dtype, mask_kind):
+ # A boolean or integer mask is binary: any non-zero value keeps a position, so an OpenCV
+ # 0/255 mask means the same as a 0/1 one and does not scale the responses by 255.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ mask = torch.zeros(1, 1, 64, 64, device=device, dtype=torch.bool)
+ mask[:, :, 32:, 32:] = True
+ if mask_kind == "uint8_255":
+ mask = mask.to(torch.uint8) * 255
+ elif mask_kind == "int32_100":
+ mask = mask.to(torch.int32) * 100
+ det = self._make_detector(num_features=10).to(device, dtype)
+ lafs_bool, resps_bool = det(inp, mask)
+ lafs_float, resps_float = det(inp, mask.ne(0).to(dtype))
+ assert bool((resps_bool != 0).any())
+ assert torch.equal(resps_bool, resps_float)
+ assert torch.equal(lafs_bool, lafs_float)
+ # ... and the mask is doing something, so the two arms cannot agree vacuously the way
+ # they would if the mask were ignored altogether.
+ _lafs_free, resps_free = det(inp)
+ assert not torch.equal(resps_bool, resps_free)
+
+ def test_padding_survives_the_affine_and_orientation_modules(self, device, dtype):
+ # `forward` runs `aff` and `ori` after `detect`; `LAFAffineShapeEstimator` normalises a
+ # zero frame into a finite 1e-5-scale one, so the zero-LAF contract has to be re-applied.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("LAFAffineShapeEstimator uses linalg.inv, which has no half-precision kernel")
+ det = MultiResolutionDetector(
+ kornia.feature.BlobHessian(),
+ num_features=10,
+ aff_module=kornia.feature.LAFAffineShapeEstimator(19),
+ ori_module=kornia.feature.LAFOrienter(19),
+ ).to(device, dtype)
+ lafs, resps = det(torch.zeros(1, 1, 64, 64, device=device, dtype=dtype))
+ assert (resps == 0).all()
+ assert (lafs == 0).all()
+
+ def test_zero_mask_detects_nothing(self, device, dtype):
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ mask = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector(num_features=20).to(device, dtype)
+ lafs, resps = det(inp, mask)
+ assert (resps == 0).all()
+ assert (lafs == 0).all()
+
+ @staticmethod
+ def _require_half_response(device, half_dtype):
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ # `BlobHessian` reaches `spatial_gradient`, which pads with mode="replicate".
+ # `replication_pad2d` has no CPU float16 kernel before torch 2.6.
+ if not supports_replicate_padding(device, half_dtype):
+ pytest.skip(f"no replicate-padding kernel for {half_dtype} on {device.type}")
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_half_precision_dtype_is_preserved(self, device, half_dtype):
+ # `detect_features_on_single_level` used to hardcode `.float()` on the pixel
+ # coordinates, so half-precision input came back with float32 LAFs beside
+ # half-precision responses.
+ self._require_half_response(device, half_dtype)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=half_dtype)
+ det = self._make_detector(num_features=20).to(device, half_dtype)
+ lafs, resps = det(inp)
+ assert lafs.dtype == half_dtype
+ assert resps.dtype == half_dtype
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_mask_does_not_promote_the_response_dtype(self, device, half_dtype):
+ # A float32 mask multiplied into a half-precision response map used to promote the
+ # responses to float32 while the LAFs stayed half.
+ self._require_half_response(device, half_dtype)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=half_dtype)
+ mask = torch.ones(1, 1, 64, 64, device=device, dtype=torch.float32)
+ det = self._make_detector(num_features=20).to(device, half_dtype)
+ lafs, resps = det(inp, mask)
+ assert lafs.dtype == half_dtype
+ assert resps.dtype == half_dtype
+
+ def test_color_input_with_single_channel_response(self, device, dtype):
+ class ColorResponse(torch.nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x.mean(dim=1, keepdim=True)
+
+ torch.manual_seed(3)
+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
+ det = MultiResolutionDetector(ColorResponse(), num_features=100).to(device, dtype)
+ lafs, resps = det(inp)
+ found = resps[0] != 0
+ assert bool(found.any())
+ cx = lafs[0, :, 0, 2]
+ cy = lafs[0, :, 1, 2]
+ assert (cx >= 0).all() and (cx <= 63).all()
+ assert (cy >= 0).all() and (cy <= 63).all()
+
+ def test_multichannel_response_is_rejected(self, device, dtype):
+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
+ detector = self._make_detector(num_features=100).to(device, dtype)
+ with pytest.raises(Exception, match="one response map"):
+ detector(inp)
+
+ def test_result_is_padded_to_num_features(self, device, dtype):
+ # An 8x8 image is smaller than the 15px border `remove_borders` strips, so there is
+ # genuinely nothing to detect and every slot is padding. A level is also capped at its
+ # own pixel count (64 here), so the concatenated result used to come back short.
+ cfg = get_default_detector_config()
+ cfg["pyramid_levels"] = 0
+ cfg["up_levels"] = 0
+ tiny = MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=100, config=cfg).to(device, dtype)
+ lafs, resps = tiny(torch.rand(1, 1, 8, 8, device=device, dtype=dtype))
+ assert lafs.shape == torch.Size([1, 100, 2, 3])
+ assert resps.shape == torch.Size([1, 100])
+ # Say so explicitly, so this test cannot pass by codifying a dummy result elsewhere.
+ assert (resps == 0).all()
+ assert (lafs == 0).all()
+
+ def test_short_result_is_sorted(self, device, dtype):
+ # `detect` used to run its final top-K only when the levels had produced *more* slots than
+ # `num_features`, so a short result came back in level order with each level's own padding
+ # left in place and the real detections scattered through it.
+ det = self._make_detector(num_features=6000, pyramid_levels=2, up_levels=0).to(device, dtype)
+ resps, _lafs = det.detect(torch.rand(1, 1, 48, 48, device=device, dtype=dtype))
+ found = int((resps[0] != 0).sum())
+ assert 0 < found < 6000, f"expected a short result, got {found} detections"
+ assert bool((resps[0][:found] != 0).all()), "the detections do not come first"
+ assert torch.equal(resps[0], torch.sort(resps[0], descending=True).values)
+
+ def test_single_feature_request_returns_a_real_detection(self, device, dtype):
+ # With the default configuration and `num_features=1` every proportional quota truncates
+ # to zero (the shares are 0.508 .. 0.016), so every level was queried for zero candidates
+ # and the result was a padded dummy on an image full of maxima.
+ torch.manual_seed(11)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ lafs_one, resps_one = self._make_detector(num_features=1).to(device, dtype)(inp)
+ lafs_two, resps_two = self._make_detector(num_features=2).to(device, dtype)(inp)
+
+ assert resps_one.shape == torch.Size([1, 1])
+ assert resps_one[0, 0] > 0
+ # Asking for one feature must return the same best feature as asking for two.
+ self.assert_close(resps_one[0, 0], resps_two[0].max())
+ self.assert_close(lafs_one[0, 0], lafs_two[0, int(resps_two[0].argmax())])
+
+ def test_negative_score_threshold_is_rejected(self, device, dtype):
+ # NMS writes an exact zero at every suppressed position, so a negative threshold would
+ # admit all of them -- and collide with the zero response that marks an unfilled slot.
+ with pytest.raises(ValueError):
+ MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=10, score_threshold=-1.0)
+
+ def test_detect_rejects_a_batch(self, device, dtype):
+ # `detect` is public and documents `(1, C, H, W)`; a larger batch would be flattened
+ # across the batch axis and silently return coordinates for the wrong image.
+ det = self._make_detector(num_features=10).to(device, dtype)
+ with pytest.raises(ShapeError):
+ det.detect(torch.rand(2, 1, 64, 64, device=device, dtype=dtype))
+
+ def test_forward_uses_overridden_detect(self, device, dtype):
+ # `detect` is the public extension point; `forward` reads occupancy off its zero-LAF
+ # padding rather than off the response, so an override is honoured whole.
+ class CustomDetector(MultiResolutionDetector):
+ def detect(self, img, mask=None):
+ responses = img.new_full((1, self.num_features), 123.0)
+ lafs = img.new_full((1, self.num_features, 2, 3), 7.0)
+ return responses, lafs
+
+ inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ det = CustomDetector(kornia.feature.BlobHessian(), num_features=3).to(device, dtype)
+ lafs, responses = det(inp)
+ assert torch.equal(responses, inp.new_full((1, 3), 123.0))
+ assert torch.equal(lafs, inp.new_full((1, 3, 2, 3), 7.0))
+
+ def test_three_argument_level_override_still_runs_unmasked(self, device, dtype):
+ # `detect_features_on_single_level` is public and gained a keyword-only `mask`; a subclass
+ # written against the historical three-argument signature keeps working without a mask
+ # and gets a TypeError, not silent misbehaviour, with one.
+ class LegacyLevel(MultiResolutionDetector):
+ def detect_features_on_single_level(self, level_img, num_kp, factor):
+ return super().detect_features_on_single_level(level_img, num_kp, factor)
+
+ torch.manual_seed(0)
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = LegacyLevel(kornia.feature.BlobHessian(), num_features=10).to(device, dtype)
+ ref = self._make_detector(num_features=10).to(device, dtype)
+ lafs, resps = det(inp)
+ lafs_ref, resps_ref = ref(inp)
+ assert torch.equal(lafs, lafs_ref) and torch.equal(resps, resps_ref)
+ with pytest.raises(TypeError):
+ det(inp, torch.ones(1, 1, 64, 64, device=device, dtype=dtype))
def test_smoke_with_blob_image(self, device, dtype):
# Synthetic image with a bright blob β€” detector should find it.
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index 7c337ec2c..697265961 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -25,7 +25,7 @@ from kornia.feature.siftdesc import (
get_sift_pooling_kernel,
)
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_replicate_padding
@pytest.mark.parametrize("ksize", [5, 13, 25])
@@ -109,6 +109,110 @@ class TestSIFTDescriptorKernelBuffer(BaseTester):
assert (mod.gk.dtype, mod.gk.device) == before
+class TestSIFTConstantPatchIsFinite(BaseTester):
+ """A constant patch has a zero-norm descriptor; normalising it must not give NaN.
+
+ `F.normalize`'s default eps of 1e-12 is not representable in float16, so the clamp that
+ exists to stop `0 / 0` was itself zero there. A detector that pads a short result hands the
+ descriptor a zero LAF, which samples one point repeatedly and produces exactly this patch.
+ """
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ @pytest.mark.parametrize("rootsift", [False, True])
+ def test_sift(self, device, desc_dtype, rootsift):
+ if not supports_replicate_padding(device, desc_dtype):
+ # `spatial_gradient` pads with mode="replicate"; torch 2.5.1 has no float16 CPU kernel.
+ pytest.skip(f"no replicate-padding kernel for {desc_dtype} on {device.type}")
+ patches = torch.zeros(2, 1, 16, 16, device=device, dtype=desc_dtype)
+ out = SIFTDescriptor(16, rootsift=rootsift).to(device, desc_dtype)(patches)
+ assert torch.isfinite(out).all()
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ @pytest.mark.parametrize("rootsift", [False, True])
+ def test_gradients_are_finite_on_ordinary_patches(self, device, desc_dtype, rootsift):
+ # Not only the forward: `sqrt` and `atan2` have an undefined backward at a zero gradient,
+ # and the 1e-10 guard is zero in float16, so two equal neighbouring pixels -- ordinary
+ # with a 10-bit mantissa -- put NaN into the input gradient (9 of 4096 on this seed).
+ if not supports_replicate_padding(device, desc_dtype):
+ pytest.skip(f"no replicate-padding kernel for {desc_dtype} on {device.type}")
+ torch.manual_seed(0)
+ patches = torch.rand(4, 1, 32, 32, device=device, dtype=desc_dtype, requires_grad=True)
+ out = SIFTDescriptor(32, rootsift=rootsift).to(device, desc_dtype)(patches)
+ out.sum().backward()
+ assert torch.isfinite(out).all()
+ assert patches.grad is not None and torch.isfinite(patches.grad).all()
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ @pytest.mark.parametrize("rootsift", [False, True])
+ def test_flat_patch_backward_is_finite(self, device, desc_dtype, rootsift):
+ # The flat forward and the random-patch backward were each pinned, never their intersection:
+ # on an exactly flat patch -- what a zero-LAF padding slot samples -- the zero-norm descriptor
+ # had the `eps` clamp's `1 / eps` gradient, `1e12` in float32 and `inf` once cast to float16,
+ # and the orientation's `atan2` a `1 / eps` of its own; the input gradient was NaN in float16
+ # (256 of 256) and ~1e8 in float32. A zero gradient has no orientation and a zero vector no
+ # direction, so both branches now have a zero derivative.
+ if not supports_replicate_padding(device, desc_dtype):
+ pytest.skip(f"no replicate-padding kernel for {desc_dtype} on {device.type}")
+ patches = torch.zeros(2, 1, 16, 16, device=device, dtype=desc_dtype, requires_grad=True)
+ out = SIFTDescriptor(16, rootsift=rootsift).to(device, desc_dtype)(patches)
+ out.sum().backward()
+ assert torch.isfinite(out).all()
+ assert patches.grad is not None and torch.isfinite(patches.grad).all(), patches.grad.abs().max()
+ assert bool((patches.grad == 0).all()), f"flat patch has a gradient of {patches.grad.abs().max().item()}"
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+ def test_l2_normalize_zero_vector_has_a_zero_gradient(self, device, desc_dtype):
+ from kornia.core.utils import _l2_normalize
+
+ x = torch.zeros(3, 8, device=device, dtype=desc_dtype, requires_grad=True)
+ _l2_normalize(x, dim=1).sum().backward()
+ assert x.grad is not None and bool((x.grad == 0).all()), x.grad
+ # and a non-zero vector keeps `F.normalize`'s value and gradient
+ y = torch.rand(3, 8, device=device, dtype=desc_dtype, requires_grad=True)
+ y_ref = y.detach().clone().requires_grad_(True)
+ _l2_normalize(y, dim=1).sum().backward()
+ torch.nn.functional.normalize(y_ref.float(), dim=1, eps=1e-12).to(desc_dtype).sum().backward()
+ self.assert_close(y.grad, y_ref.grad)
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ def test_dense_sift(self, device, desc_dtype):
+ if not supports_replicate_padding(device, desc_dtype):
+ # `spatial_gradient` pads with mode="replicate"; torch 2.5.1 has no float16 CPU kernel.
+ pytest.skip(f"no replicate-padding kernel for {desc_dtype} on {device.type}")
+ img = torch.zeros(1, 1, 32, 32, device=device, dtype=desc_dtype)
+ out = DenseSIFTDescriptor().to(device, desc_dtype)(img)
+ assert torch.isfinite(out).all()
+
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16])
+ def test_rootsift_half_precision_matches_float32(self, device, desc_dtype):
+ # The float16-representable `eps` is 6.1e-5, and `sqrt(6.1e-5)` in every empty bin pushed
+ # the norm to ~1.004; the RootSIFT step therefore runs in float32 for a float16 input.
+ if not supports_replicate_padding(device, desc_dtype):
+ pytest.skip(f"no replicate-padding kernel for {desc_dtype} on {device.type}")
+ torch.manual_seed(0)
+ patches = torch.rand(4, 1, 41, 41, device=device)
+ ref = SIFTDescriptor(41, rootsift=True).to(device)(patches)
+ out = SIFTDescriptor(41, rootsift=True).to(device, desc_dtype)(patches.to(desc_dtype))
+ assert out.dtype == desc_dtype
+ self.assert_close(out.float().norm(dim=1), torch.ones(4, device=device), atol=2e-3, rtol=0)
+ self.assert_close(out.float(), ref, atol=2e-2, rtol=0)
+
+ def test_float16_subnormal_norm_still_normalises_to_one(self, device):
+ # A float16 vector whose norm sits below the smallest normal (6.1e-5) is representable
+ # and torch's fp16 `norm` accumulates in fp32, so clamping the norm to 6.1e-5 shrank the
+ # result to 0.55 instead of 1. The normalisation runs in float32 for a float16 input.
+ from kornia.core.utils import _l2_normalize
+
+ x = torch.full((1, 128), 3e-6, device=device, dtype=torch.float16)
+ out = _l2_normalize(x, dim=1)
+ assert out.dtype == torch.float16
+ self.assert_close(out.float().norm(dim=1), torch.ones(1, device=device), atol=2e-3, rtol=0)
+ assert (_l2_normalize(torch.zeros_like(x), dim=1) == 0).all()
+ for dt in (torch.bfloat16, torch.float32, torch.float64):
+ y = torch.rand(3, 8, device=device, dtype=dt)
+ assert torch.equal(_l2_normalize(y, dim=1), torch.nn.functional.normalize(y, dim=1, eps=1e-12))
+
+
class TestDenseSIFTDescriptor(BaseTester):
def test_shape_default(self, device, dtype):
bs, h, w = 1, 20, 15