Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): SOLD2_detector builds and runs no descriptor head; share SOLD2's mirrored checkpoint (#6424)

Dmytro Mishkina4b28a4a35fc
diff --git a/changelog.d/6424.added.md b/changelog.d/6424.added.md
new file mode 100644
index 000000000..dd7fda199
--- /dev/null
+++ b/changelog.d/6424.added.md
@@ -0,0 +1 @@
+`SOLD2_detector` neither builds nor runs the descriptor head of the SOLD2 network, whose output it never used: the same junctions, heatmaps and line segments, 7 % fewer parameters, and a network forward about 7 % faster at 512 x 512 on an Apple M1, on CPU and MPS; the whole detector, whose line detection is unchanged, is about 3 % faster on CPU. Weights saved with the head still load. `SOLD2_detector` also downloads the pretrained checkpoint from the Hugging Face mirror with a fallback, the same file `SOLD2` uses, instead of a single ETH URL, so the two classes share one cached copy.
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index a311afd73..a17c9dfab 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -483,7 +483,7 @@ class SOLD2Net(nn.Module):
a Dict with the following values:
junctions: heatmap of junctions.
heatmap: line heatmap.
- descriptors: semi-dense descriptors.
+ descriptors: semi-dense descriptors, only when ``use_descriptor`` is true in ``model_cfg``.
"""
@@ -501,9 +501,27 @@ class SOLD2Net(nn.Module):
# Line heatmap decoder
self.heatmap_decoder = PixelShuffleDecoder(feat_channel, num_upsample=2)
- # Descriptor decoder
- if "use_descriptor" in self.cfg:
- self.descriptor_decoder = SuperpointDescriptor(feat_channel)
+ # Descriptor decoder, only when the descriptors are used: SOLD2 sets use_descriptor, SOLD2_detector does not
+ self.descriptor_decoder = SuperpointDescriptor(feat_channel) if self.cfg.get("use_descriptor", False) else None
+
+ def _load_from_state_dict(
+ self,
+ state_dict: Dict[str, Any],
+ prefix: str,
+ local_metadata: Dict[str, Any],
+ strict: bool,
+ missing_keys: List[str],
+ unexpected_keys: List[str],
+ error_msgs: List[str],
+ ) -> None:
+ # The pretrained checkpoint, and state dicts saved from a detector that built the descriptor head, carry its
+ # weights; a network without the head loads the rest. ``load_state_dict`` passes a copy of the caller's dict.
+ if self.descriptor_decoder is None:
+ for key in [k for k in state_dict if k.startswith(prefix + "descriptor_decoder.")]:
+ del state_dict[key]
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
def forward(self, input_images: torch.Tensor) -> Dict[str, torch.Tensor]:
"""Run this SOLD2 backbone component forward.
@@ -526,7 +544,7 @@ class SOLD2Net(nn.Module):
outputs = {"junctions": junctions, "heatmap": heatmaps}
# Descriptor decoder
- if "use_descriptor" in self.cfg:
+ if self.descriptor_decoder is not None:
outputs["descriptors"] = self.descriptor_decoder(features)
return outputs
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 5f43da44f..45ef2ae95 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -23,18 +23,12 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.download import hf_url, load_state_dict_from_url
+from kornia.core.download import load_state_dict_from_url
from kornia.core.utils import dataclass_to_dict, dict_to_dataclass
from kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfg
from .backbones import SOLD2Net
-from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions
-
-urls: Dict[str, str | list[str]] = {}
-urls["wireframe"] = [
- hf_url("sold2", "sold2_wireframe.pth"),
- "https://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
-]
+from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions, urls
class SOLD2(nn.Module):
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 1b6cb8951..674d584dd 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -17,21 +17,24 @@
import math
import warnings
-from typing import Any, Dict, Optional, Tuple, cast
+from typing import Any, Dict, List, Optional, Tuple, cast
import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.download import load_state_dict_from_url
+from kornia.core.download import hf_url, load_state_dict_from_url
from kornia.core.utils import dataclass_to_dict, dict_to_dataclass
from kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfg
from kornia.geometry.bbox import nms
from .backbones import SOLD2Net
-urls: Dict[str, str] = {}
-urls["wireframe"] = "https://cvg-data.inf.ethz.ch/SOLD2/sold2_wireframe.tar"
+urls: Dict[str, List[str]] = {}
+urls["wireframe"] = [
+ hf_url("sold2", "sold2_wireframe.pth"),
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
+]
class SOLD2_detector(nn.Module):
@@ -72,7 +75,7 @@ class SOLD2_detector(nn.Module):
warnings.warn(
"Usage of config as a plain dictionary is deprecated in favor of"
"`kornia.features.sold2.structures.DetectorCfg`. The support of plain"
- "dictionaries as config will be removed in kornia v0.8.0 (December 2024).",
+ "dictionaries as config will be removed in a future release.",
category=DeprecationWarning,
stacklevel=2,
)
diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.py
index 65e52ddf4..ca0040f93 100644
--- a/tests/core/test_weights_prefetch.py
+++ b/tests/core/test_weights_prefetch.py
@@ -223,9 +223,6 @@ NOT_PREFETCHED: dict[str, str] = {
"tfeat-yosemite.params": "yosemite variant; tests use the liberty default",
# Model variants no test selects.
"loftr_indoor_ds_new.ckpt": "tests instantiate LoFTR('indoor') and LoFTR('outdoor') only",
- "sold2_wireframe.tar": (
- "the suite builds SOLD2_detector random, or weighted through the prefetched, byte-identical sold2_wireframe.pth"
- ),
"epipolar-save.pth": "tests call DISK.from_pretrained(checkpoint='depth')",
# LightGlue heads: tests build the disk and doghardnet matchers, and the
# suite also reaches the superpoint head. The rest are unused.
diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.py
index b72a7b1ef..e447c1b3c 100644
--- a/tests/feature/test_sold2.py
+++ b/tests/feature/test_sold2.py
@@ -52,13 +52,38 @@ class TestSOLD2_detector(BaseTester):
def test_jit(self, device, dtype):
B, C, H, W = 2, 1, 128, 128
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
- # pretrained=False: scripting does not need the weights, and the CI cache
- # deliberately does not carry ``sold2_wireframe.tar`` -- see
- # ``NOT_PREFETCHED`` in tests/core/test_weights_prefetch.py.
+ # pretrained=False: scripting does not need the weights
model = SOLD2_detector(pretrained=False).to(img.device, img.dtype).eval()
model_jit = torch.jit.script(model)
self.assert_close(model(img), model_jit(img))
+ def test_has_no_descriptor_head(self, device, dtype):
+ # SOLD2_detector returns no descriptors, so its network neither builds nor runs the descriptor head; SOLD2 does
+ detector = SOLD2_detector(pretrained=False).to(device, dtype).eval()
+ assert detector.model.descriptor_decoder is None
+ assert not any("descriptor_decoder" in key for key in detector.state_dict())
+ assert SOLD2(pretrained=False).model.descriptor_decoder is not None
+ with torch.no_grad():
+ outputs = detector.model(torch.rand(1, 1, 64, 64, device=device, dtype=dtype))
+ assert set(outputs) == {"junctions", "heatmap"}
+
+ def test_loads_weights_with_a_descriptor_head_and_detects_as_sold2(self, device, dtype):
+ # the pretrained checkpoint, and state dicts saved from a detector that built the head, carry the head's weights
+ torch.manual_seed(0)
+ sold2 = SOLD2(pretrained=False).to(device, dtype).eval()
+ detector = SOLD2_detector(pretrained=False).to(device, dtype).eval()
+ weights = sold2.model.state_dict()
+ detector.model.load_state_dict(weights)
+ assert any(key.startswith("descriptor_decoder.") for key in weights) # the caller's dict is left as it was
+ img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ with torch.no_grad():
+ expected, actual = sold2(img), detector(img)
+ self.assert_close(actual["junction_heatmap"], expected["junction_heatmap"])
+ self.assert_close(actual["line_heatmap"], expected["line_heatmap"])
+ assert len(actual["line_segments"]) == len(expected["line_segments"])
+ for segments, expected_segments in zip(actual["line_segments"], expected["line_segments"]):
+ self.assert_close(segments, expected_segments)
+
class TestJunctionsAndSegments(BaseTester):
def test_bilinear_integer_coordinates(self, device, dtype):