π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix submodule mutation in SIFT forwards (#4144)
X-mo7b773dcfc47f8
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex f8a1188ff..7a4a7782a 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -105,10 +105,12 @@ class PatchDominantGradientOrientation(nn.Module):f"input shape should be must be [Bx1x{self.patch_size}x{self.patch_size}]. Got {patch.size()}")# 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.)+ # whichever tensor was passed last, and is a `torch.compile` guard hazard.weighting = self.weighting.to(patch.dtype).to(patch.device)- self.angular_smooth = self.angular_smooth.to(patch.dtype).to(patch.device)+ angular_smooth_weight = self.angular_smooth.weight.to(patch.dtype).to(patch.device)+ angular_smooth_bias = self.angular_smooth.bias+ if angular_smooth_bias is not None:+ angular_smooth_bias = angular_smooth_bias.to(patch.dtype).to(patch.device)grads: torch.Tensor = self.gradient(patch)# unpack the edgesgx: torch.Tensor = grads[:, :, 0]@@ -134,7 +136,23 @@ class PatchDominantGradientOrientation(nn.Module):)ang_bins_list.append(ang_bins_i)ang_bins = torch.cat(ang_bins_list, 1).view(-1, 1, self.num_ang_bins)- ang_bins = self.angular_smooth(ang_bins).view(-1, self.num_ang_bins)+ angular_smooth_padding = self.angular_smooth.padding+ if self.angular_smooth.padding_mode != "zeros":+ ang_bins = F.pad(+ ang_bins,+ (angular_smooth_padding[0], angular_smooth_padding[0]),+ mode=self.angular_smooth.padding_mode,+ )+ angular_smooth_padding = (0,)+ ang_bins = F.conv1d(+ ang_bins,+ angular_smooth_weight,+ angular_smooth_bias,+ self.angular_smooth.stride,+ angular_smooth_padding,+ self.angular_smooth.dilation,+ self.angular_smooth.groups,+ ).view(-1, self.num_ang_bins)values, indices = ang_bins.max(1)indices_left = (self.num_ang_bins + indices - 1) % self.num_ang_binsindices_right = (indices + 1) % self.num_ang_binsdiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex aec1778bb..4fc3d0be1 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -209,7 +209,10 @@ class SIFTDescriptor(nn.Module):"""KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])B: int = input.shape[0]- self.pk = self.pk.to(input.dtype).to(input.device)+ pk_weight = self.pk.weight.to(input.dtype).to(input.device)+ pk_bias = self.pk.bias+ if pk_bias is not None:+ pk_bias = pk_bias.to(input.dtype).to(input.device)grads = spatial_gradient(input, "diff")# unpack the edges@@ -229,7 +232,15 @@ class SIFTDescriptor(nn.Module):ang_bins = torch.cat([- self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big)+ F.conv2d(+ (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big,+ pk_weight,+ pk_bias,+ self.pk.stride,+ self.pk.padding,+ self.pk.dilation,+ self.pk.groups,+ )for i in range(self.num_ang_bins)],1,@@ -381,8 +392,14 @@ class DenseSIFTDescriptor(nn.Module):KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])_B, _CH, _W, _H = input.size()- self.bin_pooling_kernel = self.bin_pooling_kernel.to(input.dtype).to(input.device)- self.PoolingConv = self.PoolingConv.to(input.dtype).to(input.device)+ bin_pooling_weight = self.bin_pooling_kernel.weight.to(input.dtype).to(input.device)+ bin_pooling_bias = self.bin_pooling_kernel.bias+ if bin_pooling_bias is not None:+ bin_pooling_bias = bin_pooling_bias.to(input.dtype).to(input.device)+ poolingconv_weight = self.PoolingConv.weight.to(input.dtype).to(input.device)+ poolingconv_bias = self.PoolingConv.bias+ if poolingconv_bias is not None:+ poolingconv_bias = poolingconv_bias.to(input.dtype).to(input.device)grads = spatial_gradient(input, "diff")# unpack the edgesgx = grads[:, :, 0]@@ -398,15 +415,29 @@ class DenseSIFTDescriptor(nn.Module):wo1_big = wo1_big_ * magang_bins = torch.cat([- self.bin_pooling_kernel(- (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big+ F.conv2d(+ (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big,+ bin_pooling_weight,+ bin_pooling_bias,+ self.bin_pooling_kernel.stride,+ self.bin_pooling_kernel.padding,+ self.bin_pooling_kernel.dilation,+ self.bin_pooling_kernel.groups,)for i in range(self.num_ang_bins)],1,)- out_no_norm = self.PoolingConv(ang_bins)+ out_no_norm = F.conv2d(+ ang_bins,+ poolingconv_weight,+ poolingconv_bias,+ self.PoolingConv.stride,+ self.PoolingConv.padding,+ self.PoolingConv.dilation,+ self.PoolingConv.groups,+ )out = _l2_normalize(out_no_norm, dim=1).clamp_(0, float(self.clipval))out = _l2_normalize(out, dim=1)if self.rootsift:diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.pyindex f5d83b82e..bce891d40 100644--- a/tests/feature/test_local_features_orientation.py+++ b/tests/feature/test_local_features_orientation.py@@ -182,6 +182,39 @@ class TestOrientationKernelBuffer(BaseTester):mod(torch.rand(2, 1, 32, 32, dtype=torch.float64))assert (mod.weighting.dtype, mod.weighting.device) == before+ def test_forward_uses_input_dtype_without_mutating_angular_smooth(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)+ mod = PatchDominantGradientOrientation(32).to(device)+ ref = PatchDominantGradientOrientation(32).to(device, torch.float64)+ ref.load_state_dict(mod.state_dict())++ out = mod(patches)+ with torch.no_grad():+ expected = ref(patches)++ assert out.dtype == torch.float64+ assert torch.equal(out, expected)+ assert mod.angular_smooth.weight.dtype == torch.float32+ assert mod.angular_smooth.weight.device == device+ out.sum().backward()+ assert mod.angular_smooth.weight.grad is not None++ def test_forward_uses_input_device_without_mutating_angular_smooth(self, device):+ if device.type == "cpu":+ pytest.skip("device mismatch requires a non-CPU test device")+ if not supports_replicate_padding(device, torch.float32):+ pytest.skip(f"no float32 replicate-pad kernel on {device.type}")+ patches = torch.rand(2, 1, 32, 32, device=device)+ mod = PatchDominantGradientOrientation(32)++ out = mod(patches)++ assert out.device == device+ assert mod.angular_smooth.weight.device == torch.device("cpu")+class TestOriNet(BaseTester):def test_shape(self, device):diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex f84300f8d..51d67a4c0 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -25,7 +25,7 @@ from kornia.feature.siftdesc import (get_sift_pooling_kernel,)-from testing.base import BaseTester, supports_replicate_padding+from testing.base import BaseTester, supports_conv2d, supports_replicate_padding@pytest.mark.parametrize("ksize", [5, 13, 25])@@ -124,6 +124,39 @@ class TestSIFTDescriptorKernelBuffer(BaseTester):self.assert_close(mod.pk.weight, expected_pooling)self.assert_close(mod.gk, expected_weighting)+ def test_forward_uses_input_dtype_without_mutating_pooling_layer(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)+ mod = SIFTDescriptor(32).to(device)+ ref = SIFTDescriptor(32).to(device, torch.float64)+ ref.load_state_dict(mod.state_dict())++ out = mod(patches)+ with torch.no_grad():+ expected = ref(patches)++ assert out.dtype == torch.float64+ assert torch.equal(out, expected)+ assert mod.pk.weight.dtype == torch.float32+ assert mod.pk.weight.device == device+ out.sum().backward()+ assert mod.pk.weight.grad is not None++ def test_forward_uses_input_device_without_mutating_pooling_layer(self, device):+ if device.type == "cpu":+ pytest.skip("device mismatch requires a non-CPU test device")+ if not (supports_replicate_padding(device, torch.float32) and supports_conv2d(device, torch.float32)):+ pytest.skip(f"no float32 SIFT kernels on {device.type}")+ patches = torch.rand(2, 1, 32, 32, device=device)+ mod = SIFTDescriptor(32)++ out = mod(patches)++ assert out.device == device+ assert mod.pk.weight.device == torch.device("cpu")+class TestSIFTConstantPatchIsFinite(BaseTester):"""A constant patch has a zero-norm descriptor; normalising it must not give NaN.@@ -271,12 +304,49 @@ class TestDenseSIFTDescriptor(BaseTester):if device.type != "mps":mod = DenseSIFTDescriptor()+ before = (mod.bin_pooling_kernel.weight.dtype, mod.bin_pooling_kernel.weight.device)mod(torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64))kernel = mod.get_pooling_kernel()- assert kernel.dtype == torch.float64- assert kernel.device == device+ assert (kernel.dtype, kernel.device) == beforeself.assert_close(kernel, mod.bin_pooling_kernel.weight)+ def test_forward_uses_input_dtype_without_mutating_convolution_layers(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ img = torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64)+ mod = DenseSIFTDescriptor().to(device)+ ref = DenseSIFTDescriptor().to(device, torch.float64)+ ref.load_state_dict(mod.state_dict())++ out = mod(img)+ with torch.no_grad():+ expected = ref(img)++ assert out.dtype == torch.float64+ assert torch.equal(out, expected)+ assert mod.bin_pooling_kernel.weight.dtype == torch.float32+ assert mod.PoolingConv.weight.dtype == torch.float32+ assert mod.bin_pooling_kernel.weight.device == device+ assert mod.PoolingConv.weight.device == device+ out.sum().backward()+ assert mod.bin_pooling_kernel.weight.grad is not None+ assert mod.PoolingConv.weight.grad is not None++ def test_forward_uses_input_device_without_mutating_convolution_layers(self, device):+ if device.type == "cpu":+ pytest.skip("device mismatch requires a non-CPU test device")+ if not (supports_replicate_padding(device, torch.float32) and supports_conv2d(device, torch.float32)):+ pytest.skip(f"no float32 DenseSIFT kernels on {device.type}")+ img = torch.rand(1, 1, 8, 8, device=device)+ mod = DenseSIFTDescriptor()++ out = mod(img)++ assert out.device == device+ assert mod.bin_pooling_kernel.weight.device == torch.device("cpu")+ assert mod.PoolingConv.weight.device == torch.device("cpu")+def test_instances_do_not_share_buffer_storage(self, device):"""Instances must not share storage for `_poolingconv_weight` (see #4068).