Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): return float32 coordinates from half-precision feature models (#5966)

Dmytro Mishkin3bac7711dbf1
diff --git a/changelog.d/5966.fixed.md b/changelog.d/5966.fixed.md
new file mode 100644
index 000000000..790fb368b
--- /dev/null
+++ b/changelog.d/5966.fixed.md
@@ -0,0 +1 @@
+Float16 and bfloat16 `LoFTR`, `DISK`, `ALIKED`, `ScaleSpaceDetector`, `MultiResolutionDetector` and `SIFTFeatureScaleSpace` (both backends), with `KeyNetDetector` and the `LocalFeature` presets built on them, now return float32 keypoints and LAFs, formed in float32 where they are computed; scores, responses, confidences and descriptors keep the model's dtype. In bfloat16 the coordinates were rounded to a 2 px grid above x = 256 and a 4 px grid above 512, and in float16 to a 0.25 px grid above 256. A half-precision module fed these coordinates directly has to cast them: `LightGlue` now accepts float32 keypoints with a float16 or bfloat16 model (it raised `expected m1 and m2 to have the same dtype`), and `LocalFeatureMatcher` returns the same keypoint and LAF dtype whether or not a pair matches (it returned half keypoints and LAFs when no pair matched and float32 ones otherwise). `ImageStitcher` with a float16 matcher and `estimator="vanilla"` could give a NaN panorama, because the DLT ran on float16 keypoints; it now runs on float32 keypoints.
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index c82659379..33df59c30 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -307,7 +307,10 @@ class DKD(nn.Module):
indices = indices[sort_idx[: self.n_limit]]
indices_keypoints.append(indices)
- wh = torch.tensor([w - 1, h - 1], device=scores_nograd.device, dtype=scores_nograd.dtype)
+ # Keypoints are formed in at least float32: a half-precision dtype holds no odd integer above 256 (bfloat16)
+ # or 2048 (float16), not even ``w - 1``. The grid of the score lookup is cast to the map's dtype for the call.
+ coord_dtype = torch.promote_types(scores_map.dtype, torch.float32)
+ wh = torch.tensor([w - 1, h - 1], device=scores_nograd.device, dtype=coord_dtype)
keypoints = []
scoredispersitys = []
@@ -339,12 +342,12 @@ class DKD(nn.Module):
)
scoredispersity = (x_exp * hw_grid_dist2).sum(dim=1) / x_exp.sum(dim=1)
- keypoints_xy = keypoints_xy_nms + xy_residual
+ keypoints_xy = keypoints_xy_nms.to(coord_dtype) + xy_residual
keypoints_xy = keypoints_xy / wh * 2 - 1 # -> [-1, 1]
kptscore = F.grid_sample(
scores_map[b_idx].unsqueeze(0),
- keypoints_xy.view(1, 1, -1, 2),
+ keypoints_xy.view(1, 1, -1, 2).to(scores_map.dtype),
mode="bilinear",
align_corners=True,
)[0, 0, 0, :]
@@ -368,10 +371,10 @@ class DKD(nn.Module):
[indices_kpt % w, torch.div(indices_kpt, w, rounding_mode="trunc")],
dim=1,
)
- keypoints_xy = keypoints_xy_nms / wh * 2 - 1
+ keypoints_xy = keypoints_xy_nms.to(coord_dtype) / wh * 2 - 1
kptscore = F.grid_sample(
scores_map[b_idx].unsqueeze(0),
- keypoints_xy.view(1, 1, -1, 2),
+ keypoints_xy.view(1, 1, -1, 2).to(scores_map.dtype),
mode="bilinear",
align_corners=True,
)[0, 0, 0, :]
@@ -685,7 +688,8 @@ class SDDH(nn.Module):
A pair ``(descriptors, offsets)`` where each element is a list of length B.
"""
b, c, h, w = x.shape
- wh = torch.tensor([[w - 1, h - 1]], device=x.device, dtype=x.dtype)
+ # Positions in at least float32, as in DKD; the sampling grid is cast to the feature map's dtype for the call.
+ wh = torch.tensor([[w - 1, h - 1]], device=x.device, dtype=torch.promote_types(x.dtype, torch.float32))
max_offset = max(h, w) / 4.0
offsets_list = []
@@ -717,7 +721,7 @@ class SDDH(nn.Module):
pos = 2.0 * pos / wh[None] - 1
pos = pos.reshape(1, N_kpts * self.n_pos, 1, 2)
- features = F.grid_sample(xi.unsqueeze(0), pos, mode="bilinear", align_corners=True)
+ features = F.grid_sample(xi.unsqueeze(0), pos.to(xi.dtype), mode="bilinear", align_corners=True)
features = features.reshape(c, N_kpts, self.n_pos, 1).permute(1, 0, 2, 3)
if mask_w is not None:
@@ -778,10 +782,11 @@ class ALIKED(nn.Module):
does not move the keypoints.
- :meth:`forward` returns one :class:`ALIKEDFeatures` per image. Its keypoints are sub-pixel ``(x, y)`` in the
pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
- (see :ref:`Local features <local-features-conventions>`), in the image's dtype: a strict maximum of the
- score map in its ``2 * nms_radius + 1`` window (see the note), at least ``nms_radius`` pixels from the
- border, moved by a soft-argmax over that window. Its score is the score map read bilinearly there, and the
- descriptors are L2-normalised.
+ (see :ref:`Local features <local-features-conventions>`): a strict maximum of the score map in its
+ ``2 * nms_radius + 1`` window (see the note), at least ``nms_radius`` pixels from the border, moved by a
+ soft-argmax over that window. Its score is the score map read bilinearly there, and the descriptors are
+ L2-normalised. The keypoints, and the LAFs of :meth:`forward_laf`, are float32 for a float16 or bfloat16
+ model and otherwise in the image's dtype; scores and descriptors keep the model's dtype.
- With ``detection_threshold > 0`` (threshold mode), the maxima strictly above it are kept, at most
``max_num_keypoints`` of them, and at most 20000 for a non-positive ``max_num_keypoints``. An image with no
maximum above the threshold keeps the maxima above its own mean score instead, whatever the rest of the
@@ -968,7 +973,7 @@ class ALIKED(nn.Module):
B = images.shape[0]
_, _, h, w = images.shape
- wh = torch.tensor([w - 1, h - 1], device=images.device, dtype=images.dtype)
+ wh = torch.tensor([w - 1, h - 1], device=images.device, dtype=torch.promote_types(images.dtype, torch.float32))
results = []
for i in range(B):
@@ -1040,7 +1045,7 @@ class ALIKED(nn.Module):
descriptors, _offsets = self.desc_head(feature_map, keypoints)
B, _, H, W = img.shape
- wh = torch.tensor([W - 1, H - 1], device=img.device, dtype=img.dtype)
+ wh = torch.tensor([W - 1, H - 1], device=img.device, dtype=torch.promote_types(img.dtype, torch.float32))
lafs_list: list[torch.Tensor] = []
for i in range(B):
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index e07b650e5..aa8f0317f 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -62,8 +62,9 @@ class DISK(nn.Module):
- Each image gives a :class:`DISKFeatures`. Keypoints are the integer ``(x, y)`` pixels of the strict heatmap
maxima (see the note), in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`), listed in raster order (row by row, then column
- by column) rather than by score, in the dtype of the network's output. ``detection_scores`` are the
- heatmap values there, and each descriptor is the dense descriptor at the keypoint's pixel, L2-normalised;
+ by column) rather than by score, in float32 for a float16 or bfloat16 network and otherwise in the dtype
+ of the network's output. ``detection_scores`` are the heatmap values there, in the network's dtype, and
+ each descriptor is the dense descriptor at the keypoint's pixel, L2-normalised;
:meth:`heatmap_and_dense_descriptors` returns the dense descriptors without normalisation.
- ``score_threshold`` keeps the scores strictly above it. ``n`` is an upper bound on the maxima above
``score_threshold`` in each image; the ``n`` argument of :meth:`forward` says which of them are kept when
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 62bd3f1c9..73c3aaf61 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -111,4 +111,6 @@ class Keypoints:
desc = descriptors[:, y, x].T
desc = F.normalize(desc, dim=-1)
- return DISKFeatures(self.xys.to(dtype), desc, self.detection_logp.to(dtype))
+ # The integer pixels go to at least float32: bfloat16 holds no odd integer above 256, float16 none above 2048.
+ xys = self.xys.to(torch.promote_types(dtype, torch.float32))
+ return DISKFeatures(xys, desc, self.detection_logp.to(dtype))
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 6b748d4e4..7351e60a4 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -446,7 +446,8 @@ class SIFTFeatureScaleSpace(LocalFeature):
- On both backends the LAF scale is 6 times the detection sigma, and ``responses`` is the absolute DoG, the
same for a bright blob as for a dark one. The LAF centres are in the frame of
:func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`) on
- every octave.
+ every octave. For a float16 or bfloat16 image the LAFs are float32 on both backends, and the responses and
+ descriptors keep the image dtype.
- Descriptors come in kornia's SIFT layout; ``descriptor_layout="opencv"`` returns them in OpenCV's, which
:class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.
:func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.
@@ -939,7 +940,11 @@ class LocalFeatureMatcher(nn.Module):
out_batch_indexes.append(batch_idxs)
if len(out_batch_indexes) == 0:
- return self.no_match_output(data["image0"].device, data["image0"].dtype)
+ out = self.no_match_output(data["image0"].device, data["image0"].dtype)
+ # As on the match path, keypoints and LAFs keep the LAFs' dtype: float32 for a half-precision detector.
+ out["keypoints0"], out["lafs0"] = out["keypoints0"].to(lafs0.dtype), out["lafs0"].to(lafs0.dtype)
+ out["keypoints1"], out["lafs1"] = out["keypoints1"].to(lafs1.dtype), out["lafs1"].to(lafs1.dtype)
+ return out
return {
"keypoints0": torch.cat(out_keypoints0, dim=0).view(-1, 2),
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 174dd0261..e5fc24d71 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -478,7 +478,8 @@ class LightGlue(nn.Module):
- The ``keypoints`` of each image are ``(x, y)`` pixels and ``image_size`` is ``(W, H)``; an ``image``
tensor gives the size from its last two dimensions instead. ``forward`` normalises the keypoints to
``(k - size / 2) / (max(size) / 2)``, as the reference implementation does, and raises for a keypoint
- outside :math:`[-1, 1]` after that.
+ outside :math:`[-1, 1]` after that. The keypoints can be wider than the model, like the float32 keypoints
+ of kornia's detectors with a float16 or bfloat16 model; the positional encoding runs in the model's dtype.
- The ``"sift"``, ``"doghardnet"`` and ``"dog_affnet_hardnet"`` configurations, which set ``add_scale_ori``,
also read ``scales`` and ``oris`` (radians) of each image; the last two multiply ``scales`` by their
``scale_coef`` of 1/6 first, so they take the LAF scale. ``"keynet_affnet_hardnet"``, which sets ``add_laf``,
@@ -845,9 +846,11 @@ class LightGlue(nn.Module):
kpts1, _ = pad_to_length(kpts1, kn)
desc0 = self.input_proj(desc0)
desc1 = self.input_proj(desc1)
- # cache positional embeddings
- encoding0 = self.posenc(kpts0)
- encoding1 = self.posenc(kpts1)
+ # cache positional embeddings, in the encoder's dtype: kornia's detectors return float32 keypoints for a
+ # half-precision model, which would otherwise meet half-precision weights here
+ pe_dtype = self.posenc.Wr.weight.dtype
+ encoding0 = self.posenc(kpts0.to(pe_dtype))
+ encoding1 = self.posenc(kpts1.to(pe_dtype))
# GNN + final_proj + assignment
do_early_stop = self.conf.depth_confidence > 0
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index f678f9737..f4e22388a 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -94,6 +94,8 @@ class LoFTR(nn.Module):
the frame of the reference implementation, in which the pretrained models put the centre of pixel
:math:`(x, y)` at :math:`(x + 0.5, y + 0.5)`: subtract 0.5 to get kornia's frame
(:ref:`Local features <local-features-conventions>`), in which pixel centres have integer coordinates.
+ The keypoints are float32 for a float16 or bfloat16 model and float64 for a float64 one;
+ ``confidence`` keeps the model dtype.
- ``confidence`` is the coarse matching score of the match, a dual-softmax score with the default
``match_type``; only matches above ``max(thr, 0)`` are returned, with the ``thr`` of
``config["match_coarse"]``, 0.2 by default.
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 5ae09aea9..4a9f47cd3 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -336,20 +336,22 @@ class CoarseMatching(nn.Module):
coarse_matches = {"b_ids": b_ids, "i_ids": i_ids, "j_ids": j_ids}
# 4. Update with matches in original image resolution: coarse cell (x, y) of either image sits on pixel
- # (stride_c * x, stride_c * y) for any image size
+ # (stride_c * x, stride_c * y) for any image size. The keypoints are built in at least float32 before any
+ # scaling: bfloat16 holds no odd integer above 256 and float16 none above 2048.
+ coord_dtype = torch.promote_types(conf_matrix.dtype, torch.float32)
scale = data["stride_c"]
- scale0 = scale * data["scale0"][b_ids] if "scale0" in data else scale
- scale1 = scale * data["scale1"][b_ids] if "scale1" in data else scale
- mkpts0_c = torch.stack([i_ids % data["hw0_c"][1], i_ids // data["hw0_c"][1]], dim=1) * scale0
- mkpts1_c = torch.stack([j_ids % data["hw1_c"][1], j_ids // data["hw1_c"][1]], dim=1) * scale1
+ scale0 = scale * data["scale0"][b_ids].to(coord_dtype) if "scale0" in data else scale
+ scale1 = scale * data["scale1"][b_ids].to(coord_dtype) if "scale1" in data else scale
+ mkpts0_c = torch.stack([i_ids % data["hw0_c"][1], i_ids // data["hw0_c"][1]], dim=1).to(coord_dtype) * scale0
+ mkpts1_c = torch.stack([j_ids % data["hw1_c"][1], j_ids // data["hw1_c"][1]], dim=1).to(coord_dtype) * scale1
# These matches is the current prediction (for visualization)
coarse_matches.update(
{
"gt_mask": mconf == 0,
"m_bids": b_ids[mconf != 0], # mconf == 0 => gt matches
- "mkpts0_c": mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
- "mkpts1_c": mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ "mkpts0_c": mkpts0_c[mconf != 0],
+ "mkpts1_c": mkpts1_c[mconf != 0],
"mconf": mconf[mconf != 0],
}
)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 3eb67753f..82346c3b0 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -112,7 +112,9 @@ def _adaptive_min_pool_1d(m: torch.Tensor, out_size: int, dim: int) -> torch.Ten
return gathered.reshape(shape).amin(dim=dim + 1)
-def _weight_scores(scores: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
+def _weight_scores(
+ scores: torch.Tensor, weights: torch.Tensor, bound_dtype: Optional[torch.dtype] = None
+) -> 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
@@ -126,14 +128,16 @@ def _weight_scores(scores: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
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.
+ dtypes are unchanged wherever the quotient is representable. ``bound_dtype`` names the dtype the
+ score is reported in when that is narrower than ``scores``, as for the float32 copy of a
+ half-precision response that :class:`ScaleSpaceDetector` ranks, so the bound still fits it.
"""
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)
+ return out.clamp_min(torch.finfo(dtype if bound_dtype is None else bound_dtype).min).to(dtype)
def _create_octave_mask(mask: torch.Tensor, octave_resp: torch.Tensor) -> torch.Tensor:
@@ -228,6 +232,9 @@ class ScaleSpaceDetector(nn.Module):
centres; the whole frame can reach outside the image.
- The output has ``num_features`` slots: the detections by decreasing response, then the unfilled slots, which
hold a zero response and a zero LAF.
+ - The LAFs are float32 for a float16 or bfloat16 image and float64 for a float64 one; the responses keep the
+ response function's dtype. Non-maximum suppression and sub-pixel refinement run on the response promoted to
+ at least float32.
- Known defects: an octave passes only its ``num_features`` strongest candidates to the border test and to the
mask check of their refined centres, so the slot of a candidate rejected there stays empty even when a
weaker valid candidate exists (`#5741 <https://github.com/kornia/kornia/issues/5741>`_).
@@ -386,14 +393,15 @@ class ScaleSpaceDetector(nn.Module):
is_iterative_subpix: bool,
batchable_subpix: bool,
octave_to_image: Tuple[float, float],
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.dtype]:
"""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.
+ Returns the top-K responses, their LAFs, a boolean mask of the slots a detection
+ actually filled, and the dtype of the response function's output. 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. The responses
+ and LAFs are in at least float32; ``_detect`` casts the responses back to the returned dtype.
"""
dev = octave.device
# An octave searches `num_levels` response levels, 1..num_levels; levels 0 and num_levels + 1 are only
@@ -435,7 +443,14 @@ class ScaleSpaceDetector(nn.Module):
# level/channel permutation above is contiguous when CH == 1 (the common path), but
# not for a response that preserves multiple channels, nor for a scale-space response cut to its levels.
oct_resp = oct_resp[:, :, :n_resp_levels].contiguous()
- scale_sigmas = sigmas_oct[:, : oct_resp.shape[2]]
+ # The mask weights are cast to the response's own dtype (see `_resize_mask`), before the promotion below.
+ resampled = None if mask is None else _create_octave_mask(mask, oct_resp)
+ # The refiners write absolute pixel coordinates into a tensor of the response's dtype, and bfloat16 holds no
+ # odd integer above 256 (float16: above 2048). Run NMS, refinement and top-K on the response in at least
+ # float32; promoting is exact, so NMS selects the same candidates. `_detect` casts the responses back.
+ resp_dtype = oct_resp.dtype
+ oct_resp = oct_resp.to(torch.promote_types(resp_dtype, torch.float32))
+ scale_sigmas = sigmas_oct[:, : oct_resp.shape[2]].to(oct_resp.dtype)
# Always precompute NMS masks in one fused pass.
# - For minima_are_also_good: both masks are needed anyway.
@@ -452,8 +467,7 @@ class ScaleSpaceDetector(nn.Module):
# 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)
+ if mask is not None and resampled is not None:
oct_keep = resampled > 0
max_nms_mask = max_nms_mask & oct_keep
min_nms_mask = min_nms_mask & oct_keep
@@ -477,13 +491,13 @@ class ScaleSpaceDetector(nn.Module):
response_max[:, :, 0] = 0.0
response_max[:, :, -1] = 0.0
if oct_mask is not None:
- response_max = _weight_scores(response_max, oct_mask)
+ response_max = _weight_scores(response_max, oct_mask, resp_dtype)
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)
+ response_min = _weight_scores(response_min, oct_mask, resp_dtype)
take_min_mask = (response_min > response_max) & min_nms_mask
response_max = torch.where(take_min_mask, response_min, response_max)
# Candidate positions: original max-NMS plus swapped min-NMS positions.
@@ -586,7 +600,7 @@ class ScaleSpaceDetector(nn.Module):
# Octave pixels to input pixels, per axis: x scales the first LAF row, y the second.
current_lafs[:, :, 0, :].mul_(octave_to_image[0])
current_lafs[:, :, 1, :].mul_(octave_to_image[1])
- return resp_flat_best, current_lafs, filled
+ return resp_flat_best, current_lafs, filled, resp_dtype
def _detect(
self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
@@ -613,7 +627,8 @@ class ScaleSpaceDetector(nn.Module):
"Expected the scale pyramid module to have `n_levels` as a torch.Tensor or int."
f"Got {type(self.scale_pyr.n_levels)}"
)
- rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
+ # The LAFs are assembled in at least float32, the dtype `_process_octave` refines the centres in.
+ rotmat = torch.eye(2, dtype=torch.promote_types(dtype, torch.float32), device=dev).view(1, 1, 2, 2)
# Read the live module once per forward, so a refiner swapped in after construction, or a
# compiled one passed by the caller, is dispatched consistently on both the single-sign and
# the minima-and-maxima path.
@@ -632,7 +647,7 @@ 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, torch.Tensor]] = [
+ results: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.dtype]] = [
self._process_octave(
sp[i],
sigmas[i],
@@ -665,7 +680,8 @@ class ScaleSpaceDetector(nn.Module):
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))
+ # The ranking ran on the float32 copy of a half-precision response; the scores keep the response's dtype.
+ responses = torch.where(filled, responses, torch.zeros_like(responses)).to(results[0][3])
return responses, _zero_unfilled(lafs, filled), filled
def detect(
@@ -929,16 +945,15 @@ class MultiResolutionDetector(nn.Module):
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.
+ # resolution. The LAFs are built in at least float32: a half-precision dtype cannot hold a
+ # pixel index times a scale factor, nor an odd pixel above 256 (bfloat16) or 2048 (float16).
yx = torch.stack([top_flat_idx // w, top_flat_idx % w], dim=1) # (k, 2)
- wide = torch.float64 if level_img.dtype == torch.float64 else torch.float32
+ wide = torch.promote_types(level_img.dtype, 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)
+ xy_projected = yx.view(1, k, 2).flip(2).to(wide) * fx
scale_val = 0.5 * (factor[0] + factor[1]) * self.mr_size
- scale = level_img.new_full((1, k, 1, 1), scale_val)
- lafs = laf_from_center_scale_ori(xy_projected, scale, level_img.new_zeros(1, k, 1))
+ scale = torch.full((1, k, 1, 1), scale_val, device=level_img.device, dtype=wide)
+ lafs = laf_from_center_scale_ori(xy_projected, scale, scale.new_zeros(1, k, 1))
lafs = lafs * valid.view(1, k, 1, 1).to(lafs.dtype)
return top_scores, lafs
@@ -969,8 +984,8 @@ class MultiResolutionDetector(nn.Module):
`(1, num_features, 2, 3)`, holding the `num_features` highest responses in the image and sorted by
response, descending. 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.
+ The LAFs are float32 for a float16 or bfloat16 image and float64 for a float64 one; the responses keep
+ the response function's dtype.
"""
KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
if mask is not None:
diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.py
index 8e92ecce5..c467b11df 100644
--- a/kornia/feature/sift/scale_space.py
+++ b/kornia/feature/sift/scale_space.py
@@ -506,10 +506,12 @@ class _SIFTScaleSpaceDetector(nn.Module):
if mask.is_floating_point():
mask = mask.clamp_max(1.0).to(img.dtype)
bsz, dtype, device = img.shape[0], img.dtype, img.device
+ # LAFs are at least float32: bfloat16 holds no odd pixel above 256, float16 none above 2048.
+ laf_dtype = torch.promote_types(dtype, torch.float32)
zero = img[..., :0, :0].sum()
if bsz == 0 or num_feats == 0:
responses = img.new_zeros(bsz, num_feats) + zero
- lafs = img.new_zeros(bsz, num_feats, 2, 3) + zero
+ lafs = img.new_zeros(bsz, num_feats, 2, 3, dtype=laf_dtype) + zero
filled = torch.zeros(bsz, num_feats, device=device, dtype=torch.bool)
ids = torch.full((bsz, num_feats), -1, device=device, dtype=torch.long)
return responses, lafs, filled, [img.unsqueeze(2)], ids, ids.clone()
@@ -527,7 +529,7 @@ class _SIFTScaleSpaceDetector(nn.Module):
xy = torch.stack([(x.to(gaussian.dtype) + sx) * pixel, (y.to(gaussian.dtype) + sy) * pixel], -1)
entries.append((b, layer, xy, response, sigma, torch.full_like(layer, octave)))
responses = torch.zeros(bsz, num_feats, device=device, dtype=dtype) + zero
- lafs = torch.zeros(bsz, num_feats, 2, 3, device=device, dtype=dtype) + zero
+ lafs = torch.zeros(bsz, num_feats, 2, 3, device=device, dtype=laf_dtype) + zero
filled = torch.zeros(bsz, num_feats, device=device, dtype=torch.bool)
octaves = torch.full((bsz, num_feats), -1, device=device, dtype=torch.long)
levels = torch.full_like(octaves, -1)
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index f635ad9a0..3950ba7bd 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -332,6 +332,9 @@ class XFeat(nn.Module):
1 keeps every cell of both scales. Its descriptors are not normalised. The reference implementation gives
the 1.3 scale ``int(0.8 * top_k)`` and reads a share of 0 as "every cell"; kornia does not, because that
returns more keypoints than ``top_k`` asks for.
+ - Known defects: converting the model to float16 or bfloat16 makes every extraction raise, because
+ ``_preprocess_tensor`` passes float32 input to the half-precision weights
+ (`#5957 <https://github.com/kornia/kornia/issues/5957>`_).
Args:
top_k: maximum number of keypoints to keep per image. Default: ``4096``.
diff --git a/tests/contrib/test_image_stitcher.py b/tests/contrib/test_image_stitcher.py
index 525ba2c44..47a0c7fee 100644
--- a/tests/contrib/test_image_stitcher.py
+++ b/tests/contrib/test_image_stitcher.py
@@ -24,7 +24,7 @@ from torch import nn
import kornia
from kornia.feature import LocalFeatureMatcher
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
def _render(x0: float, w: int, h: int = 48, dtype: torch.dtype = torch.float32) -> torch.Tensor: # float32: MPS too
@@ -326,6 +326,33 @@ class TestImageStitcher(BaseTester):
assert out.shape[:-1] == torch.Size([1, 3, 6])
assert out.shape[-1] <= 12
+ @pytest.mark.parametrize("estimator", ["ransac", "vanilla"])
+ def test_real_matcher_in_the_image_dtype(self, estimator, device, dtype):
+ # A real matcher, not keypoints mocked in the test dtype: a float16 or bfloat16 SIFT matcher returns float32
+ # keypoints and so a float32 homography, which the stitcher must warp the half-precision image with. The right
+ # crop overlaps the left one by 64 px of a 96 x 224 scene, so the panorama is about 224 px wide.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):
+ pytest.skip(f"SIFTFeature pads with reflection and replication, absent for {dtype} on {device.type}")
+ g = torch.Generator().manual_seed(0)
+ scene = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 96, 224, generator=g), 5, 1, 2).expand(-1, 3, -1, -1)
+ left, right = scene[..., :144].to(device, dtype), scene[..., 80:].to(device, dtype)
+ matcher = kornia.feature.LocalFeatureMatcher(
+ kornia.feature.SIFTFeature(200), kornia.feature.DescriptorMatcher("snn", 0.8)
+ ).to(device, dtype)
+ stitcher = kornia.contrib.ImageStitcher(matcher, estimator=estimator)
+ torch.manual_seed(0) # RANSAC sampling
+ with torch.no_grad():
+ pano = stitcher(left, right)
+ _, mask = stitcher.stitch_pair(left, right)
+ assert pano.dtype == mask.dtype == dtype
+ assert pano.shape[:3] == (1, 3, 96)
+ assert 220 <= pano.shape[-1] <= 236
+ assert bool(torch.isfinite(pano).all())
+ width = min(pano.shape[-1], 224)
+ assert (pano[..., :width].cpu().double() - scene[..., :width].double()).abs().median() < 0.05
+
@pytest.mark.slow
def test_exception(self, device, dtype):
B, C, H, W = 1, 3, 224, 224
diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.py
index 2afe7bea8..645c849ef 100644
--- a/tests/feature/test_aliked.py
+++ b/tests/feature/test_aliked.py
@@ -361,6 +361,30 @@ class TestALIKED(BaseTester):
# ---------------------------------------------------------------------------
+class TestALIKEDHalfPrecisionCoordinates(BaseTester):
+ def test_half_model_returns_float32_keypoints(self, device, dtype):
+ # R4: the soft-argmax keypoints were formed and returned in the score map's dtype, which puts every bfloat16
+ # keypoint past x = 256 on a 2 px grid. They are float32 now; scores and descriptors keep the model dtype.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ if not (supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)):
+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")
+ torch.manual_seed(0)
+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)
+ image = torch.rand(1, 3, 96, 400, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+ with torch.no_grad():
+ (feats,) = aliked(image)
+ lafs, responses, descs = aliked.forward_laf(image)
+ assert feats.keypoints.dtype == torch.float32
+ assert feats.keypoint_scores.dtype == dtype
+ assert feats.descriptors.dtype == dtype
+ assert lafs.dtype == torch.float32
+ assert responses.dtype == dtype
+ assert descs.dtype == dtype
+ for x in (feats.keypoints[:, 0], lafs[0, :, 0, 2]):
+ assert (x[x > 256] % 2 != 0).any() # sub-2-px positions past 256, which bfloat16 cannot hold
+
+
class TestALIKEDForwardLAF(BaseTester):
"""Tests for ALIKED.forward_laf returning kornia LAF-format outputs."""
@@ -484,7 +508,9 @@ class TestALIKEDForwardLAF(BaseTester):
hook.remove()
assert lafs.shape == (1, 3, 2, 3)
order = torch.argsort(lafs[0, :, 0, 2] * 100 + lafs[0, :, 1, 2]) # by x, then y
- A = lafs[0, order, :, :2] # peaks at x = 30 (neighbour below), 60 (right), 80 (diagonal)
+ # peaks at x = 30 (neighbour below), 60 (right), 80 (diagonal); the shape comes from the soft-argmax weights,
+ # which are in the model's dtype, while the LAFs are float32 for a half-precision model
+ A = lafs[0, order, :, :2].to(dtype)
det = A[:, 0, 0] * A[:, 1, 1] - A[:, 0, 1] * A[:, 1, 0]
assert (det > 0).all(), det
ellipse_right = torch.tensor([[0.45736**2, 0.0], [0.0, 0.11605**2]], device=device, dtype=dtype)
@@ -524,8 +550,8 @@ class TestALIKEDKeypointSelection(BaseTester):
@staticmethod
def _tol(dtype):
- # an isolated peak lands on its pixel; in half precision DKD computes in the map's dtype, so 0.25 px
- return 0.25 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ # an isolated peak lands on its pixel; the keypoints are float32 for a half-precision model as well
+ return 1e-4
@staticmethod
def _top_k(k, device, dtype):
@@ -535,7 +561,8 @@ class TestALIKEDKeypointSelection(BaseTester):
# Three maxima, returned by score: k = 3 returns them; k = 5 and k = 10000 (more than the 64 * 96 pixels)
# return the same three, never a non-maximum.
peaks = [(0, 60, 40, 0.8), (0, 21, 13, 0.9), (0, 35, 50, 0.7)]
- maxima = torch.tensor([[21.0, 13.0], [60.0, 40.0], [35.0, 50.0]], device=device, dtype=dtype)
+ coord = torch.promote_types(dtype, torch.float32)
+ maxima = torch.tensor([[21.0, 13.0], [60.0, 40.0], [35.0, 50.0]], device=device, dtype=coord)
# relabelling: the transposed map gives the transposed maxima
peaks_t = [(b, y, x, s) for b, x, y, s in peaks]
for h, w, peaks_i, maxima_i in ((64, 96, peaks, maxima), (96, 64, peaks_t, maxima.flip(-1))):
@@ -566,7 +593,7 @@ class TestALIKEDKeypointSelection(BaseTester):
assert feats.n == len(expected)
assert lafs.shape == (1, len(expected), 2, 3)
if expected:
- expected_t = torch.tensor(expected, device=device, dtype=dtype)
+ expected_t = torch.tensor(expected, device=device, dtype=torch.promote_types(dtype, torch.float32))
self.assert_close(feats.keypoints, expected_t, rtol=0.0, atol=self._tol(dtype))
def test_top_k_keeps_no_keypoint_in_the_border_or_the_padding_5862(self, device, dtype):
@@ -582,7 +609,7 @@ class TestALIKEDKeypointSelection(BaseTester):
assert [f.n for f in feats] == [2, 1]
for f, (w, h), expected_i in zip(feats, image_size.tolist(), expected):
self.assert_close(
- f.keypoints, torch.tensor(expected_i, device=device, dtype=dtype), rtol=0.0, atol=self._tol(dtype)
+ f.keypoints, torch.tensor(expected_i, device=device, dtype=f.keypoints.dtype), rtol=0.0, atol=1e-4
)
assert (f.keypoints >= 2).all()
assert (f.keypoints[:, 0] <= w - 3).all()
@@ -611,12 +638,47 @@ class TestALIKEDKeypointSelection(BaseTester):
for i, expected_i in enumerate(expected):
centres = lafs[i, filled[i], :, 2]
self.assert_close(
- centres, torch.tensor(expected_i, device=device, dtype=dtype), rtol=0.0, atol=self._tol(dtype)
+ centres, torch.tensor(expected_i, device=device, dtype=centres.dtype), rtol=0.0, atol=1e-4
)
assert lafs[1, 1:].abs().max() == 0
assert responses[1, 1:].abs().max() == 0
assert descs[1, 1:].abs().max() == 0
+ def test_isolated_peaks_past_256_land_on_their_pixel(self, device, dtype):
+ # The keypoints are float32 for a half-precision model, normalised by W - 1 = 319, which bfloat16 rounds to
+ # 320: the odd pixels past 256, which bfloat16 cannot hold, come back exactly from forward and forward_laf.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ if not (supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)):
+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")
+ peaks = [(0, 257, 13, 0.9), (0, 301, 40, 0.8), (0, 35, 50, 0.7)]
+ score_map = self._score_map(peaks, device, dtype, w=320)
+ aliked = self._top_k(5, device, dtype)
+ (feats,) = self._run(aliked, score_map)
+ lafs, _, _ = self._run(aliked, score_map, "forward_laf", compute_affine=False)
+ expected = torch.tensor([[257.0, 13.0], [301.0, 40.0], [35.0, 50.0]], dtype=torch.float64)
+ for found in (feats.keypoints, lafs[0, :, :, 2]):
+ assert found.dtype == torch.promote_types(dtype, torch.float32)
+ self.assert_close(found.cpu().double(), expected, rtol=0.0, atol=1e-4)
+
+ def test_descriptor_head_reads_the_keypoint_pixel_past_256(self, device, dtype):
+ # SDDH predicts its sampling offsets from the feature patch around each keypoint's pixel. With W - 1 = 319,
+ # which bfloat16 rounds to 320, a half-precision normaliser put that pixel one column off past x = 256. The
+ # right neighbour moves the keypoint to x = 300.27 by the soft-argmax, so its pixel is column 300.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ if not (supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)):
+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")
+ score_map = self._score_map([(0, 300, 40, 0.8), (0, 301, 40, 0.7)], device, dtype, w=320)
+ aliked = self._top_k(5, device, dtype)
+ corners = []
+ get_patches = aliked.desc_head.get_patches_func
+ aliked.desc_head.get_patches_func = lambda t, c, ps: corners.append(c.cpu()) or get_patches(t, c, ps)
+ (feats,) = self._run(aliked, score_map)
+ assert feats.n == 1
+ assert 300.2 < feats.keypoints[0, 0].item() < 300.3
+ assert corners[0][0, 0].item() == 300
+
def test_threshold_fallback_is_decided_per_image_5865(self, device, dtype):
# The weak image's maxima, 0.15 and 0.12, are below detection_threshold = 0.2, so it keeps the maxima above
# its mean score; the strong image keeps its maxima above 0.2. Each image gets the same keypoints alone and in
@@ -659,9 +721,8 @@ class TestConventionsALIKED(BaseTester):
@staticmethod
def _peak_tol(dtype):
- # An isolated peak lands on its pixel. In half precision DKD computes in the map's dtype, so the position is
- # checked to 0.25 px, half of the 0.5 px offset of an edge-aligned frame.
- return 0.25 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ # An isolated peak lands on its pixel; the keypoints are float32 for a half-precision model as well.
+ return 1e-4
def test_convention_aliked_keypoints_are_soft_argmax_peaks_in_the_pixel_frame(self, device, dtype):
# Keypoints are pixel coordinates (x, y) of the score map, wh = (W - 1, H - 1) with align_corners=True (the
@@ -687,10 +748,11 @@ class TestConventionsALIKED(BaseTester):
assert feats.n == 3
order = torch.argsort(feats.keypoints[:, 1] * 1000 + feats.keypoints[:, 0])
found, expected_i = feats.keypoints[order].cpu().double(), self._raster(expected_i)
- # bfloat16 loses the soft-argmax step, so in half precision only the isolated peaks are checked
isolated = (expected_i == expected_i.round()).all(dim=-1)
- checked = isolated if half else torch.ones_like(isolated)
- self.assert_close(found[checked], expected_i[checked], rtol=0.0, atol=self._peak_tol(dtype))
+ self.assert_close(found[isolated], expected_i[isolated], rtol=0.0, atol=self._peak_tol(dtype))
+ # the soft-argmax step runs in the model's dtype, and moves a half-precision keypoint by 3e-3 px at most
+ step_tol = 0.01 if half else 1e-4
+ self.assert_close(found[~isolated], expected_i[~isolated], rtol=0.0, atol=step_tol)
self.assert_close(lafs[0, :, :, 2], feats.keypoints)
self.assert_close(responses[0, :, 0], feats.keypoint_scores)
if not half:
@@ -723,14 +785,15 @@ class TestConventionsALIKED(BaseTester):
assert descs[1, 1:].abs().max() == 0
assert kornia.feature.laf_is_filled(lafs).tolist() == [[True, True, True], [True, False, False]]
tol = self._peak_tol(dtype)
- self.assert_close(lafs[1, 0, :, 2], torch.tensor([70.0, 20.0], device=device, dtype=dtype), rtol=0.0, atol=tol)
- eye = torch.eye(2, device=device, dtype=dtype)
+ coord = lafs.dtype # float32 for a half-precision model
+ self.assert_close(lafs[1, 0, :, 2], torch.tensor([70.0, 20.0], device=device, dtype=coord), rtol=0.0, atol=tol)
+ eye = torch.eye(2, device=device, dtype=coord)
self.assert_close(lafs_id[0, :, :, :2], eye.expand(3, 2, 2))
self.assert_close(lafs_id[1, 0, :, :2], eye)
assert lafs_id[1, 1:].abs().max() == 0
# the mask leaves (60, 40) in the first image: one keypoint in each image, so N = 1
assert lafs_masked.shape == (2, 1, 2, 3)
- expected = torch.tensor([[60.0, 40.0], [70.0, 20.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[60.0, 40.0], [70.0, 20.0]], device=device, dtype=coord)
self.assert_close(lafs_masked[:, 0, :, 2], expected, rtol=0.0, atol=tol)
def test_convention_aliked_counts_by_threshold_or_top_k(self, device, dtype):
@@ -828,7 +891,9 @@ class TestConventionsALIKED(BaseTester):
hook = self._hooked(aliked, self._score_map([(0, 31, 20, 0.9), (0, 70, 47, 0.8)], device, dtype))
rgb = torch.rand(1, 3, 50, 75, device=device, dtype=dtype)
gray = torch.rand(1, 1, 50, 75, device=device, dtype=dtype)
- expected = torch.tensor([[21.0, 13.0], [60.0, 40.0]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[21.0, 13.0], [60.0, 40.0]], device=device, dtype=torch.promote_types(dtype, torch.float32)
+ )
try:
with torch.no_grad():
for image in (rgb, gray):
diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.py
index 3ec26b051..4356a3731 100644
--- a/tests/feature/test_disk.py
+++ b/tests/feature/test_disk.py
@@ -84,6 +84,22 @@ class TestDisk(BaseTester):
assert heatmaps.dtype == dtype
assert descriptors.dtype == dtype
+ def test_half_model_returns_float32_keypoints(self, device, dtype):
+ # R4: keypoints are integer pixels, and bfloat16 holds no odd integer above 256, so a bfloat16 DISK put every
+ # keypoint past x = 256 on an even pixel. They are float32 now; scores and descriptors keep the model dtype.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ torch.manual_seed(0)
+ disk = DISK().to(device, dtype)
+ image = torch.rand(1, 3, 112, 400, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+ with torch.no_grad():
+ (feats,) = disk(image)
+ assert feats.keypoints.dtype == torch.float32
+ assert feats.detection_scores.dtype == dtype
+ assert feats.descriptors.dtype == dtype
+ x = feats.keypoints[:, 0]
+ assert (x[x > 256] % 2 != 0).any() # odd pixels past 256, which bfloat16 cannot hold
+
def test_not_divisible_by_16(self, device):
disk = DISK().to(device)
inp = torch.ones(1, 3, 72, 64, device=device)
@@ -253,7 +269,8 @@ class TestConventionsDISK(BaseTester):
expected = torch.tensor([[50.0, 9.0], [13.0, 21.0], [60.0, 33.0]], device=device, dtype=dtype)
image = torch.rand(1, 3, 48, 80, device=device, dtype=dtype)
(feats,) = self._disk(peaks, device, dtype)(image)
- self.assert_close(feats.keypoints, expected, rtol=0.0, atol=0.0)
+ # the keypoints are float32 for a half-precision network, the scores and descriptors keep its dtype
+ self.assert_close(feats.keypoints, expected.to(torch.promote_types(dtype, torch.float32)), rtol=0.0, atol=0.0)
self.assert_close(feats.detection_scores, torch.tensor([1.5, 2.0, 1.0], device=device, dtype=dtype))
named = torch.cat([expected, torch.ones_like(expected[:, :1])], dim=-1)
self.assert_close(feats.descriptors[:, :3], torch.nn.functional.normalize(named, dim=-1), low_tolerance=True)
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 006ce4f1f..50656a36f 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -223,6 +223,27 @@ class TestLocalFeatureMatcherEmptyPath(BaseTester):
assert out["lafs0"][0].shape == (0, 2, 3)
assert out["keypoints0"].shape == (0, 2)
+ def test_no_match_keypoints_keep_the_laf_dtype(self, device, dtype):
+ # Kornia's detectors return float32 LAFs for a float16 or bfloat16 image; a pair without matches returns
+ # keypoints and LAFs in the dtype a matched pair has, so the two concatenate without a cast.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")
+ matcher = kornia.feature.LocalFeatureMatcher(
+ kornia.feature.SIFTFeature(50), kornia.feature.DescriptorMatcher("nn")
+ ).to(device, dtype)
+ g = torch.Generator().manual_seed(0)
+ img = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 64, 80, generator=g), 3, 1, 1).to(device, dtype)
+ with torch.no_grad():
+ matched = matcher({"image0": img, "image1": img})
+ empty = matcher({"image0": torch.zeros_like(img), "image1": torch.zeros_like(img)})
+ assert matched["keypoints0"].shape[0] > 0
+ assert empty["keypoints0"].shape[0] == 0
+ for key in ("keypoints0", "keypoints1", "lafs0", "lafs1"):
+ assert matched[key].dtype == empty[key].dtype == torch.promote_types(dtype, torch.float32)
+ assert empty["confidence"].dtype == matched["confidence"].dtype == dtype
+
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
@@ -625,7 +646,7 @@ class TestSIFTFeatureHalfPrecision(BaseTester):
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
+ assert lafs.dtype == torch.float32 # pixel coordinates are float32 for a half-precision image
assert descs.dtype == torch.float16
assert int(lafs[0].ne(0).any(dim=-1).any(dim=-1).sum()) > 0
assert torch.isfinite(lafs).all()
@@ -706,8 +727,9 @@ class TestDoGHardNet(BaseTester):
assert lafs.shape == (2, 8, 2, 3)
assert responses.shape == (2, 8)
assert descriptors.shape == (2, 8, 128)
+ assert lafs.dtype == torch.promote_types(dtype, torch.float32) # float32 coordinates for a half image
+ assert responses.dtype == descriptors.dtype == dtype
for out in (lafs, responses, descriptors):
- assert out.dtype == dtype
assert out.device == image.device
def test_lafs_are_twice_the_dog_frames(self, device, dtype):
diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.py
index ced926706..006fb5995 100644
--- a/tests/feature/test_lightglue.py
+++ b/tests/feature/test_lightglue.py
@@ -595,6 +595,22 @@ class TestLightGluePruningDtype(BaseTester):
for key in ("matching_scores0", "matching_scores1"):
self.assert_close(out[key], ref[key].to(dtype))
+ def test_float32_keypoints_with_a_half_precision_model(self, device, dtype):
+ # kornia's detectors return float32 keypoints for a float16 or bfloat16 model; the positional encoding runs in
+ # the model's dtype, so wider keypoints give the result of keypoints in the model's dtype.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ data, _ = self._scene(device, dtype)
+ wide = torch.promote_types(dtype, torch.float32)
+ wide_data = {name: {**image, "keypoints": image["keypoints"].to(wide)} for name, image in data.items()}
+ model = self._model(device, dtype)
+ out, out_wide = self._forward(model, data), self._forward(model, wide_data)
+ assert self._floating_dtypes(out_wide) == {dtype}
+ for key in ("matches0", "matches1", "prune0", "prune1"):
+ self.assert_close(out_wide[key], out[key], rtol=0.0, atol=0.0)
+ for key in ("matching_scores0", "matching_scores1"):
+ self.assert_close(out_wide[key], out[key])
+
def test_no_descriptors_returns_the_input_dtype_5837(self, device, dtype):
empty = {
"keypoints": torch.empty(1, 0, 2, device=device, dtype=dtype),
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index e24e29f58..a7d6999ac 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -176,6 +176,22 @@ class TestLoFTR(BaseTester):
assert kpts0[:, 0].max() >= 8 * 5
assert kpts0[:, 1].max() >= 8 * 9
+ def test_half_model_returns_float32_keypoints(self, device, dtype):
+ # R4: bfloat16 keypoints resolve 2 px for x in [256, 512); the any-size slow test failed on that alone.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ model = _loftr_matching_every_cell(device, dtype)
+ g = torch.Generator().manual_seed(0)
+ image0 = torch.rand(1, 1, 300, 424, generator=g).to(device, dtype)
+ image1 = torch.rand(1, 1, 296, 432, generator=g).to(device, dtype)
+ with torch.no_grad():
+ out = model({"image0": image0, "image1": image1})
+ assert out["keypoints0"].dtype == torch.float32
+ assert out["keypoints1"].dtype == torch.float32
+ assert out["confidence"].dtype == dtype
+ far = out["keypoints1"][out["keypoints1"][:, 0] > 256, 0]
+ assert (far % 2 != 0).any() # sub-2-px positions exist past 256, which bfloat16 cannot hold
+
def test_mask_is_read_at_the_coarse_cell_pixels_5728(self, device, dtype):
# A coarse cell takes the mask value of the pixel it sits on, (8x, 8y). The masks are 1 only on those pixels
# (image0: on the ones with y < 64 and x < 40, so coarse rows 0..7 and columns 0..4), so every such cell is
@@ -650,11 +666,38 @@ class TestCoarseMatching(BaseTester):
cm = CoarseMatching(self.CFG).to(device).eval()
out = cm.get_coarse_match(conf, data)
assert out["i_ids"].tolist() == i_ids.tolist()
- expected0 = torch.tensor([[0, 0], [8, 8], [16, 40], [64, 96]], device=device, dtype=dtype)
- expected1 = torch.tensor([[24, 0], [56, 24], [0, 56], [80, 88]], device=device, dtype=dtype)
+ # the keypoints are float32 for a half-precision confidence matrix
+ coord = torch.promote_types(dtype, torch.float32)
+ expected0 = torch.tensor([[0, 0], [8, 8], [16, 40], [64, 96]], device=device, dtype=coord)
+ expected1 = torch.tensor([[24, 0], [56, 24], [0, 56], [80, 88]], device=device, dtype=coord)
self.assert_close(out["mkpts0_c"], expected0, rtol=0.0, atol=0.0)
self.assert_close(out["mkpts1_c"], expected1, rtol=0.0, atol=0.0)
+ def test_coarse_coordinates_are_built_before_scaling(self, device):
+ # Plan review P5: with a half `scale0`, main scaled the integer cell indices in half precision and cast
+ # afterwards. LoFTR.forward never passes scale0/scale1, so this drives get_coarse_match directly.
+ # bfloat16(1.37) == 1.3671875; cell x = 39 sits at 39 * 8 * 1.3671875 = 426.5625, which bfloat16 rounds to 426.
+ h_c, w_c = 2, 40
+ n = h_c * w_c
+ conf = torch.zeros(1, n, n, device=device, dtype=torch.bfloat16)
+ conf[0, torch.arange(n), torch.arange(n)] = 0.9 # every cell is its own mutual nearest neighbour
+ scale = torch.tensor([[1.37, 1.37]], device=device, dtype=torch.bfloat16)
+ data = {
+ "hw0_c": (h_c, w_c),
+ "hw1_c": (h_c, w_c),
+ "hw0_i": (h_c * 8, w_c * 8),
+ "hw1_i": (h_c * 8, w_c * 8),
+ "stride_c": 8,
+ "scale0": scale,
+ "scale1": scale,
+ }
+ out = CoarseMatching(self.CFG).to(device).eval().get_coarse_match(conf, data)
+ i = out["i_ids"]
+ expected = torch.stack([i % w_c, i // w_c], 1).to(torch.float32) * (8 * 1.3671875)
+ assert out["mkpts0_c"].dtype == torch.float32
+ assert out["mkpts1_c"].dtype == torch.float32
+ assert torch.equal(out["mkpts0_c"], expected) # products of small integers and 1.3671875: exact in float32
+
class TestCoarseMatchingSelection(BaseTester):
"""The row max / column max selection and the dual softmax against their reference formulations."""
@@ -1163,8 +1206,9 @@ class TestConventionsLoFTR(BaseTester):
# the pretrained models put pixel centres at +0.5 (subtract 0.5 for kornia's frame).
expected0 = [[56.0, 24.0], [16.0, 40.0], [24.0, 16.0]]
expected1 = [[24.0 + 2.0, 40.0 - 2.0], [48.0 - 4.0, 16.0 + 4.0], [56.0 + 4.0, 32.0]]
- self.assert_close(out["keypoints0"], torch.tensor(expected0, device=device, dtype=dtype))
- self.assert_close(out["keypoints1"], torch.tensor(expected1, device=device, dtype=dtype))
+ coord = torch.promote_types(dtype, torch.float32) # the keypoints are float32 for a half-precision model
+ self.assert_close(out["keypoints0"], torch.tensor(expected0, device=device, dtype=coord))
+ self.assert_close(out["keypoints1"], torch.tensor(expected1, device=device, dtype=coord))
assert out["batch_indexes"].tolist() == [0, 0, 1]
# confidence is the coarse dual-softmax score: similarity 16 * 16 / 256 / 0.1 = 10 against the zero similarity
# of the 79 other cells of image 1 and the 87 other cells of image 0. The pair of amplitude 4 (similarity
@@ -1177,8 +1221,8 @@ class TestConventionsLoFTR(BaseTester):
swapped = self._hooked_loftr(device, dtype, swap=True)({"image0": image1, "image1": image0})
expected0 = [[48.0, 16.0], [24.0, 40.0], [56.0, 32.0]]
expected1 = [[16.0 - 4.0, 40.0 + 4.0], [56.0 + 2.0, 24.0 - 2.0], [24.0 + 4.0, 16.0]]
- self.assert_close(swapped["keypoints0"], torch.tensor(expected0, device=device, dtype=dtype))
- self.assert_close(swapped["keypoints1"], torch.tensor(expected1, device=device, dtype=dtype))
+ self.assert_close(swapped["keypoints0"], torch.tensor(expected0, device=device, dtype=coord))
+ self.assert_close(swapped["keypoints1"], torch.tensor(expected1, device=device, dtype=coord))
assert swapped["batch_indexes"].tolist() == [0, 0, 1]
@pytest.mark.slow
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 9d3bee324..1fbe0d73e 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -21,13 +21,14 @@ from torch.utils._python_dispatch import TorchDispatchMode
import kornia
from kornia.core.check import ShapeError
+from kornia.feature import KeyNetDetector
from kornia.feature.scale_space_detector import (
MultiResolutionDetector,
ScaleSpaceDetector,
_resize_mask,
get_default_detector_config,
)
-from kornia.geometry.subpix import AdaptiveQuadInterp3d, ConvQuadInterp3d, IterativeQuadInterp3d
+from kornia.geometry.subpix import AdaptiveQuadInterp3d, ConvQuadInterp3d, ConvSoftArgmax3d, IterativeQuadInterp3d
from kornia.geometry.transform import ScalePyramid
from testing.base import (
@@ -208,7 +209,11 @@ class TestScaleSpaceDetector(BaseTester):
n_feats = 1
det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)
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_laf = torch.tensor(
+ [[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]],
+ device=device,
+ dtype=torch.promote_types(dtype, torch.float32),
+ )
expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)
# 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.
@@ -226,7 +231,11 @@ class TestScaleSpaceDetector(BaseTester):
n_feats = 1
det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)
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_laf = torch.tensor(
+ [[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]],
+ device=device,
+ dtype=torch.promote_types(dtype, torch.float32),
+ )
expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)
# 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.
@@ -245,7 +254,7 @@ class TestScaleSpaceDetector(BaseTester):
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 lafs.dtype == torch.promote_types(dtype, torch.float32)
assert resps.dtype == dtype
def test_mask_spatial_size_must_match_the_image(self, device, dtype):
@@ -443,7 +452,9 @@ class TestScaleSpaceDetector(BaseTester):
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)
+ self.assert_close(
+ lafs[0, 0, :, 2], torch.tensor([31.6, 48.0], device=device, dtype=lafs.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
@@ -473,6 +484,19 @@ class TestScaleSpaceDetector(BaseTester):
assert 0 < int(filled[0].sum()) < 20
assert bool((resps[~filled] == 0).all())
+ def test_float_weights_are_cast_to_the_response_dtype(self, device, dtype):
+ # The refinement runs on a float32 copy of a half-precision response, but the weights are still cast to the
+ # response's dtype first: a weight of 1e-8 is zero in float16, where it suppresses, and positive otherwise.
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ _skip_without_half_padding(device, dtype)
+ g = torch.Generator().manual_seed(0)
+ img = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 96, 128, generator=g), 5, 1, 2).to(device, dtype)
+ det = ScaleSpaceDetector(8).to(device, dtype)
+ assert bool(kornia.feature.laf_is_filled(det(img)[0]).any())
+ lafs, _ = det(img, torch.full((1, 1, 96, 128), 1e-8, device=device))
+ assert bool(kornia.feature.laf_is_filled(lafs).any()) == (dtype != torch.float16)
+
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
@@ -505,8 +529,8 @@ class TestScaleSpaceDetector(BaseTester):
centers = lafs[0, :, :, 2]
# The maximum sits at octave pixel W_o // 2 of the 96, 48 and 24 px octaves, which ScalePyramid's
# align_corners=True resizes put at 48, 24 * 95 / 47 and 12 * 95 / 23 in the input.
- expected = torch.tensor([48.0, 24 * 95 / 47, 12 * 95 / 23], device=device, dtype=dtype)
- atol = {torch.float16: 0.02, torch.bfloat16: 0.13, torch.float32: 1e-4}.get(dtype, 1e-9)
+ expected = torch.tensor([48.0, 24 * 95 / 47, 12 * 95 / 23], device=device, dtype=centers.dtype)
+ atol = 1e-9 if dtype == torch.float64 else 1e-4 # float32 centres for float16 and bfloat16 images too
found = torch.isclose(centers[:, None, :], expected[None, :, None], rtol=0.0, atol=atol).all(-1).any(0)
assert bool(found.all()), f"expected the three maxima at {expected.tolist()}, got {centers.tolist()}"
@@ -827,6 +851,37 @@ class TestScaleSpaceDetector(BaseTester):
det = ScaleSpaceDetector(2, subpix_module=ConvQuadInterp3d(10)).to(device)
self.gradcheck(det, patches, nondet_tol=1e-4)
+ @pytest.mark.parametrize("refiner", ["adaptive", "conv_quad", "iterative", "soft_argmax"])
+ def test_half_image_refines_coordinates_in_float32(self, refiner, device, dtype):
+ # R4 / plan review P2: the refiners write absolute coordinates into a tensor of the response's dtype, and
+ # bfloat16 holds no odd integer above 256 (torch.arange(257, 263, dtype=bfloat16) == [256, 258, 260, 260,
+ # 260, 262]); float16 holds only multiples of 0.25 in [256, 512). The refiner sees a float32 response, so the
+ # refined centres past x = 256 lie off that grid; a centre rounded through the half dtype in the image frame
+ # lies on it, whatever the LAF dtype.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ _skip_without_half_padding(device, dtype)
+ refiners = {
+ "adaptive": AdaptiveQuadInterp3d,
+ "conv_quad": ConvQuadInterp3d,
+ "iterative": IterativeQuadInterp3d,
+ "soft_argmax": ConvSoftArgmax3d,
+ }
+ g = torch.Generator().manual_seed(0)
+ img = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 300, 420, generator=g), 5, 1, 2).to(device, dtype)
+ det = ScaleSpaceDetector(200, subpix_module=refiners[refiner]()).to(device, dtype)
+ seen = []
+ det.subpix.register_forward_pre_hook(lambda mod, args: seen.append(args[0].dtype))
+ with torch.no_grad():
+ lafs, responses = det(img)
+ assert set(seen) == {torch.float32}
+ assert lafs.dtype == torch.float32
+ assert responses.dtype == dtype
+ x = lafs[0, :, 0, 2]
+ far = x[x > 256]
+ assert far.numel() > 20
+ assert (far != far.to(dtype).float()).float().mean() > 0.5
+
class TestMultiResolutionDetector(BaseTester):
def _make_detector(self, num_features: int = 50, **config_overrides):
@@ -834,6 +889,20 @@ class TestMultiResolutionDetector(BaseTester):
cfg.update(config_overrides)
return MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=num_features, config=cfg)
+ def test_multi_resolution_half_image_gives_float32_lafs(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ _skip_without_half_padding(device, dtype)
+ g = torch.Generator().manual_seed(0)
+ img = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 300, 420, generator=g), 5, 1, 2).to(device, dtype)
+ torch.manual_seed(1) # random KeyNet weights; those of seed 0 give no positive response maximum at all
+ lafs, responses = KeyNetDetector(False, num_features=100).to(device, dtype)(img)
+ assert lafs.dtype == torch.float32
+ assert responses.dtype == dtype
+ x = lafs[0, :, 0, 2]
+ assert x[x > 256].numel() > 20
+ assert (x[x > 256] % 2 != 0).any()
+
def test_shape(self, device, dtype):
inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
det = self._make_detector().to(device, dtype)
@@ -983,7 +1052,7 @@ class TestMultiResolutionDetector(BaseTester):
resp[0, 0, 32, 16], resp[0, 0, 32, 12], resp[0, 0, 32, 40] = 1.0, 2.0, 0.5
lafs, resps = det(resp)
self.assert_close(resps, torch.tensor([[0.5, 0.0]], device=device, dtype=dtype))
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([40.0, 32.0], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([40.0, 32.0], device=device, dtype=lafs.dtype))
def test_remove_borders_writes_an_exact_zero(self, device, dtype):
# A 0/1 mask multiplied into the scores turns an infinite score inside the strip into NaN, which
@@ -1001,7 +1070,7 @@ class TestMultiResolutionDetector(BaseTester):
assert torch.equal(det.remove_borders(score, borders=0), score)
lafs, resps = det(score)
self.assert_close(resps, torch.ones_like(resps))
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([32.0, 32.0], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([32.0, 32.0], device=device, dtype=lafs.dtype))
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
@@ -1197,27 +1266,26 @@ class TestMultiResolutionDetector(BaseTester):
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.
+ def test_half_precision_gives_float32_lafs_and_half_responses(self, device, half_dtype):
+ # Pixel coordinates are float32 for a half-precision image: bfloat16 holds no odd pixel above 256. The
+ # responses keep the response function's dtype.
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 lafs.dtype == torch.float32
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.
+ # responses to float32. The LAFs are float32 for a half-precision image either way.
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 lafs.dtype == torch.float32
assert resps.dtype == half_dtype
def test_color_input_with_single_channel_response(self, device, dtype):
@@ -1522,7 +1590,8 @@ class TestConventionsScaleSpaceDetector(BaseTester):
def test_convention_scale_space_detector_centre_is_sub_pixel_in_the_laf_frame(self, device, dtype):
# A blob of sigma 2.5 centred at x = 25.4, y = 18.6 (pixel centres at integers, LAF frame) on a 48 x 72 image is
# found at its centre to sub-pixel accuracy, and the other 15 slots are padding: zero LAF, zero response.
- # Measured on CPU: (25.4001, 18.5999) in float32 and float64. bfloat16 spaces values in [16, 32) by 0.125.
+ # Measured on CPU: (25.4001, 18.5999) in float32 and float64. The centres are float32 for a half-precision
+ # image, and the half-precision response moves them by about 0.05 px in bfloat16 and 0.01 px in float16.
_skip_without_half_padding(device, dtype)
tol = 0.15 if dtype == torch.bfloat16 else 0.05
img = _conv_blob(25.4, 18.6, 2.5, 48, 72, device, dtype)
@@ -1530,7 +1599,7 @@ class TestConventionsScaleSpaceDetector(BaseTester):
# relabelling: the transposed image swaps the centre's coordinates
for image, centre in ((img, (25.4, 18.6)), (img.transpose(-1, -2).contiguous(), (18.6, 25.4))):
lafs, resps = det(image)
- expected = torch.tensor(centre, device=device, dtype=dtype)
+ expected = torch.tensor(centre, device=device, dtype=lafs.dtype)
self.assert_close(lafs[0, 0, :, 2], expected, rtol=0.0, atol=tol)
assert resps[0, 0] > 0
assert bool((lafs[0, 1:] == 0).all())
@@ -1626,7 +1695,7 @@ class TestConventionsScaleSpaceDetector(BaseTester):
filled[n] = kornia.feature.laf_is_filled(lafs)[0].tolist()
assert filled[1] == [False]
assert filled[2] == [True, False]
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=lafs.dtype))
self.assert_close(resps[0, 0], torch.tensor(-0.5, device=device, dtype=dtype))
@pytest.mark.parametrize(
@@ -1660,7 +1729,7 @@ class TestConventionsScaleSpaceDetector(BaseTester):
lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, 64, 96, device=device, dtype=dtype))
n = len(values)
assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True] * n + [False] * (8 - n)
- self.assert_close(lafs[0, :n, :, 2], torch.tensor(centres, device=device, dtype=dtype))
+ self.assert_close(lafs[0, :n, :, 2], torch.tensor(centres, device=device, dtype=lafs.dtype))
self.assert_close(resps[0, :n], torch.tensor(values, device=device, dtype=dtype))
@pytest.mark.parametrize("minima_are_also_good", [False, True])
@@ -1684,7 +1753,7 @@ class TestConventionsScaleSpaceDetector(BaseTester):
assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [False, False]
return
assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True, False]
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([20.375, 30.375], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([20.375, 30.375], device=device, dtype=lafs.dtype))
self.assert_close(resps[0, 0], torch.tensor(0.3, device=device, dtype=dtype))
def test_convention_scale_space_detector_masks_candidates_before_the_top_k(self, device, dtype):
@@ -1698,10 +1767,10 @@ class TestConventionsScaleSpaceDetector(BaseTester):
det = ScaleSpaceDetector(1, resp_module=_TwoMaxima(), scale_space_response=True, mr_size=2.0).to(device, dtype)
lafs, resps = det(img, mask)
assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True]
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=lafs.dtype))
self.assert_close(resps[0, 0], torch.tensor(-0.5, device=device, dtype=dtype))
lafs, _ = det(img)
- self.assert_close(lafs[0, 0, :, 2], torch.tensor([40.0, 50.0], device=device, dtype=dtype))
+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([40.0, 50.0], device=device, dtype=lafs.dtype))
class TestConventionsMultiResolutionDetector(BaseTester):
@@ -1717,7 +1786,7 @@ class TestConventionsMultiResolutionDetector(BaseTester):
_skip_without_half_padding(device, dtype)
cfg = get_default_detector_config()
cfg.update(pyramid_levels=1, up_levels=0, scale_factor_levels=2.0)
- tol = 0.15 if dtype == torch.bfloat16 else 1e-3 # bfloat16 spaces values in [32, 64) by 0.25
+ tol = 1e-3 # the LAFs are float32 for a half-precision image as well
for transposed in (False, True):
if transposed: # relabelling: the transposed image reports swapped coordinates
size, peaks = (128, 69), {(128, 69): ((31, 45), 1.0), (64, 34): ((17, 20), 0.5)}
@@ -1735,8 +1804,8 @@ class TestConventionsMultiResolutionDetector(BaseTester):
lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, *size, device=device, dtype=dtype))
self.assert_close(resps, torch.tensor([[1.0, 0.5, 0.0, 0.0]], device=device, dtype=dtype))
expected = kornia.feature.laf_from_center_scale_ori(
- torch.tensor([centres], device=device, dtype=dtype),
- torch.tensor([22.0, 44.3235294], device=device, dtype=dtype).view(1, 2, 1, 1),
+ torch.tensor([centres], device=device, dtype=lafs.dtype),
+ torch.tensor([22.0, 44.3235294], device=device, dtype=lafs.dtype).view(1, 2, 1, 1),
)
self.assert_close(lafs[:, :2], expected, rtol=0.0, atol=tol)
assert bool((lafs[0, 2:] == 0).all())
diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.py
index 322d2726f..824423d58 100644
--- a/tests/feature/test_sift_scale_space.py
+++ b/tests/feature/test_sift_scale_space.py
@@ -457,7 +457,33 @@ class TestSharedSIFTScaleSpace(BaseTester):
assert isinstance(feature.detector, _SIFTScaleSpaceDetector)
lafs, responses, descriptors = feature(torch.rand(1, 1, 33, 35, device=device, dtype=dtype))
assert lafs.shape == (1, 8, 2, 3)
- assert responses.dtype == descriptors.dtype == lafs.dtype == dtype
+ assert responses.dtype == descriptors.dtype == dtype
+ assert lafs.dtype == torch.promote_types(dtype, torch.float32) # float32 LAFs for a half-precision image
+
+ @pytest.mark.parametrize("backend", ["patch", "pyramid"])
+ def test_half_image_gives_float32_lafs(self, device, dtype, backend):
+ # bfloat16 holds only even values in [256, 512) and float16 only multiples of 0.25 there, so half-precision
+ # LAFs put every refined centre past x = 256 on that grid. The LAFs are float32 on both backends; the responses
+ # and descriptors keep the image dtype. An empty batch gives float32 LAFs as well (pyramid backend; the patch
+ # backend's ScaleSpaceDetector does not take an empty batch).
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision rule")
+ half_padding = supports_replicate_padding(device, dtype) and supports_reflect_padding(device, dtype)
+ if backend == "patch" and not half_padding:
+ pytest.skip("the patch backend pads the half-precision image; the pyramid backend promotes it")
+ g = torch.Generator().manual_seed(0)
+ img = F.avg_pool2d(torch.rand(1, 1, 300, 420, generator=g), 5, 1, 2).to(device, dtype)
+ feature = SIFTFeatureScaleSpace(300, descriptor_backend=backend).to(device, dtype)
+ with torch.no_grad():
+ lafs, responses, descriptors = feature(img)
+ if backend == "pyramid":
+ assert feature(img[:0])[0].dtype == torch.float32
+ assert lafs.dtype == torch.float32
+ assert responses.dtype == descriptors.dtype == dtype
+ x = lafs[0, :, 0, 2]
+ far = x[x > 256]
+ assert far.numel() > 20
+ assert (far != far.to(dtype).float()).float().mean() > 0.5
def test_large_frame_is_described_in_half_precision(self, device, dtype):
# Products of two entries of the first LAF overflow float16 (det 300 * 280 + 40 * 25 = 85000 > 65504).
@@ -808,7 +834,8 @@ class TestSIFTScaleSpaceDetector(BaseTester):
lafs, responses = detector(image)
filled = laf_is_filled(lafs)
assert filled[0, 0]
- expected = torch.tensor([11.2 * 0.5, 10.3 * 0.5], device=device, dtype=dtype)
+ # the LAFs are float32 for a half-precision image
+ expected = torch.tensor([11.2 * 0.5, 10.3 * 0.5], device=device, dtype=lafs.dtype)
self.assert_close(get_laf_center(lafs)[0, 0], expected, rtol=2e-3, atol=2e-3)
amplitude = 1e-4 if dtype == torch.float16 else 1e-8
tiny_lafs, tiny_responses = _SIFTScaleSpaceDetector(4, _FixedPyramid(dog * amplitude)).to(device, dtype)(image)
@@ -867,7 +894,7 @@ class TestSIFTScaleSpaceDetector(BaseTester):
dog = _quadratic_dog(device, dtype, center=(2.2, 26.3, 26.2))
lafs, _ = _SIFTScaleSpaceDetector(1, _FixedPyramid(dog))(image)
assert laf_is_filled(lafs).all()
- expected = torch.tensor([26.2, 26.3], device=device, dtype=dtype) * 0.5
+ expected = torch.tensor([26.2, 26.3], device=device, dtype=lafs.dtype) * 0.5
self.assert_close(get_laf_center(lafs)[0, 0], expected, atol=0.01, rtol=0.001)
def test_topk_sorts_by_refined_response(self, device, dtype):
@@ -878,7 +905,7 @@ class TestSIFTScaleSpaceDetector(BaseTester):
lafs, scores = _SIFTScaleSpaceDetector(2, _FixedPyramid(dog))(image)
assert laf_is_filled(lafs).all()
assert scores[0, 0] > scores[0, 1]
- expected = torch.tensor([[21.2, 10.3], [11.2, 10.3]], device=device, dtype=dtype) * 0.5
+ expected = torch.tensor([[21.2, 10.3], [11.2, 10.3]], device=device, dtype=lafs.dtype) * 0.5
self.assert_close(get_laf_center(lafs)[0], expected, atol=0.01, rtol=0.001)
def test_refinement_backward_is_finite(self, device):
@@ -893,10 +920,8 @@ class TestConventionsSIFTFeatureScaleSpace(BaseTester):
def test_convention_pyramid_backend_centres_are_pixel_centres_at_every_octave(self, device, dtype):
# Three bright blobs (x, y, sigma) at non-integer centres of a 120 x 176 image, detected on octaves 0, 1 and 2.
# The pyramid backend maps every octave's pixel back to the image's pixel-centre frame, so each centre is
- # within 0.1 px of its blob. Half-precision input is detected in float32 and the LAFs are cast to the dtype at
- # the end, which adds half a unit in the last place at coordinates below 128: 0.25 px in bfloat16, 1 / 32 px
- # in float16.
- tol = 0.1 + {torch.bfloat16: 0.25, torch.float16: 1.0 / 32}.get(dtype, 0.0)
+ # within 0.1 px of its blob. Half-precision input is detected in float32 and the LAFs stay float32.
+ tol = 0.1
blobs = [(37.3, 41.6, 1.5), (112.7, 38.2, 3.5), (71.4, 84.3, 8.0)]
yy, xx = torch.meshgrid(
torch.arange(120, dtype=torch.float64), torch.arange(176, dtype=torch.float64), indexing="ij"
diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.py
index d4cd83ea7..5b06f98d5 100644
--- a/tests/feature/test_xfeat.py
+++ b/tests/feature/test_xfeat.py
@@ -175,6 +175,16 @@ class TestXFeat(BaseTester):
with pytest.raises(Exception):
model.detectAndCompute(torch.rand(3, 64, 64, device=device)) # missing batch dim
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])
+ def test_wart_half_weights_raise_5957(self, half, device):
+ # Known defect #5957: _preprocess_tensor calls x.float(), so half-precision weights meet float32 input.
+ # CPU: "expected scalar type Float but found Half"; MPS and CUDA: "Input type (...) and weight type (...)".
+ model = XFeat().to(device, half)
+ with pytest.raises(
+ RuntimeError, match=r"expected scalar type Float but found|Input type \(.*\) and weight type"
+ ):
+ model.detectAndCompute(torch.rand(1, 3, 96, 128, device=device, dtype=half), top_k=50)
+
def test_gradcheck(self, device):
pass # inference_mode on detectAndCompute; gradcheck not applicable