Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): clamp the MPS patch-extraction grid to pixel centers, not edges (#4073)

Dmytro Mishkinde02ae4bdbff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc35a55a8..b00d58758 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,6 +97,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
and the device guard in `BaseTester.gradcheck` for the six callers named something else. No runtime
behavior changed.
+* Fix patch extraction on MPS returning darkened patches for any LAF that touches an image border (#4063).
+ MPS has no `padding_mode="border"` for `torch.nn.functional.grid_sample`, so `extract_patches_simple` and
+ `extract_patches_from_pyramid` emulate it with zero padding and a clamped grid. The clamp was `grid.clamp(-1, 1)`,
+ but with `align_corners=False` normalized coordinate `Β±1` is the outer *edge* of the border pixel, not its center,
+ so bilinear sampling blended the border pixel with the zero padding and returned roughly half its value. The grid
+ is now clamped to the outermost pixel centers, `Β±(1 - 1/size)` per axis, which reproduces `padding_mode="border"`
+ exactly. On a patch overlapping the image corner the maximum deviation from the CPU result drops from `0.395` to
+ `2.5e-6` on a `[0, 1]` image, with 64.7% of the patch's pixels previously off by more than `1e-3`. Every descriptor
+ built on these patches β€” `get_laf_descriptors`, `LAFDescriptor`, `SIFTFeature`, `KeyNetAffNetHardNet` and the rest β€”
+ moves with them for keypoints near the border. The CPU and CUDA paths never took this branch and are byte-identical
+ to before.
* Fix `match_fginn`'s geometric consistency check comparing every query's candidates against **query 0**'s
candidates instead of against the query's own 1st nearest neighbor, which changes every `match_fginn` and
`GeometryAwareDescriptorMatcher("fginn")` result -- the latter being that class's *default* mode (#4062). The distance
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 655dac9ea..04c3236b4 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -402,6 +402,32 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
return grid
+def _clamp_grid_to_pixel_centers(grid: torch.Tensor, h: int, w: int) -> torch.Tensor:
+ r"""Clamp a normalized sampling grid to the outermost pixel centers.
+
+ MPS does not implement ``padding_mode="border"`` for :func:`torch.nn.functional.grid_sample`,
+ so the border behavior has to be emulated with zero padding plus a clamped grid. Clamping to
+ :math:`\pm 1` is *not* equivalent: with ``align_corners=False`` that is the outer **edge** of
+ the border pixel, i.e. pixel index :math:`-0.5`, where bilinear sampling blends the border
+ pixel with the zero padding and returns roughly half its value. The outermost pixel **center**
+ sits at :math:`\pm (1 - 1/\text{size})`, and clamping there reproduces ``padding_mode="border"``
+ exactly.
+
+ Args:
+ grid: sampling grid :math:`(B, PS, PS, 2)`, last dimension ordered ``(x, y)``. Only the 2-D form is
+ handled; a 3-D grid would need a third bound from the depth of the sampled volume.
+ h: height of the sampled image.
+ w: width of the sampled image.
+
+ Returns:
+ the clamped grid :math:`(B, PS, PS, 2)`.
+
+ """
+ x = grid[..., 0].clamp(-1.0 + 1.0 / float(w), 1.0 - 1.0 / float(w))
+ y = grid[..., 1].clamp(-1.0 + 1.0 / float(h), 1.0 - 1.0 / float(h))
+ return torch.stack([x, y], dim=-1)
+
+
def extract_patches_simple(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
@@ -434,7 +460,7 @@ def extract_patches_simple(
out.append(
F.grid_sample(
img[i : i + 1].expand(grid.size(0), ch, h, w),
- grid.clamp(-1, 1),
+ _clamp_grid_to_pixel_centers(grid, h, w),
padding_mode="zeros",
align_corners=False,
)
@@ -489,7 +515,7 @@ def extract_patches_from_pyramid(
if cur_img.device.type == "mps":
patches = F.grid_sample(
cur_img[i : i + 1].expand(N, ch_l, h_l, w_l),
- grid.clamp(-1, 1),
+ _clamp_grid_to_pixel_centers(grid, h_l, w_l),
padding_mode="zeros",
align_corners=False,
)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 6acbbb2ac..23af7fd11 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -406,6 +406,75 @@ class TestGenPatchGrid(BaseTester):
self.gradcheck(generate_patch_grid_from_normalized_LAF, (img, laf, PS))
+class TestClampGridToPixelCenters(BaseTester):
+ """Pin the MPS ``padding_mode="border"`` emulation used by the patch extractors.
+
+ MPS has no ``border`` padding for ``grid_sample``, so the extractors clamp the grid and use
+ zero padding instead. The clamp must target the outermost pixel *center*; clamping to
+ :math:`\\pm 1` lands on the outer *edge* of the border pixel and halves its value.
+
+ The reference is always computed on CPU, because ``padding_mode="border"`` is exactly what the
+ target device may not support.
+ """
+
+ @staticmethod
+ def _make(h, w, dtype):
+ torch.manual_seed(0)
+ img = torch.rand(1, 2, h, w, dtype=dtype)
+ # a grid that deliberately runs off every edge
+ grid = (torch.rand(1, 9, 11, 2, dtype=dtype) * 3.0) - 1.5
+ return img, grid
+
+ def test_matches_border_padding(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("grid_sample reference comparison is meaningful only in full precision")
+ h, w = 17, 23
+ img, grid = self._make(h, w, dtype)
+ expected = torch.nn.functional.grid_sample(img, grid, padding_mode="border", align_corners=False)
+
+ clamped = kornia.feature.laf._clamp_grid_to_pixel_centers(grid.to(device), h, w)
+ actual = torch.nn.functional.grid_sample(img.to(device), clamped, padding_mode="zeros", align_corners=False)
+ self.assert_close(actual.cpu(), expected)
+
+ def test_naive_clamp_is_not_equivalent(self, device, dtype):
+ """Guard against regressing to ``grid.clamp(-1, 1)``, which is off by half a pixel."""
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("grid_sample reference comparison is meaningful only in full precision")
+ h, w = 17, 23
+ img, grid = self._make(h, w, dtype)
+ expected = torch.nn.functional.grid_sample(img, grid, padding_mode="border", align_corners=False)
+ naive = torch.nn.functional.grid_sample(
+ img.to(device), grid.clamp(-1, 1).to(device), padding_mode="zeros", align_corners=False
+ )
+ assert (naive.cpu() - expected).abs().max() > 1e-3
+
+ def test_shape(self, device, dtype):
+ grid = torch.rand(4, 5, 6, 2, device=device, dtype=dtype)
+ assert kornia.feature.laf._clamp_grid_to_pixel_centers(grid, 8, 9).shape == grid.shape
+
+ def test_gradcheck(self, device):
+ grid = ((torch.rand(1, 3, 3, 2, device=device, dtype=torch.float64) * 3.0) - 1.5).requires_grad_()
+ self.gradcheck(lambda g: kornia.feature.laf._clamp_grid_to_pixel_centers(g, 7, 11), (grid,), fast_mode=False)
+
+ @pytest.mark.parametrize(
+ "extractor",
+ [kornia.feature.extract_patches_simple, kornia.feature.extract_patches_from_pyramid],
+ )
+ def test_extractors_match_cpu_at_the_border(self, device, dtype, extractor):
+ """Patches overlapping the image border must not depend on the device."""
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("cross-device comparison is meaningful only in full precision")
+ torch.manual_seed(0)
+ img = torch.rand(1, 1, 64, 64, dtype=dtype)
+ # centered near the corner with a large scale, so the patch runs off two edges
+ laf = kornia.feature.laf_from_center_scale_ori(
+ torch.tensor([[[3.0, 3.0]]], dtype=dtype), torch.full((1, 1, 1, 1), 12.0, dtype=dtype)
+ )
+ expected = extractor(img, laf, 32)
+ actual = extractor(img.to(device), laf.to(device), 32)
+ self.assert_close(actual.cpu(), expected)
+
+
class TestExtractPatchesSimple(BaseTester):
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)