π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): reject HyNet pretrained weights with is_bias_FRN=False (#6037)
Aditya Sinha453f6170bd01
diff --git a/changelog.d/6017.breaking.md b/changelog.d/6017.breaking.mdindex d97274b2a..0c6bf5685 100644--- a/changelog.d/6017.breaking.md+++ b/changelog.d/6017.breaking.md@@ -1,3 +1,3 @@-`HardNet`, `HardNet8`, `HyNet`, `SOSNet`, `TFeat`, `OriNet`, `LAFAffNetShapeEstimator`, `KeyNet`, `KeyNetDetector` and `DeFMO` default to `pretrained=True`. Constructing one downloads its weights (once) and returns the trained model in evaluation mode; for `KeyNetDetector` that is its `KeyNet` network, while the detector itself keeps its mode, so an `ori_module` or `aff_module` you pass is not switched. They defaulted to random weights, returned in evaluation mode with BatchNorm, where the network has any, on its initial statistics. Pass `pretrained=False` for random weights. An architecture argument the checkpoint does not fit now needs `pretrained=False` as well: with the default, `HyNet` with another `is_bias` or `dim_desc`, and `KeyNet` or `KeyNetDetector` with a `keynet_conf` of another `num_levels` or `kernel_size`, raise `RuntimeError` from the strict weight load, and `HyNet(is_bias_FRN=False)` loads the weights but leaves their trained FRN biases unused.+`HardNet`, `HardNet8`, `HyNet`, `SOSNet`, `TFeat`, `OriNet`, `LAFAffNetShapeEstimator`, `KeyNet`, `KeyNetDetector` and `DeFMO` default to `pretrained=True`. Constructing one downloads its weights (once) and returns the trained model in evaluation mode; for `KeyNetDetector` that is its `KeyNet` network, while the detector itself keeps its mode, so an `ori_module` or `aff_module` you pass is not switched. They defaulted to random weights, returned in evaluation mode with BatchNorm, where the network has any, on its initial statistics. Pass `pretrained=False` for random weights. An architecture argument the checkpoint does not fit now needs `pretrained=False` as well: with the default, `HyNet` with another `is_bias` or `dim_desc`, and `KeyNet` or `KeyNetDetector` with a `keynet_conf` of another `num_filters`, `num_levels` or `kernel_size`, raise `RuntimeError` from the strict weight load, and `HyNet(is_bias_FRN=False)` raises `ValueError` before downloading the weights, which would load but leave their trained FRN biases unused.Randomly initialised models are returned in training mode: `pretrained=False` on those classes, `SOLD2(pretrained=False)`, `SOLD2_detector(pretrained=False)` and `LoFTR(pretrained=None)`. They were returned in evaluation mode. Call `.eval()` before inference, and after loading your own weights into one of them. A random `LoFTR` in training mode runs its supervised training branch, so its forward raises without ground-truth matches until `.eval()` is called.diff --git a/changelog.d/6037.fixed.md b/changelog.d/6037.fixed.mdnew file mode 100644index 000000000..6e3127e77--- /dev/null+++ b/changelog.d/6037.fixed.md@@ -0,0 +1 @@+`HyNet(pretrained=True, is_bias_FRN=False)` now raises `ValueError` before downloading the weights. Previously it loaded the checkpoint without error but left the trained FRN biases unused, so its descriptors differed from the pretrained ones. Pass `pretrained=False` to build `HyNet` with `is_bias_FRN=False`.diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex df21278a3..46e0247ec 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -221,8 +221,8 @@ class HyNet(nn.Module):Args:pretrained: Download and set pretrained weights to the model. The weights fit the default ``is_bias``,``is_bias_FRN`` and ``dim_desc`` only, so pass ``pretrained=False`` with another value: the strict load- raises ``RuntimeError`` for another ``is_bias`` or ``dim_desc``, and ``is_bias_FRN=False`` loads the- weights but leaves their trained FRN biases unused.+ raises ``RuntimeError`` for another ``is_bias`` or ``dim_desc``, and ``is_bias_FRN=False`` raises+ ``ValueError`` before downloading, since the weights would load but leave their trained FRN biases unused.is_bias: use bias in the convolution layers (the final 8 x 8 convolution has none either way)is_bias_FRN: use bias in FRN layersdim_desc: descriptor dimensionality,@@ -259,6 +259,12 @@ class HyNet(nn.Module):eps_l2_norm: float = 1e-10,) -> None:super().__init__()+ if pretrained and not is_bias_FRN:+ # The FRN biases exist with either flag, so the strict load cannot catch this mismatch.+ raise ValueError(+ "HyNet's pretrained weights use their trained FRN biases; pass pretrained=False to build it with "+ "is_bias_FRN=False."+ )self.eps_l2_norm = eps_l2_normself.dim_desc = dim_descself.drop_rate = drop_ratediff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.pyindex 76fbedaee..665080856 100644--- a/tests/feature/test_hynet.py+++ b/tests/feature/test_hynet.py@@ -45,6 +45,25 @@ class TestHyNet(BaseTester):with pytest.raises(ShapeError):HyNet(pretrained=False).to(device).eval()(torch.ones(*shape, device=device))+ @pytest.mark.device_agnostic+ def test_pretrained_rejects_is_bias_frn_false_6016(self, monkeypatch):+ # ``is_bias_FRN=False`` used to load the checkpoint and silently skip its trained FRN biases.+ state_dict = HyNet(pretrained=False).state_dict()+ downloads = []++ def fake_load_state_dict_from_url(*args, **kwargs):+ downloads.append(args)+ return state_dict++ monkeypatch.setattr("kornia.feature.hynet.load_state_dict_from_url", fake_load_state_dict_from_url)+ with pytest.raises(ValueError, match="is_bias_FRN"):+ HyNet(pretrained=True, is_bias_FRN=False)+ assert downloads == []++ HyNet(pretrained=True)+ assert len(downloads) == 1+ HyNet(pretrained=False, is_bias_FRN=False)+def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)hynet = HyNet(pretrained=False).to(device).eval()