Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): build KeyNet's learnable block with num_filters channels (#6036)

Aditya Sinha529e20b8ea88
diff --git a/changelog.d/6036.fixed.md b/changelog.d/6036.fixed.md
new file mode 100644
index 000000000..a2746b612
--- /dev/null
+++ b/changelog.d/6036.fixed.md
@@ -0,0 +1 @@
+`KeyNet` and `KeyNetDetector` build their learnable block with `num_filters` channels per level, so a `num_filters` other than the default 8 no longer crashes in `forward`. The default architecture and the pretrained weights are unchanged.
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index b22f17bd6..727a6ee30 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -63,11 +63,11 @@ class _FeatureExtractor(nn.Module):
It loads both, the handcrafted and learnable blocks
"""
- def __init__(self) -> None:
+ def __init__(self, num_filters: int = 8) -> None:
super().__init__()
self.hc_block = _HandcraftedBlock()
- self.lb_block = _LearnableBlock()
+ self.lb_block = _LearnableBlock(num_filters=num_filters)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x_hc = self.hc_block(x)
@@ -100,12 +100,12 @@ class _LearnableBlock(nn.Sequential):
It defines the learnable blocks within the Key.Net
"""
- def __init__(self, in_channels: int = 10) -> None:
+ def __init__(self, in_channels: int = 10, num_filters: int = 8) -> None:
super().__init__()
- self.conv0 = _KeyNetConvBlock(in_channels)
- self.conv1 = _KeyNetConvBlock()
- self.conv2 = _KeyNetConvBlock()
+ self.conv0 = _KeyNetConvBlock(in_channels, num_filters)
+ self.conv1 = _KeyNetConvBlock(num_filters, num_filters)
+ self.conv2 = _KeyNetConvBlock(num_filters, num_filters)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# These narrow convolutions benefit from channel-contiguous activations on
@@ -153,7 +153,7 @@ class KeyNet(nn.Module):
Args:
pretrained: Download and set pretrained weights to the model.
keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A
- ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
+ ``num_filters``, ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.
Returns:
@@ -175,7 +175,7 @@ class KeyNet(nn.Module):
kernel_size = keynet_conf["kernel_size"]
padding = kernel_size // 2
- self.feature_extractor = _FeatureExtractor()
+ self.feature_extractor = _FeatureExtractor(num_filters)
self.last_conv = nn.Sequential(
nn.Conv2d(
in_channels=num_filters * self.num_levels, out_channels=1, kernel_size=kernel_size, padding=padding
@@ -217,7 +217,7 @@ class KeyNetDetector(MultiResolutionDetector):
pretrained: Download and set pretrained weights to the model.
num_features: Number of features to detect.
keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A
- ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
+ ``num_filters``, ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.
ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
diff --git a/tests/feature/test_keynet.py b/tests/feature/test_keynet.py
index 5077d970f..7236133d2 100644
--- a/tests/feature/test_keynet.py
+++ b/tests/feature/test_keynet.py
@@ -19,6 +19,7 @@ import pytest
import torch
from kornia.feature import KeyNet
+from kornia.feature.keynet import keynet_default_config
from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
@@ -48,6 +49,31 @@ class TestKeyNet(BaseTester):
out = keynet(inp)
assert out.shape == inp.shape
+ @pytest.mark.parametrize("num_filters", [4, 16])
+ def test_non_default_num_filters(self, num_filters, device, dtype):
+ # The learnable block used to produce 8 channels per level whatever ``num_filters`` said, while
+ # ``last_conv`` expects ``num_filters * num_levels``, so any other value crashed in ``forward`` (#6015).
+ keynet_conf = {**keynet_default_config, "num_filters": num_filters}
+ keynet = KeyNet(pretrained=False, keynet_conf=keynet_conf).to(device, dtype).eval()
+ # As in the reference Key.Net, every learnable block is ``num_filters`` wide, not only the first and last.
+ widths = [(m.in_channels, m.out_channels) for m in keynet.modules() if isinstance(m, torch.nn.Conv2d)]
+ last_in = num_filters * keynet_default_config["num_levels"]
+ assert widths == [(10, num_filters), (num_filters, num_filters), (num_filters, num_filters), (last_in, 1)]
+ inp = torch.rand(1, 1, 40, 56, device=device, dtype=dtype)
+ out = keynet(inp)
+ assert out.shape == inp.shape
+
+ @pytest.mark.device_agnostic
+ def test_pretrained_rejects_non_default_num_filters(self, monkeypatch):
+ # The checkpoint has 8 filters per level, so a non-default ``num_filters`` must still fail the strict load.
+ state_dict = KeyNet(pretrained=False).state_dict()
+ monkeypatch.setattr(
+ "kornia.feature.keynet.load_state_dict_from_url", lambda *args, **kwargs: {"state_dict": state_dict}
+ )
+ KeyNet(pretrained=True)
+ with pytest.raises(RuntimeError, match="size mismatch"):
+ KeyNet(pretrained=True, keynet_conf={**keynet_default_config, "num_filters": 4})
+
def test_gradcheck(self, device):
patches = torch.rand(2, 1, 16, 16, device=device, dtype=torch.float64)
keynet = KeyNet(pretrained=False).to(patches.device, patches.dtype).eval()