Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): stop DenseSIFTDescriptor sharing the identity cache as a buffer (#4074)

Dmytro Mishkin776b08d01596
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ddc211745..7a82cb3d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -130,6 +130,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
existing FGINN tests pass unchanged on both sides, which is how this survived; two tests that discriminate it were
added. `match_fginn`'s docstring now also records the saturation corner, where every candidate falls within
`spatial_th` of the 1st nearest neighbor, the ratio collapses towards zero and the match is accepted.
+* Fix `DenseSIFTDescriptor` registering a process-global cached tensor as its `_poolingconv_weight` buffer, so that
+ one instance's `load_state_dict` silently corrupted every other instance and every instance constructed later
+ (#4068). `_get_reshape_kernel` memoises `torch.eye(numel)` per `numel` and used to return a *view* of the cached
+ tensor; `.float()` on an already-float tensor returns the same object, so no copy happened between the cache and
+ the buffer, and `load_state_dict` copies into buffers in place. Loading a checkpoint into one `DenseSIFTDescriptor`
+ therefore overwrote the shared identity matrix, with no error raised and every descriptor built from it wrong from
+ then on. The cache is removed rather than made safe: cloning on the way out is what a safe cache requires, and a
+ clone costs more than rebuilding the identity at every size measured (2.6 us against 2.0 us at the default
+ `numel = 8 * 4 * 4`; 3.9 ms against 2.8 ms at the former 4096 bound, which also retained 67 MB for the lifetime of
+ the process). Descriptor output is byte-identical to before.
* Fix `laf_is_inside_image` treating the image extent as `(w, h)` rather than `(w - 1, h - 1)`, which made its
bounds asymmetric: the lower bound rejected anything left of `x = 0`, but the upper bound accepted `x = w`, a
full pixel past the last valid column `w - 1` (#4064). Valid pixel coordinates run `0 .. w-1` and `0 .. h-1` --
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 5bfae2bbb..b69212217 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -28,26 +28,14 @@ from kornia.geometry.conversions import pi
def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
- """Return neigh2channels conv kernel."""
- numel: int = kd * ky * kx
+ """Return neigh2channels conv kernel.
- # Fast-path: use static _eye_cache if available for small numel
- # (to avoid repeated allocations for common kernel sizes)
- # The cache size is limited for memory efficiency.
- # NOTE: If memory is a concern and large kd/ky/kx are rare, adjust _MAX_CACHED.
- _MAX_CACHED = 4096
- if numel <= _MAX_CACHED:
- if not hasattr(_get_reshape_kernel, "_eye_cache"):
- _get_reshape_kernel._eye_cache = {} # type: ignore[attr-defined]
- cache = _get_reshape_kernel._eye_cache # type: ignore[attr-defined]
- res = cache.get(numel)
- if res is None:
- res = torch.eye(numel)
- cache[numel] = res
- return res.view(numel, kd, ky, kx)
- else:
- # fallback to normal allocation for big kernels
- return torch.eye(numel).view(numel, kd, ky, kx)
+ Deliberately not memoised: the result is registered as a buffer, so a shared cache has to clone
+ on the way out to keep callers from writing into it, and the clone costs more than rebuilding
+ the identity.
+ """
+ numel: int = kd * ky * kx
+ return torch.eye(numel).view(numel, kd, ky, kx)
def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index d521cde16..7c337ec2c 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -135,6 +135,34 @@ class TestDenseSIFTDescriptor(BaseTester):
sift = DenseSIFTDescriptor()
sift.__repr__()
+ def test_instances_do_not_share_buffer_storage(self, device):
+ """Instances must not share storage for `_poolingconv_weight` (see #4068).
+
+ `_get_reshape_kernel` used to memoise `torch.eye(numel)` and hand out a view of it, so
+ every `DenseSIFTDescriptor` with the same configuration shared one storage and a single
+ in-place write leaked into all of them.
+ """
+ a = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)
+ b = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)
+ assert a._poolingconv_weight.untyped_storage().data_ptr() != (
+ b._poolingconv_weight.untyped_storage().data_ptr()
+ )
+
+ def test_load_state_dict_does_not_leak_into_other_instances(self, device):
+ """`load_state_dict` copies into buffers in place; that must stay local to one module."""
+ a = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)
+ b = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)
+ expected = a._poolingconv_weight.clone()
+
+ state = b.state_dict()
+ state["_poolingconv_weight"] = torch.zeros_like(state["_poolingconv_weight"])
+ b.load_state_dict(state)
+
+ self.assert_close(a._poolingconv_weight, expected)
+ # and a module built afterwards is still healthy
+ c = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)
+ self.assert_close(c._poolingconv_weight, expected)
+
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 16, 16
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)