Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): MKD pcaws for small output_dims, half-precision laf_is_valid, non-contiguous descriptor outputs (#5834)

Dmytro Mishkin89cdca35c0f3
diff --git a/changelog.d/5834.fixed.md b/changelog.d/5834.fixed.md
new file mode 100644
index 000000000..7de2426c6
--- /dev/null
+++ b/changelog.d/5834.fixed.md
@@ -0,0 +1,7 @@
+`MKDDescriptor` and `Whitening` with `whitening="pcaws"` and `output_dims` of 40 or less raised `IndexError: index 40 is out of bounds` at construction, because the shrinkage weight (the eigenvalue at index `keval=40`) was read after the spectrum had been truncated to `output_dims`. It is now read from the whitening model's full spectrum, so a smaller `output_dims` keeps the leading columns of the larger transform; `output_dims` of 41 or more gives the same descriptors as before. A `keval` outside `0 <= keval < len(eigvals)` now raises a `ValueError` that says so: a negative `keval` of `Whitening`, which indexed the spectrum truncated to `output_dims` (or raised `IndexError` below `-output_dims`), is no longer accepted.
+
+`MKDDescriptor` now raises a `ShapeError` (a `ValueError`) for patches that are not `(B, 1, patch_size, patch_size)`; a patch of another size used to fail deep inside with torch's broadcast `RuntimeError`, a three-channel patch with a `ValueError` that reported five channels, and an input that is not 4-D with a plain `ValueError`.
+
+`laf_is_valid`, `get_laf_scale` and `make_upright` formed products of two LAF entries in float16, which broke every float16 LAF for which such a product exceeds 65504. Any LAF of scale 256 px or more was reported invalid, had an `inf` scale and a `nan` upright frame; `make_upright` already overflowed for an elongated LAF whose first row is 256 px or longer (300 x 20 px, a scale of 77 px), for which `LAFAffineShapeEstimator` returned an `inf` frame. They now compute in float32 for float16 LAFs and return the mask, scale and frame as before; float32, float64 and bfloat16 results are unchanged. With it, `LAFAffineShapeEstimator` and `LAFAffNetShapeEstimator` estimate such a float16 LAF instead of returning a zero-shape or `inf` frame (or the input unchanged with `preserve_orientation=True`), and `SIFTFeatureScaleSpace` with `descriptor_backend="pyramid"` describes it instead of returning the zero descriptor of a padded slot.
+
+`get_laf_descriptors` and `LAFDescriptor` raised `RuntimeError: view size is not compatible with input tensor's size and stride` when the descriptor module returned a tensor whose per-patch dimensions are not contiguous, such as a transposed block or a channels-last convolution output; the output is now reshaped instead of viewed.
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index d07c43ca0..e0ec57765 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -165,7 +165,7 @@ def get_laf_descriptors(
warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.Tensor", stacklevel=1)
# Probe the descriptor for its output width instead of assuming 128, so the empty result
# has the same trailing dimension and dtype as a non-empty one. The non-empty path ends in
- # `.view(B, N, -1)`, which flattens everything the descriptor produced per patch, so the
+ # `.reshape(B, N, -1)`, which flattens everything the descriptor produced per patch, so the
# matching width is the whole probe -- `probe.shape[-1]` would only agree for descriptors
# whose output is 2-D. The probe has a batch of one, so its numel is that width.
with torch.no_grad():
@@ -179,7 +179,8 @@ def get_laf_descriptors(
# Descriptor accepts standard torch.Tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
B, N, CH, H, W = patches.size()
- return _run_descriptor(patch_descriptor, patches.view(B * N, CH, H, W)).view(B, N, -1)
+ # `reshape`, not `view`: a descriptor may return a non-contiguous output, e.g. a channels-last convolution.
+ return _run_descriptor(patch_descriptor, patches.view(B * N, CH, H, W)).reshape(B, N, -1)
class LAFDescriptor(nn.Module):
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 2ec7587f3..dc3e6a62e 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -27,9 +27,26 @@ from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
+def _laf_product_dtype(dtype: torch.dtype) -> torch.dtype:
+ """Return the dtype to multiply two LAF entries in.
+
+ A product of two entries of an ordinary LAF can leave the float16 range. It overflows above 65504: the determinant
+ of any LAF of scale 256 px or more, and the square of a 256 px entry of an elongated LAF of a smaller scale (300 x
+ 20 px has a scale of 77 px). It rounds to zero for entries below about 1.7e-4. float16 therefore works in float32,
+ which holds every product of two float16 values exactly. bfloat16 has the exponent range of float32 and is left as
+ it is.
+ """
+ if dtype == torch.float16:
+ return torch.float32
+ return dtype
+
+
def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
"""Return a scale of the LAFs.
+ The determinant of a float16 LAF is formed in float32, so that a LAF whose entry products leave the float16 range
+ does not overflow; the scale is returned in the LAF dtype.
+
Args:
LAF: :math:`(B, N, 2, 3)`
@@ -43,13 +60,21 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
eps = 1e-10
- out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] - LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + eps
- return out.abs().sqrt()
+ work = LAF.to(_laf_product_dtype(LAF.dtype))
+ out = work[..., 0:1, 0:1] * work[..., 1:2, 1:2] - work[..., 1:2, 0:1] * work[..., 0:1, 1:2] + eps
+ scale = out.abs().sqrt()
+ if work.dtype != LAF.dtype:
+ scale = scale.to(LAF.dtype)
+ return scale
def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
"""Check that each LAF is finite and has a finite, nonzero determinant.
+ The determinant of a float16 LAF is formed in float32, so the LAF is not judged by an intermediate outside the
+ float16 range: one whose entry products overflow float16 (for instance any LAF of scale 256 px or more) is valid,
+ and so is one whose determinant is too small for float16.
+
Args:
laf: :math:`(B, N, 2, 3)`.
@@ -63,6 +88,7 @@ def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(laf)
+ laf = laf.to(_laf_product_dtype(laf.dtype))
det = laf[..., 0, 0] * laf[..., 1, 1] - laf[..., 1, 0] * laf[..., 0, 1]
return laf.isfinite().all(dim=-1).all(dim=-1) & det.isfinite() & (det != 0)
@@ -231,7 +257,8 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""Rectify the affine matrix, so that it becomes upright.
The all-zero LAF that pads an unfilled detector slot (see :func:`laf_is_filled`) is returned unchanged, so the
- padding stays recognizable.
+ padding stays recognizable. A float16 LAF is rectified in float32, so that a LAF whose entry products leave the
+ float16 range does not overflow; the result is returned in the LAF dtype.
Args:
laf: :math:`(B, N, 2, 3)`
@@ -246,6 +273,8 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(laf)
+ dtype = laf.dtype
+ laf = laf.to(_laf_product_dtype(dtype))
# Differentiate through an identity frame in place of the zero padding: sqrt at exactly zero has an infinite
# derivative, which torch.where below would turn into nan rather than mask.
filled = laf_is_filled(laf)[..., None, None]
@@ -268,7 +297,10 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
upright = scale_laf(laf_unit_scale, scale)
# The padding LAF would otherwise come back as a tiny nonzero frame (the determinant and the division carry eps).
- return torch.where(filled, upright, padding)
+ out = torch.where(filled, upright, padding)
+ if laf.dtype != dtype:
+ out = out.to(dtype)
+ return out
def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index ab6c40523..ce0a63451 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -21,6 +21,7 @@ from typing import Any, Dict, List, Tuple, Union
import torch
from torch import nn
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.download import load_state_dict_from_url
from kornia.core.utils import _l2_normalize
from kornia.filters import GaussianBlur2d, SpatialGradient
@@ -416,15 +417,17 @@ class Whitening(nn.Module):
whitening_model: Dictionary with keys 'mean', 'eigvecs', 'eigvals' holding Tensors.
in_dims: Dimensionality of input descriptors.
output_dims: (int) Dimensionality reduction.
- keval: Shrinkage parameter.
+ keval: Shrinkage parameter: ``'pcaws'`` replaces each kept eigenvalue ``lambda`` by ``(1 - alpha) * lambda +
+ alpha``, a shrinkage towards 1 with weight ``alpha``, the eigenvalue at index ``keval`` (``0 <= keval <
+ len(eigvals)``) of the whitening model's full spectrum, whatever ``output_dims`` is.
t: Attenuation parameter.
Returns:
l2-normalized, whitened descriptors.
Shape:
- - Input: (B, in_dims, fmap_size, fmap_size)
- - Output: (B, out_dims, fmap_size, fmap_size)
+ - Input: :math:`(N, in_{dims})`.
+ - Output: :math:`(N, output_{dims})`.
Examples:
>>> descs = torch.rand(23, 238)
@@ -437,7 +440,8 @@ class Whitening(nn.Module):
... output_dims=128,
... keval=40,
... t=0.7)
- >>> wdescs = whitening(descs) # 23x128
+ >>> whitening(descs).shape
+ torch.Size([23, 128])
"""
@@ -487,7 +491,7 @@ class Whitening(nn.Module):
modifications = {
"pca": self._modify_pca,
"lw": self._modify_lw,
- "pcaws": self._modify_pcaws,
+ "pcaws": lambda: self._modify_pcaws(wh_model["eigvals"]),
"pcawt": self._modify_pcawt,
}
@@ -501,9 +505,20 @@ class Whitening(nn.Module):
def _modify_lw(self) -> None:
"""No modification required."""
- def _modify_pcaws(self) -> None:
- """Shrinkage for eigenvalues."""
- alpha = self.evals[self.keval]
+ def _modify_pcaws(self, eigvals: torch.Tensor) -> None:
+ """Shrink each kept eigenvalue towards 1: ``(1 - alpha) * lambda + alpha`` with ``alpha = eigvals[keval]``.
+
+ The shrinkage weight ``alpha`` is a property of the whitening model, not of how many components are kept, so it
+ is read from the full spectrum ``eigvals`` before truncation to ``output_dims``: keeping fewer components only
+ drops columns.
+ """
+ n = eigvals.shape[0]
+ if not 0 <= self.keval < n:
+ raise ValueError(
+ f"pcaws needs the eigenvalue at index keval={self.keval} of the whitening model's spectrum, which has "
+ f"{n} eigenvalues (0 <= keval < {n})."
+ )
+ alpha = eigvals[self.keval]
evals = ((1 - alpha) * self.evals) + alpha
self.evecs.data = self.evecs @ torch.diag(torch.pow(evals, -0.5))
@@ -553,8 +568,8 @@ class MKDDescriptor(nn.Module):
Explicit cartesian or polar embedding.
Shape:
- - Input: :math:`(B, in_{dims}, fmap_{size}, fmap_{size})`.
- - Output: :math:`(B, out_{dims}, fmap_{size}, fmap_{size})`,
+ - Input: :math:`(B, 1, P, P)` with :math:`P` = ``patch_size``; the spatial encoding is precomputed for it.
+ - Output: :math:`(B, out_{dims})`.
Examples:
>>> patches = torch.rand(23, 1, 32, 32)
@@ -634,17 +649,19 @@ class MKDDescriptor(nn.Module):
"""Compute Multiple Kernel Descriptor (MKD) vectors for image patches.
Args:
- patches: Grayscale patch tensor with shape :math:`(B, 1, H, W)`, where
- ``B`` is the number of patches and ``H``/``W`` are patch dimensions.
+ patches: Grayscale patch tensor with shape :math:`(B, 1, P, P)`, where ``B`` is the number of patches
+ and :math:`P` is ``patch_size``.
Returns:
Descriptor tensor with shape :math:`(B, D)`, where ``D`` is the configured
output descriptor dimension after optional whitening.
+
+ Raises:
+ ShapeError: if ``patches`` is not :math:`(B, 1, P, P)`.
"""
if not isinstance(patches, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(patches)}")
- if not len(patches.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {patches.shape}")
+ KORNIA_CHECK_SHAPE(patches, ["B", "1", str(self.patch_size), str(self.patch_size)])
# Extract gradients.
g = self.smoothing(patches)
g = self.gradients(g)
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index ba0215c82..a42c448fa 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -87,6 +87,12 @@ _SKEWED_SHAPE = [[14.0, 6.0], [-3.0, 17.0]]
# Entry tolerances of a unit-determinant ellipse matrix computed from a LAF of each dtype.
_ELLIPSE_ATOL = {torch.float64: 1e-6, torch.float32: 1e-5, torch.float16: 1e-2, torch.bfloat16: 5e-2}
+# A LAF of scale ~292 px: products of two of its entries (det 300 * 280 + 40 * 25 = 85000) exceed float16's 65504.
+_LARGE_SHAPE = [[300.0, 40.0], [-25.0, 280.0]]
+
+# Relative tolerances of the scale of an output LAF whose entries are rounded to each dtype.
+_SCALE_RTOL = {torch.float64: 1e-6, torch.float32: 1e-5, torch.float16: 4e-3, torch.bfloat16: 3e-2}
+
def _gaussian_blob(
h: int, w: int, center: tuple[float, float], axes: tuple[float, float], angle_deg: float, device, dtype
@@ -452,6 +458,24 @@ class TestLAFAffineShapeEstimator(BaseTester):
nondet_tol=1e-4,
)
+ @pytest.mark.parametrize("preserve_orientation", [False, True])
+ def test_large_half_precision_laf_is_estimated(self, device, dtype, preserve_orientation):
+ # Products of two entries of this LAF overflow float16 (det 85000 > 65504). It used to be judged invalid in
+ # float16, and the estimate was dropped: a zero-shape frame without preserve_orientation, the input with it.
+ abc = (1.0, 0.3, 0.5)
+ img = torch.rand(1, 1, 96, 128, device=device, dtype=dtype)
+ laf = _laf_with_shape(_LARGE_SHAPE, (70.0, 41.0), device, dtype)
+ aff = LAFAffineShapeEstimator(32, ConstantShape(abc), preserve_orientation=preserve_orientation)
+ out = aff.to(device, dtype)(laf, img)
+ assert out.dtype == dtype
+ frame = make_upright(laf.cpu().double())[0, 0, :, :2]
+ patch_ellipse = torch.tensor([[abc[0], abc[1]], [abc[1], abc[2]]], dtype=torch.float64)
+ expected = frame @ torch.linalg.inv(patch_ellipse) @ frame.T
+ self.assert_close(_unit_ellipse(out), expected / expected.det().sqrt(), rtol=0.0, atol=_ELLIPSE_ATOL[dtype])
+ self.assert_close(out[..., 2], laf[..., 2])
+ actual_scale, expected_scale = get_laf_scale(out.cpu().double()), get_laf_scale(laf.cpu().double())
+ self.assert_close(actual_scale, expected_scale, rtol=_SCALE_RTOL[dtype], atol=0.0)
+
class TestLAFAffNetShapeEstimator(BaseTester):
def test_singular_prediction_falls_back_upright(self, device, dtype):
@@ -579,3 +603,22 @@ class TestLAFAffNetShapeEstimator(BaseTester):
atol=1e-3,
nondet_tol=1e-3,
)
+
+ @pytest.mark.parametrize("preserve_orientation", [False, True])
+ def test_large_half_precision_laf_is_estimated(self, device, dtype, preserve_orientation):
+ # Products of two entries of this LAF overflow float16 (det 85000 > 65504). It used to be judged invalid in
+ # float16, and the prediction was dropped: a zero-shape frame without preserve_orientation, the input with it.
+ xy = (0.2, -0.3, -0.4)
+ img = torch.rand(1, 1, 96, 128, device=device, dtype=dtype)
+ laf = _laf_with_shape(_LARGE_SHAPE, (70.0, 41.0), device, dtype)
+ aff = LAFAffNetShapeEstimator(preserve_orientation=preserve_orientation).to(device, dtype)
+ aff.features = ConstantAffNetOutput(xy)
+ out = aff(laf, img)
+ assert out.dtype == dtype
+ frame = make_upright(laf.cpu().double())[0, 0, :, :2]
+ prediction = torch.tensor([[1.0 + xy[0], 0.0], [xy[1], 1.0 + xy[2]]], dtype=torch.float64)
+ expected = frame @ prediction @ prediction.T @ frame.T
+ self.assert_close(_unit_ellipse(out), expected / expected.det().sqrt(), rtol=0.0, atol=_ELLIPSE_ATOL[dtype])
+ self.assert_close(out[..., 2], laf[..., 2])
+ actual_scale, expected_scale = get_laf_scale(out.cpu().double()), get_laf_scale(laf.cpu().double())
+ self.assert_close(actual_scale, expected_scale, rtol=_SCALE_RTOL[dtype], atol=0.0)
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 26aabab78..3b165b3f5 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -100,6 +100,48 @@ class TestGetLAFDescriptors(BaseTester):
nondet_tol=1e-3,
)
+ @pytest.mark.parametrize("layout", ["transposed", "channels_last"])
+ def test_non_contiguous_descriptor_output(self, device, dtype, layout):
+ # The per-patch output is flattened into (B, N, D). A `view` there refused an output whose trailing dimensions
+ # cannot be merged without a copy, such as a transposed block or a channels-last convolution.
+ B, N, PS = 2, 3, 16
+ img = torch.rand(B, 1, 48, 64, device=device, dtype=dtype)
+ lafs = torch.tensor(
+ [
+ [
+ [[6.0, 2.0, 20.0], [-1.0, 5.0, 30.0]],
+ [[4.0, -1.5, 41.0], [0.5, 7.0, 17.0]],
+ [[8.0, 1.0, 33.0], [-3.0, 6.0, 25.0]],
+ ],
+ [
+ [[5.0, 1.0, 12.0], [-2.0, 4.0, 36.0]],
+ [[7.0, 2.5, 50.0], [1.5, 6.0, 22.0]],
+ [[3.0, -0.5, 27.0], [1.0, 9.0, 14.0]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ patches = extract_patches_from_pyramid(img, lafs, PS).view(B * N, 1, PS, PS)
+ if layout == "transposed":
+
+ class _TransposedBlock(nn.Module):
+ def forward(self, x):
+ return x[..., :3, :5].transpose(-1, -2)
+
+ desc = _TransposedBlock()
+ expected = patches[..., :3, :5].transpose(-1, -2).reshape(B, N, 15)
+ else:
+
+ class _ChannelsLast(nn.Module):
+ def forward(self, x):
+ return x.contiguous(memory_format=torch.channels_last)
+
+ conv = nn.Conv2d(1, 4, 5, stride=4).to(device, dtype)
+ desc = nn.Sequential(conv, _ChannelsLast())
+ expected = conv(patches).reshape(B, N, -1)
+ self.assert_close(get_laf_descriptors(img, lafs, desc, PS), expected)
+
class TestGetLAFDescriptorsEmptyPath(BaseTester):
"""The empty-LAF result must agree with the non-empty one (see #4065)."""
@@ -124,7 +166,7 @@ class TestGetLAFDescriptorsEmptyPath(BaseTester):
@pytest.mark.parametrize("descriptor", ["four_dim", "dense_sift"])
def test_empty_matches_a_non_2d_descriptor(self, device, dtype, descriptor):
- """The width must be what `.view(B, N, -1)` produces, not the probe's last dimension.
+ """The width must be what `.reshape(B, N, -1)` produces, not the probe's last dimension.
The non-empty path flattens *everything* the descriptor produced per patch, so taking
`probe.shape[-1]` agreed only for descriptors whose output is 2-D. `patch_descriptor` is
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 91439e4a2..908cc9591 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -82,6 +82,13 @@ class TestGetLAFScale(BaseTester):
model_jit = torch.jit.script(kornia.feature.get_laf_scale)
self.assert_close(model(img), model_jit(img))
+ def test_large_laf_does_not_overflow(self, device, dtype):
+ # The determinant of this LAF, 300 * 280 + 40 * 25 = 85000, overflows float16 (max 65504); its scale does not.
+ laf = torch.tensor([[[[300.0, 40.0, 410.0], [-25.0, 280.0, 330.0]]]], device=device, dtype=dtype)
+ scale = kornia.feature.get_laf_scale(laf)
+ assert scale.dtype == dtype
+ self.assert_close(scale, torch.full((1, 1, 1, 1), math.sqrt(85000.0), device=device, dtype=dtype))
+
class TestGetLAFCenter(BaseTester):
def test_shape(self, device):
@@ -256,6 +263,30 @@ class TestMakeUpright(BaseTester):
model_jit = torch.jit.script(kornia.feature.make_upright)
self.assert_close(model(img), model_jit(img))
+ def test_large_laf_does_not_overflow(self, device, dtype):
+ # Squares and products of these LAFs' entries overflow float16 (max 65504); the LAFs and their upright forms
+ # do not. Upright form [[r, 0], [(a22 * a12 + a21 * a11) / r, det / r]] with r = hypot(a11, a12). The second
+ # LAF has a scale of only sqrt(300 * 20) = 77 px, but a11**2 = 90000 overflows; it is upright already.
+ laf = torch.tensor(
+ [[[[300.0, 40.0, 410.0], [-25.0, 280.0, 330.0]], [[300.0, 0.0, 10.0], [0.0, 20.0, 12.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ r = math.hypot(300.0, 40.0)
+ expected = torch.tensor(
+ [
+ [
+ [[r, 0.0, 410.0], [(280.0 * 40.0 - 25.0 * 300.0) / r, 85000.0 / r, 330.0]],
+ [[300.0, 0.0, 10.0], [0.0, 20.0, 12.0]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ out = kornia.feature.make_upright(laf)
+ assert out.dtype == dtype
+ self.assert_close(out, expected)
+
class TestELL2LAF(BaseTester):
def test_shape(self, device):
@@ -476,6 +507,26 @@ class TestLAFIsValid(BaseTester):
compiled = torch.compile(kornia.feature.laf_is_valid, fullgraph=True)
assert torch.equal(compiled(laf), expected)
+ def test_validity_does_not_depend_on_float16_range(self, device, dtype):
+ # Products of two entries of an ordinary LAF leave the float16 range: the determinant of the first LAF is
+ # 300 * 280 + 40 * 25 = 85000 > 65504, and every product in the third rounds to zero (2**-26 and below).
+ # Neither makes the LAF invalid. The second LAF is singular (300 * 300 - 600 * 150 = 0) and stays invalid.
+ tiny = 2.0**-13
+ laf = torch.tensor(
+ [
+ [
+ [[300.0, 40.0, 410.0], [-25.0, 280.0, 330.0]],
+ [[300.0, 600.0, 410.0], [150.0, 300.0, 330.0]],
+ [[tiny, tiny / 2, 7.0], [-tiny / 4, tiny, 3.0]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ valid = kornia.feature.laf_is_valid(laf)
+ assert valid.dtype == torch.bool
+ assert torch.equal(valid, torch.tensor([[True, False, True]], device=device))
+
class TestLAFIsFilled(BaseTester):
def _mixed(self, device, dtype):
diff --git a/tests/feature/test_mkd.py b/tests/feature/test_mkd.py
index 43bed8c80..83066426f 100644
--- a/tests/feature/test_mkd.py
+++ b/tests/feature/test_mkd.py
@@ -21,6 +21,7 @@ from unittest.mock import patch
import pytest
import torch
+from kornia.core.exceptions import ShapeError
from kornia.feature.mkd import (
COEFFS,
EmbedGradients,
@@ -35,7 +36,7 @@ from kornia.feature.mkd import (
spatial_kernel_embedding,
)
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_replicate_padding
@pytest.fixture(autouse=True)
@@ -398,6 +399,31 @@ class TestWhitening(BaseTester):
)
self.assert_close(model(patches), model_jit(patches))
+ @pytest.mark.parametrize("output_dims", [20, 40, 41, 50])
+ def test_pcaws_shrinkage_does_not_depend_on_output_dims(self, device, dtype, output_dims):
+ # pcaws replaces every kept eigenvalue by lambda' = (1 - alpha) * lambda + alpha, a shrinkage towards 1 with
+ # weight alpha = eigvals[keval=40] of the full spectrum. alpha belongs to the whitening model, so keeping
+ # fewer components only drops columns; output_dims <= 40 used to raise IndexError instead.
+ in_dims, keval = 50, 40
+ eigvals = 1.0 / torch.arange(1, in_dims + 1, dtype=torch.float64) # decaying, alpha = 1 / 41
+ eigvecs = torch.linspace(-1.0, 1.0, in_dims * in_dims, dtype=torch.float64).view(in_dims, in_dims)
+ model = {"pca": {"mean": torch.zeros(in_dims), "eigvecs": eigvecs.float(), "eigvals": eigvals.float()}}
+ wh = Whitening(xform="pcaws", whitening_model=model, in_dims=in_dims, output_dims=output_dims, keval=keval)
+ wh = wh.to(device, dtype)
+ alpha = eigvals[keval]
+ expected = eigvecs[:, :output_dims] * ((1 - alpha) * eigvals[:output_dims] + alpha).pow(-0.5)
+ self.assert_close(wh.evecs.data, expected.to(device, dtype))
+ assert wh(torch.rand(3, in_dims, device=device, dtype=dtype)).shape == (3, output_dims)
+
+ @pytest.mark.parametrize("keval", [40, -1, -31])
+ def test_pcaws_needs_the_shrinkage_eigenvalue(self, device, keval):
+ # A whitening model with no eigenvalue at index keval has no shrinkage weight: say so instead of IndexError.
+ # A negative keval has no meaning for a spectrum; it used to index the one truncated to output_dims.
+ in_dims = 30
+ model = {"pca": {"mean": torch.zeros(in_dims), "eigvecs": torch.eye(in_dims), "eigvals": torch.ones(in_dims)}}
+ with pytest.raises(ValueError, match=rf"keval={keval} .*30 eigenvalues \(0 <= keval < 30\)"):
+ Whitening(xform="pcaws", whitening_model=model, in_dims=in_dims, output_dims=20, keval=keval)
+
class TestMKDDescriptor(BaseTester):
dims = {"cart": 63, "polar": 175, "concat": 238}
@@ -504,6 +530,37 @@ class TestMKDDescriptor(BaseTester):
)
self.assert_close(model(patches), model_jit(patches))
+ @pytest.mark.parametrize("output_dims", [20, 40])
+ def test_pcaws_with_at_most_40_output_dims(self, device, dtype, output_dims):
+ # pcaws used to index the eigenvalue at keval=40 after truncating the spectrum to output_dims (IndexError).
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip(f"no replicate-padding kernel for {dtype} on this device")
+ mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening="pcaws", output_dims=output_dims)
+ out = mkd.to(device, dtype)(torch.rand(2, 1, 19, 19, device=device, dtype=dtype))
+ assert out.shape == (2, output_dims)
+ assert out.dtype == dtype
+
+ @pytest.mark.parametrize(
+ ("shape", "message"),
+ [
+ ((2, 1, 23, 19), "dimension 2: expected 19, got 23"),
+ ((2, 1, 19, 23), "dimension 3: expected 19, got 23"),
+ ((2, 1, 32, 32), "dimension 2: expected 19, got 32"),
+ ((2, 3, 19, 19), "dimension 1: expected 1, got 3"),
+ ((1, 19, 19), "expected 4 dimensions, got 3"),
+ ((1, 1, 1, 19, 19), "expected 4 dimensions, got 5"),
+ ],
+ ids=["height", "width", "both", "channels", "rank3", "rank5"],
+ )
+ def test_patches_must_be_grayscale_and_patch_size(self, device, dtype, shape, message):
+ # The spatial encoding is precomputed for patch_size x patch_size grayscale patches. Another size used to fail
+ # deep inside with torch's broadcast RuntimeError, and three channels with a message about five.
+ mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device, dtype)
+ with pytest.raises(ShapeError, match=message):
+ mkd(torch.rand(*shape, device=device, dtype=dtype))
+ if supports_replicate_padding(device, dtype):
+ assert mkd(torch.rand(0, 1, 19, 19, device=device, dtype=dtype)).shape == (0, 238)
+
class TestSimpleKD(BaseTester):
dims = {"cart": 63, "polar": 175}
diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.py
index 932602610..0463058eb 100644
--- a/tests/feature/test_sift_scale_space.py
+++ b/tests/feature/test_sift_scale_space.py
@@ -459,6 +459,32 @@ class TestSharedSIFTScaleSpace(BaseTester):
assert lafs.shape == (1, 8, 2, 3)
assert responses.dtype == descriptors.dtype == lafs.dtype == dtype
+ 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).
+ # laf_is_valid used to call it invalid in float16, so it got the zero descriptor of a padded slot. A half
+ # precision input is described in float32, so it must get the float32 descriptor of the same rounded input.
+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ yy, xx = torch.meshgrid(torch.arange(96.0), torch.arange(128.0), indexing="ij")
+ image = (0.5 + 0.3 * torch.sin(xx / 7.0) * torch.cos(yy / 11.0) + 0.002 * xx)[None, None]
+ pyramid = [
+ level.to(dtype) for level in _SIFTScalePyramid().to(device, work_dtype)(image.to(device, work_dtype))
+ ]
+ lafs = torch.tensor(
+ [[[[300.0, 40.0, 70.0], [-25.0, 280.0, 41.0]], [[12.0, 3.0, 50.0], [-2.0, 10.0, 60.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ octaves = torch.tensor([[2, 0]], device=device)
+ levels = torch.tensor([[3, 2]], device=device)
+ describe = _SIFTScaleSpaceDescriptor()
+ _, actual = describe(pyramid, lafs, octaves, levels, upright=True)
+ _, expected = describe(
+ [level.to(work_dtype) for level in pyramid], lafs.to(work_dtype), octaves, levels, upright=True
+ )
+ assert actual.dtype == dtype
+ assert bool(expected.abs().sum(dim=-1).gt(0).all())
+ self.assert_close(actual, expected.to(dtype))
+
class TestSIFTScalePyramid(BaseTester):
def test_precise_double_grid(self, device, dtype):