Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): register the Gaussian kernels as buffers so .to() moves them (#4079)

Dmytro Mishkin2e2932cc92c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b00d58758..399a31651 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,6 +97,13 @@ 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 `SIFTDescriptor.gk`, `PatchDominantGradientOrientation.weighting` and `PatchAffineShapeEstimator.weighting`
+ being plain attributes, so `nn.Module.to()` left them behind on the original device and dtype (#4069). They are
+ now non-persistent buffers: `.to()`, `.cuda()`, `.half()` and friends move them, and because they are fully
+ determined by `patch_size` they stay out of `state_dict()`, so existing checkpoints still load with
+ `strict=True`. The three `forward` methods also cast into a local instead of rebinding the attribute, so a call
+ no longer leaves the module's kernel in whatever dtype and device the last input happened to have. Numerical
+ output is unchanged: the kernels were already cast to the input's dtype and device inside `forward`.
* 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)`,
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index d76d2c9cb..943611d63 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -60,7 +60,12 @@ class PatchAffineShapeEstimator(nn.Module):
self.gradient: nn.Module = SpatialGradient("sobel", 1)
self.eps: float = eps
sigma: float = float(self.patch_size) / math.sqrt(2.0)
- self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
+ # non-persistent: derived from `patch_size`, so it stays out of `state_dict()` but follows `.to()`
+ self.register_buffer(
+ "weighting",
+ get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True),
+ persistent=False,
+ )
def __repr__(self) -> str:
return f"{self.__class__.__name__}(patch_size={self.patch_size}, eps={self.eps})"
@@ -76,8 +81,10 @@ class PatchAffineShapeEstimator(nn.Module):
"""
KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"])
- self.weighting = self.weighting.to(patch.dtype).to(patch.device)
- grads: torch.Tensor = self.gradient(patch) * self.weighting
+ # cast into a local; rebinding `self.weighting` would make the module's dtype/device depend
+ # on whichever tensor was passed last.
+ weighting = self.weighting.to(patch.dtype).to(patch.device)
+ grads: torch.Tensor = self.gradient(patch) * weighting
# unpack the edges
gx: torch.Tensor = grads[:, :, 0]
gy: torch.Tensor = grads[:, :, 1]
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 3c7f93185..35db8e4c9 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -75,7 +75,12 @@ class PatchDominantGradientOrientation(nn.Module):
with torch.no_grad():
self.angular_smooth.weight[:] = get_gaussian_discrete_kernel1d(5, 1.6)
sigma: float = float(self.patch_size) / 6.0
- self.weighting = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
+ # non-persistent: derived from `patch_size`, so it stays out of `state_dict()` but follows `.to()`
+ self.register_buffer(
+ "weighting",
+ get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True),
+ persistent=False,
+ )
def __repr__(self) -> str:
return (
@@ -98,14 +103,17 @@ class PatchDominantGradientOrientation(nn.Module):
raise TypeError(
f"input shape should be must be [Bx1x{self.patch_size}x{self.patch_size}]. Got {patch.size()}"
)
- self.weighting = self.weighting.to(patch.dtype).to(patch.device)
+ # cast into a local; rebinding `self.weighting` would make the buffer's dtype/device depend on
+ # whichever tensor was passed last, and is a `torch.compile` guard hazard. (The `self.angular_smooth`
+ # line below rebinds a submodule to itself -- `nn.Module.to` is in-place -- which is a different case.)
+ weighting = self.weighting.to(patch.dtype).to(patch.device)
self.angular_smooth = self.angular_smooth.to(patch.dtype).to(patch.device)
grads: torch.Tensor = self.gradient(patch)
# unpack the edges
gx: torch.Tensor = grads[:, :, 0]
gy: torch.Tensor = grads[:, :, 1]
- mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps) * self.weighting
+ mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps) * weighting
ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi
o_big = float(self.num_ang_bins) * (ori + 1.0 * pi) / (2.0 * pi)
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 3b72f47e4..5bfae2bbb 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -142,7 +142,9 @@ class SIFTDescriptor(nn.Module):
ks: int = self.patch_size
sigma: float = float(ks) / math.sqrt(2.0)
- self.gk = get_gaussian_kernel2d((ks, ks), (sigma, sigma), True)
+ # non-persistent: fully determined by `patch_size`, so it must not enter `state_dict()`
+ # (that would break existing checkpoints), but it must still follow `.to()`.
+ self.register_buffer("gk", get_gaussian_kernel2d((ks, ks), (sigma, sigma), True), persistent=False)
(self.bin_ksize, self.bin_stride, self.pad) = get_sift_bin_ksize_stride_pad(patch_size, num_spatial_bins)
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index 45e891e53..71c5ecba2 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -55,6 +55,32 @@ class TestPatchAffineShapeEstimator(BaseTester):
self.gradcheck(ori, (patches,), nondet_tol=1e-4)
+class TestAffineShapeKernelBuffer(BaseTester):
+ """`weighting` must be a real buffer so `.to()` moves it, and `forward` must not rebind it (#4069)."""
+
+ def test_to_moves_the_kernel(self, device):
+ """`.to()` must carry the kernel along with the parameters.
+
+ float16 rather than the default float32, or the dtype assertion would hold
+ vacuously; float16 also works on MPS, where float64 is unavailable.
+ """
+ mod = PatchAffineShapeEstimator(19).to(device, torch.float16)
+ assert mod.weighting.dtype == torch.float16
+ assert mod.weighting.device == torch.empty(0, device=device).device
+
+ def test_kernel_stays_out_of_state_dict(self, device):
+ """Registered non-persistent, so existing checkpoints keep loading with strict=True."""
+ assert "weighting" not in PatchAffineShapeEstimator(19).state_dict()
+
+ def test_forward_does_not_mutate_the_module(self, device):
+ if device.type == "mps":
+ pytest.skip("float64 is unavailable on MPS")
+ mod = PatchAffineShapeEstimator(19)
+ before = (mod.weighting.dtype, mod.weighting.device)
+ mod(torch.rand(2, 1, 19, 19, dtype=torch.float64))
+ assert (mod.weighting.dtype, mod.weighting.device) == before
+
+
class TestLAFAffineShapeEstimator(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.py
index 995636a10..2ecea284f 100644
--- a/tests/feature/test_local_features_orientation.py
+++ b/tests/feature/test_local_features_orientation.py
@@ -98,6 +98,32 @@ class TestPatchDominantGradientOrientation(BaseTester):
self.assert_close(model(patches), model_jit(patches))
+class TestOrientationKernelBuffer(BaseTester):
+ """`weighting` must be a real buffer so `.to()` moves it, and `forward` must not rebind it (#4069)."""
+
+ def test_to_moves_the_kernel(self, device):
+ """`.to()` must carry the kernel along with the parameters.
+
+ float16 rather than the default float32, or the dtype assertion would hold
+ vacuously; float16 also works on MPS, where float64 is unavailable.
+ """
+ mod = PatchDominantGradientOrientation(32).to(device, torch.float16)
+ assert mod.weighting.dtype == torch.float16
+ assert mod.weighting.device == torch.empty(0, device=device).device
+
+ def test_kernel_stays_out_of_state_dict(self, device):
+ """Registered non-persistent, so existing checkpoints keep loading with strict=True."""
+ assert "weighting" not in PatchDominantGradientOrientation(32).state_dict()
+
+ def test_forward_does_not_mutate_the_module(self, device):
+ if device.type == "mps":
+ pytest.skip("float64 is unavailable on MPS")
+ mod = PatchDominantGradientOrientation(32)
+ before = (mod.weighting.dtype, mod.weighting.device)
+ mod(torch.rand(2, 1, 32, 32, dtype=torch.float64))
+ assert (mod.weighting.dtype, mod.weighting.device) == before
+
+
class TestOriNet(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index e63a15a38..d521cde16 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -83,6 +83,32 @@ class TestSIFTDescriptor(BaseTester):
self.assert_close(model(patches), model_jit(patches))
+class TestSIFTDescriptorKernelBuffer(BaseTester):
+ """`gk` must be a real buffer so `.to()` moves it, and `forward` must not rebind it (#4069)."""
+
+ def test_to_moves_the_kernel(self, device):
+ """`.to()` must carry the kernel along with the parameters.
+
+ float16 rather than the default float32, or the dtype assertion would hold
+ vacuously; float16 also works on MPS, where float64 is unavailable.
+ """
+ mod = SIFTDescriptor(32).to(device, torch.float16)
+ assert mod.gk.dtype == torch.float16
+ assert mod.gk.device == torch.empty(0, device=device).device
+
+ def test_kernel_stays_out_of_state_dict(self, device):
+ """Registered non-persistent, so existing checkpoints keep loading with strict=True."""
+ assert "gk" not in SIFTDescriptor(32).state_dict()
+
+ def test_forward_does_not_mutate_the_module(self, device):
+ if device.type == "mps":
+ pytest.skip("float64 is unavailable on MPS")
+ mod = SIFTDescriptor(32)
+ before = (mod.gk.dtype, mod.gk.device)
+ mod(torch.rand(2, 1, 32, 32, dtype=torch.float64))
+ assert (mod.gk.dtype, mod.gk.device) == before
+
+
class TestDenseSIFTDescriptor(BaseTester):
def test_shape_default(self, device, dtype):
bs, h, w = 1, 20, 15