π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): give the untrained HardNet8 a non-degenerate PCA placeholder (#5693)
Dmytro Mishkin962ccd7555cb
diff --git a/changelog.d/5693.fixed.md b/changelog.d/5693.fixed.mdnew file mode 100644index 000000000..8fed97b73--- /dev/null+++ b/changelog.d/5693.fixed.md@@ -0,0 +1,3 @@+`HardNet8()` without pretrained weights now gives distinct, trainable descriptors. Its placeholder PCA projection+was an all-ones matrix, which mapped every patch to the same descriptor up to sign; it now keeps the first 128 of the+512 features until the pretrained weights replace it.diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 96634576e..43616fd7d 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -139,7 +139,8 @@ class HardNet8(nn.Module):See :cite:`HardNet2020` for more details.Args:- pretrained: Download and set pretrained weights to the model.+ pretrained: Download and set pretrained weights to the model. The 512-d features are projected to 128-d by a+ PCA stored with the weights; without them, the projection keeps the first 128 features.Returns:torch.Tensor: HardNet8 descriptor of the patches.@@ -186,7 +187,9 @@ class HardNet8(nn.Module):nn.BatchNorm2d(512, affine=False),)self.features.apply(self.weights_init)- self.register_buffer("components", torch.ones(512, 128, dtype=torch.float))+ # Placeholder PCA until a checkpoint replaces it: keep the first 128 of the 512 features. An all-ones+ # projection would collapse every descriptor to +-(1, ..., 1) / sqrt(128), with a zero gradient.+ self.register_buffer("components", torch.eye(512, 128, dtype=torch.float))self.register_buffer("mean", torch.zeros(512, dtype=torch.float))# use torch.hub to load pretrained modeldiff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.pyindex 8c6dfbf20..c2fa38f8c 100644--- a/tests/feature/test_hardnet.py+++ b/tests/feature/test_hardnet.py@@ -79,6 +79,53 @@ class TestHardNet8(BaseTester):model_jit = torch.jit.script(HardNet8().to(patches.device, patches.dtype).eval())self.assert_close(model(patches), model_jit(patches))+ def test_untrained_descriptors_are_distinct_5692(self, device, dtype):+ # An all-ones PCA placeholder mapped every patch to +-(1, ..., 1) / sqrt(128).+ if not supports_conv2d(device, dtype):+ pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ patches = torch.rand(8, 1, 32, 32, device=device, dtype=dtype)+ out = HardNet8().to(device, dtype)(patches)+ assert out.shape == (8, 128)+ self.assert_close(out.norm(dim=1), torch.ones(8, device=device, dtype=dtype))+ cos = out @ out.T+ off_diagonal = cos[~torch.eye(8, dtype=torch.bool, device=device)]+ assert off_diagonal.abs().max() < 0.99++ def test_untrained_model_keeps_the_first_features_5692(self, device, dtype):+ if not supports_conv2d(device, dtype):+ pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)+ model = HardNet8().to(device, dtype)+ features = model.features(model._normalize_input(patches)).view(4, -1)+ expected = torch.nn.functional.normalize(torch.nn.functional.normalize(features, dim=1)[:, :128], dim=1)+ self.assert_close(model(patches), expected)++ def test_untrained_model_is_trainable_5692(self, device, dtype):+ # The all-ones placeholder made the normalised output constant, so the gradient was zero (~1e-15).+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("half-precision rounding leaves a noise gradient on the degenerate placeholder as well")+ torch.manual_seed(0)+ patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)+ model = HardNet8().to(device, dtype)+ target = torch.randn(4, 128, device=device, dtype=dtype)+ (model(patches) * target).sum().backward()+ grad = model.features[0].weight.grad+ assert grad is not None+ assert grad.abs().max() > 1e-3++ def test_checkpoint_layout_is_unchanged_5692(self, device):+ # The pretrained checkpoint loads with strict=True, so the buffer names and shapes must stay.+ model = HardNet8().to(device)+ state = model.state_dict()+ assert state["components"].shape == (512, 128)+ assert state["mean"].shape == (512,)+ loaded = torch.rand(512, 128, device=device)+ state["components"] = loaded+ model.load_state_dict(state, strict=True)+ self.assert_close(model.components, loaded)+class TestHardNetConstantPatchIsFinite(BaseTester):"""A constant patch drives the features to zero; the L2 normalisation must not give NaN.