π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): centre SIFTDescriptor's cell grid on the patch (#5696)
Dmytro Mishkin0232d0bcfdfb
diff --git a/changelog.d/5696.fixed.md b/changelog.d/5696.fixed.mdnew file mode 100644index 000000000..98f89fe70--- /dev/null+++ b/changelog.d/5696.fixed.md@@ -0,0 +1,8 @@+`SIFTDescriptor` now centres its grid of spatial cells on the patch centre `(patch_size - 1) / 2`, where its+Gaussian weighting window already was. The grid, inherited from pytorch-sift, sat above and to the left of it: by+1.5 pixels at the default patch size 41, and by more at larger patch sizes. A mirrored or `rot90`-rotated patch+therefore did not give a permuted descriptor; with the default 8 angular bins it now does, up to rounding. At some+patch sizes, 41 among them, the centred grid needs a pooling kernel one pixel wider (17 instead of 16 pixels), and+`get_sift_bin_ksize_stride_pad` returns it with the new `pad`. Descriptors change for `SIFTDescriptor`,+`sift_describe` and the `"patch"` backend of `SIFTFeature` and `SIFTFeatureScaleSpace`; the `"pyramid"` backends and+`DenseSIFTDescriptor` are unchanged. A state dict holding the former, untrained pooling kernel still loads.diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.pyindex 0290d8682..ce6aa054e 100644--- a/kornia/feature/sift/pyramid.py+++ b/kornia/feature/sift/pyramid.py@@ -68,7 +68,7 @@ class SIFTDescriptorFromPyramid(nn.Module):num_spatial_bins: Number of descriptor spatial bins per axis.spatial_bin_size: Side of the DenseSIFT spatial pooling window, in pixels.The default 8 approximately matches the 19-pixel octave support to the patch SIFT- descriptor's 16-pixel pooling bins.+ descriptor's 17-pixel pooling bins at its default 41-pixel patch.rootsift: If ``True``, apply RootSIFT after clipping and normalization.clipval: Descriptor clipping threshold.orientation_bins: Number of bins for dominant-orientation assignment.diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 514cc40df..e66a9d198 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -16,7 +16,7 @@#import math-from typing import Tuple+from typing import Any, Dict, List, Tupleimport torchimport torch.nn.functional as F@@ -112,7 +112,16 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tuple[int, int, int]:- r"""Return a tuple with SIFT parameters.+ r"""Return the spatial pooling parameters of :class:`SIFTDescriptor`.++ The pooling is a convolution with :func:`get_sift_pooling_kernel` of size ``ksize``, stride ``stride`` and zero+ padding ``pad`` on every side. Its ``num_spatial_bins`` cells per side are ``stride`` pixels apart and the grid+ is centred on the patch centre :math:`(\text{patch\_size} - 1) / 2`, where the descriptor's Gaussian weighting+ window is centred: cell :math:`k` is centred at+ :math:`(\text{patch\_size} - 1) / 2 + (k - (\text{num\_spatial\_bins} - 1) / 2) \cdot \text{stride}`.++ ``ksize`` is :math:`2 \lfloor \text{patch\_size} / (\text{num\_spatial\_bins} + 1) \rfloor`, plus one when a+ centred grid needs a kernel centred on a pixel rather than between two, as at the default patch size 41.Args:patch_size: the given patch size.@@ -122,11 +131,15 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tupksize, stride, pad."""- ksize: int = 2 * int(patch_size / (num_spatial_bins + 1))stride: int = patch_size // num_spatial_bins- pad: int = ksize // 4- out_size: int = (patch_size + 2 * pad - (ksize - 1) - 1) // stride + 1- if out_size != num_spatial_bins:+ ksize: int = 2 * int(patch_size / (num_spatial_bins + 1))+ # The first cell is centred at -pad + (ksize - 1) / 2 and the grid at that plus (num_spatial_bins - 1) * stride / 2.+ # Setting the grid centre to (patch_size - 1) / 2 gives 2 * pad below, so ksize takes its parity.+ if (ksize - patch_size + (num_spatial_bins - 1) * stride) % 2 != 0:+ ksize += 1+ pad: int = (ksize - patch_size + (num_spatial_bins - 1) * stride) // 2+ out_size: int = (patch_size + 2 * pad - (ksize - 1) - 1) // stride + 1 if stride > 0 else 0+ if pad < 0 or out_size != num_spatial_bins:raise ValueError(f"Patch size {patch_size} is incompatible with the requested number of spatial bins "f"{num_spatial_bins} for SIFT descriptor. Usually it happens when patch size is too small "@@ -155,6 +168,12 @@ class SIFTDescriptor(nn.Module):The output is in kornia's angle-major SIFT layout; :func:`~kornia.feature.convert_sift_descriptor_layout` reordersit to OpenCV's.+ The ``num_spatial_bins`` x ``num_spatial_bins`` grid of spatial cells and the Gaussian weighting window are both+ centred on the patch centre :math:`(\text{patch\_size} - 1) / 2`; :func:`get_sift_bin_ksize_stride_pad` gives the+ cell spacing and pooling kernel. A patch mirrored upside down therefore has a descriptor that is a permutation of+ the original's; so does a patch mirrored left to right when ``num_ang_bins`` is even, and a ``torch.rot90``-rotated+ one when ``num_ang_bins`` is a multiple of four, as the default 8 is.+Example:>>> input = torch.rand(23, 1, 32, 32)>>> SIFT = SIFTDescriptor(32, 8, 4)@@ -207,6 +226,33 @@ class SIFTDescriptor(nn.Module):)self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))+ def _load_from_state_dict(+ self,+ state_dict: Dict[str, Any],+ prefix: str,+ local_metadata: Dict[str, Any],+ strict: bool,+ missing_keys: List[str],+ unexpected_keys: List[str],+ error_msgs: List[str],+ ) -> None:+ # The pooling kernel used to be 2 * int(patch_size / (num_spatial_bins + 1)) wide at every patch size; the+ # centred grid widens it by one pixel at some, 41 among them. A state dict saved with the narrower kernel+ # holds an untrained kernel that `patch_size` fully determines, so it is replaced by the untrained kernel of+ # the current width instead of failing a strict load on its shape -- rebuilt here, not copied from `self.pk`,+ # which may have been trained since construction. A kernel with any other values still fails.+ key = prefix + "pk.weight"+ weight = state_dict.get(key)+ if isinstance(weight, torch.Tensor) and weight.shape != self.pk.weight.shape:+ former = get_sift_pooling_kernel(2 * int(self.patch_size / (self.num_spatial_bins + 1)))+ former = former.to(weight.dtype).reshape(1, 1, *former.shape)+ if weight.shape == former.shape and torch.equal(weight.cpu(), former):+ current = get_sift_pooling_kernel(self.bin_ksize).float()+ state_dict[key] = current.reshape(1, 1, *current.shape).to(weight.device, weight.dtype)+ super()._load_from_state_dict(+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs+ )+def get_pooling_kernel(self) -> torch.Tensor:"""Return the spatial pooling kernel used for histogram accumulation.diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pyindex 0ee732d19..932602610 100644--- a/tests/feature/test_sift_scale_space.py+++ b/tests/feature/test_sift_scale_space.py@@ -101,7 +101,8 @@ class TestSharedSIFTScaleSpace(BaseTester):lafs = torch.tensor([[[[12.0, 0.0, 24.0], [0.0, 12.0, 24.0]]]], device=device, dtype=work_dtype)patch = LAFDescriptor(SIFTDescriptor(41, rootsift=False), patch_size=41).to(device, work_dtype)(image, lafs)pyramid = SIFTDescriptorFromPyramid(rootsift=False).to(device, work_dtype)(image, lafs)- # About 0.87 with either; the scale-space descriptor in its former (row, column, angle) order scored 0.44.+ # 0.92 with the patch descriptor and 0.88 with the pyramid one; the scale-space descriptor in its former+ # (row, column, angle) order scored 0.44.for other in (patch[0], pyramid[0]):assert F.cosine_similarity(descriptor.to(work_dtype), other).item() > 0.8diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex e735c81f0..c01f814a1 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -37,12 +37,64 @@ def test_get_sift_pooling_kernel(ksize):assert kernel.shape == (ksize, ksize)[email protected]("ps,n_bins,ksize,stride,pad", [(41, 3, 20, 13, 5), (32, 4, 12, 8, 3)])+# Cell centres -pad + (ksize - 1) / 2 + k * stride: (41, 3) 7 / 20 / 33, (32, 4) 3.5 / 11.5 / 19.5 / 27.5,+# (41, 4) 5 / 15 / 25 / 35 and (11, 4) 2 / 4 / 6 / 8, each grid centred on (ps - 1) / 2. The off-centre helper of+# #5691 rejected (11, 4): its 4-pixel kernel with pad 1 gave five cells.+ "ps,n_bins,ksize,stride,pad", [(41, 3, 21, 13, 3), (32, 4, 12, 8, 2), (41, 4, 17, 10, 3), (11, 4, 5, 2, 0)]+)def test_get_sift_bin_ksize_stride_pad(ps, n_bins, ksize, stride, pad):out = get_sift_bin_ksize_stride_pad(ps, n_bins)assert out == (ksize, stride, pad)[email protected]("ps,n_bins", [(3, 4), (0, 1)])+def test_get_sift_bin_ksize_stride_pad_rejects_a_patch_smaller_than_the_bins_5691(ps, n_bins):+ # A zero cell spacing used to raise ZeroDivisionError from the output-size check.+ with pytest.raises(ValueError, match="incompatible"):+ get_sift_bin_ksize_stride_pad(ps, n_bins)+++# Every (patch_size, num_spatial_bins) the suite builds a SIFTDescriptor with, odd/even pairs (31/32/33, 40/41,+# 64/65), the 41-pixel default of SIFTFeature and SIFTFeatureScaleSpace, and (11, 4), which the off-centre helper+# rejected.+_GRID_SIZES = [+ (6, 1), (11, 4), (15, 4), (16, 4), (19, 3), (31, 4), (32, 4), (33, 4), (40, 4), (41, 3), (41, 4), (64, 4), (65, 4),+] # fmt: skip+++def _flip_lr(desc: torch.Tensor, num_ang_bins: int, num_spatial_bins: int) -> torch.Tensor:+ """The descriptor of the left-right mirrored patch, predicted from ``desc``: an angle a becomes pi - a."""+ d = desc.view(desc.shape[0], num_ang_bins, num_spatial_bins, num_spatial_bins)+ perm = [(num_ang_bins // 2 - a) % num_ang_bins for a in range(num_ang_bins)]+ return d[:, perm].flip(-1).reshape(desc.shape)+++def _flip_ud(desc: torch.Tensor, num_ang_bins: int, num_spatial_bins: int) -> torch.Tensor:+ """The descriptor of the upside-down mirrored patch, predicted from ``desc``: an angle a becomes -a."""+ d = desc.view(desc.shape[0], num_ang_bins, num_spatial_bins, num_spatial_bins)+ perm = [(-a) % num_ang_bins for a in range(num_ang_bins)]+ return d[:, perm].flip(-2).reshape(desc.shape)+++def _rot90(desc: torch.Tensor, num_ang_bins: int, num_spatial_bins: int) -> torch.Tensor:+ """The descriptor of ``torch.rot90(patch, 1, (-2, -1))``, predicted from ``desc``: an angle a becomes a - pi/2."""+ d = desc.view(desc.shape[0], num_ang_bins, num_spatial_bins, num_spatial_bins)+ return torch.rot90(d, 1, (-2, -1)).roll(-(num_ang_bins // 4), 1).reshape(desc.shape)++[email protected]("ps,n_bins", _GRID_SIZES)+def test_get_sift_bin_ksize_stride_pad_centres_the_grid_5691(ps, n_bins):+ ksize, stride, pad = get_sift_bin_ksize_stride_pad(ps, n_bins)+ # The pooling triangle is centred at (ksize - 1) / 2 of its window; output k's window starts at k * stride - pad.+ centres = [-pad + (ksize - 1) / 2 + k * stride for k in range(n_bins)]+ # Mirror images about the patch centre (ps - 1) / 2, where the Gaussian weighting window is centred. Half-pixel+ # values are exact in binary floating point.+ assert [centres[k] + centres[n_bins - 1 - k] for k in range(n_bins)] == [ps - 1.0] * n_bins+ assert pad >= 0+ assert (ps + 2 * pad - ksize) // stride + 1 == n_bins++class TestSIFTDescriptor(BaseTester):def test_shape(self, device, dtype):inp = torch.ones(1, 1, 32, 32, device=device, dtype=dtype)@@ -91,6 +143,59 @@ class TestSIFTDescriptor(BaseTester):assert (descriptors[0, 0] > 0.1).all()assert (descriptors[1, 4] > 0.1).all()+ @pytest.mark.parametrize("ps,n_bins", _GRID_SIZES)+ def test_output_has_num_spatial_bins_cells_5691(self, device, dtype, ps, n_bins):+ sift = SIFTDescriptor(ps, num_ang_bins=8, num_spatial_bins=n_bins).to(device, dtype)+ assert sift(torch.rand(2, 1, ps, ps, device=device, dtype=dtype)).shape == (2, 8 * n_bins**2)++ @pytest.mark.parametrize("ps,n_bins", _GRID_SIZES)+ def test_cell_footprints_mirror_about_the_patch_centre_5691(self, device, ps, n_bins):+ # What each output cell pools, read off the module's own pooling convolution: the gradient of one cell+ # with respect to its input map. Mirroring the patch has to map every cell's footprint onto the mirrored cell's.+ sift = SIFTDescriptor(ps, num_spatial_bins=n_bins).to(device)+ x = torch.zeros(1, 1, ps, ps, device=device, requires_grad=True)+ pooled = torch.nn.functional.conv2d(x, sift.pk.weight, None, sift.pk.stride, sift.pk.padding)+ assert pooled.shape[-2:] == (n_bins, n_bins)+ footprints = torch.stack(+ [+ torch.autograd.grad(pooled[0, 0, i, j], x, retain_graph=True)[0][0, 0]+ for i in range(n_bins)+ for j in range(n_bins)+ ]+ ).view(n_bins, n_bins, ps, ps)+ self.assert_close(footprints.flip(-1), footprints.flip(1), rtol=0.0, atol=0.0)+ self.assert_close(footprints.flip(-2), footprints.flip(0), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("ps", [32, 41, 65])+ def test_centred_blob_mirrors_to_a_permutation_5691(self, device, dtype, ps):+ # An isotropic blob at the patch centre is its own mirror image, so its descriptor must be a fixed point of+ # the predicted permutation. The off-centre grid of #5691 left a residual of 0.1235 at 41 pixels.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ axis = torch.arange(ps, dtype=torch.float64) - (ps - 1) / 2+ blob = torch.exp(-(axis.view(-1, 1) ** 2 + axis.view(1, -1) ** 2) / (2 * (ps / 6) ** 2))+ patch = blob.to(device, dtype)[None, None]+ desc = SIFTDescriptor(ps, rootsift=False).to(device, dtype)(patch)+ self.assert_close(_flip_lr(desc, 8, 4), desc)+ self.assert_close(_flip_ud(desc, 8, 4), desc)+ self.assert_close(_rot90(desc, 8, 4), desc)++ @pytest.mark.parametrize("ps,n_bins", [(19, 3), (32, 4), (41, 4), (65, 4)])+ @pytest.mark.parametrize("transform", ["fliplr", "flipud", "rot90"])+ def test_mirrored_or_rotated_patch_permutes_the_descriptor_5691(self, device, dtype, ps, n_bins, transform):+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ patches = torch.rand(8, 1, ps, ps, device=device, dtype=dtype)+ sift = SIFTDescriptor(ps, num_ang_bins=8, num_spatial_bins=n_bins).to(device, dtype)+ moved, predict = {+ "fliplr": (patches.flip(-1), _flip_lr),+ "flipud": (patches.flip(-2), _flip_ud),+ "rot90": (torch.rot90(patches, 1, (-2, -1)), _rot90),+ }[transform]+ # A 90-degree rotation of a random 41-pixel patch matched the permuted descriptor to a mean cosine of 0.989.+ self.assert_close(sift(moved), predict(sift(patches), 8, n_bins))+@pytest.mark.skip("Compiled functions can't take variable number")def test_jit(self, device, dtype):B, C, H, W = 1, 1, 32, 32@@ -117,6 +222,25 @@ class TestSIFTDescriptorKernelBuffer(BaseTester):"""Registered non-persistent, so existing checkpoints keep loading with strict=True."""assert "gk" not in SIFTDescriptor(32).state_dict()+ @pytest.mark.parametrize("module_dtype", [torch.float32, torch.float16])+ def test_loads_a_state_dict_saved_before_the_grid_was_centred_5691(self, device, module_dtype):+ """A checkpoint saved with the former 16-pixel kernel of the 41-pixel patch still loads with strict=True."""+ mod = SIFTDescriptor(41).to(device, module_dtype)+ expected = mod.get_pooling_kernel()+ assert expected.shape == (1, 1, 17, 17)+ former = get_sift_pooling_kernel(16).reshape(1, 1, 16, 16).to(device, module_dtype)+ outer = torch.nn.Sequential(mod)+ outer.load_state_dict({"0.pk.weight": former})+ assert torch.equal(mod.get_pooling_kernel(), expected)+ # The untrained kernel is rebuilt, not copied from the destination, whose kernel may have been trained.+ with torch.no_grad():+ mod.pk.weight.zero_()+ outer.load_state_dict({"0.pk.weight": former})+ assert torch.equal(mod.get_pooling_kernel(), expected)+ # A kernel of the former shape with other values is a trained one: it still fails on its shape.+ with pytest.raises(RuntimeError, match="size mismatch"):+ outer.load_state_dict({"0.pk.weight": 2 * former})+def test_forward_does_not_mutate_the_module(self, device):if device.type == "mps":pytest.skip("float64 is unavailable on MPS")