Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): SOLD2 no longer replaces torch.diag or mutates the caller's config (#5723)

Dmytro Mishkinb85c22d6e0d5
diff --git a/changelog.d/5723.fixed.md b/changelog.d/5723.fixed.md
new file mode 100644
index 000000000..86b38672d
--- /dev/null
+++ b/changelog.d/5723.fixed.md
@@ -0,0 +1 @@
+`SOLD2.match` no longer replaces the global `torch.diag` with a tensor, which made every later `torch.diag(...)` call in the process (including `MKDDescriptor(whitening=...)`) raise `TypeError`. `SOLD2(config=cfg)` no longer sets `use_descriptor = True` on the `DetectorCfg` it is given; it works on a copy. `WunschLineMatcher.needleman_wunsch` now allocates its table in the dtype of the scores; float64 scores used to raise an index_put dtype error, and half-precision scores gave a float32 result. `SOLD2.match` now samples each descriptor map with a grid in that map's dtype, so segments in any floating-point dtype, including the float32 segments `SOLD2.forward` returns, match against the descriptors of a float64 or half-precision model; that, and float64 segments with float32 descriptors, used to raise a `grid_sample` dtype error such as `expected scalar type Half but found Float`.
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 81f35c382..410e713ca 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import copy
from typing import Any, Dict, Optional, Tuple, cast
import torch
@@ -43,8 +44,9 @@ class SOLD2(nn.Module):
Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
Args:
- config: Dict specifying parameters. None will load the default parameters,
- which are tuned for images in the range 400~800 px.
+ config: :class:`~kornia.feature.sold2.structures.DetectorCfg`, or a dict of its fields, specifying
+ parameters. None will load the default parameters, which are tuned for images in the range 400~800 px.
+ The model works on a copy with ``use_descriptor`` set to True; the object passed in is not modified.
pretrained: If True, download and set pretrained weights to the model.
Returns:
@@ -68,7 +70,8 @@ class SOLD2(nn.Module):
config = dict_to_dataclass(cast(Dict[str, Any], config), DetectorCfg)
super().__init__()
# Initialize some parameters
- self.config = config if config is not None else DetectorCfg()
+ # Copy so the descriptor head flag never leaks into the caller's object.
+ self.config = copy.deepcopy(config) if config is not None else DetectorCfg()
self.config.use_descriptor = True # Only difference to SOLD2_detector DetectorCfg
self.grid_size = self.config.grid_size
self.junc_detect_thresh = self.config.detection_thresh
@@ -128,6 +131,8 @@ class SOLD2(nn.Module):
) -> torch.Tensor:
"""Find the best matches between two sets of line segments and their corresponding descriptors.
+ Each descriptor map is sampled in its own dtype, so the segments may be in another floating-point dtype.
+
Args:
line_seg1: list of line segments in image 1, with shape [num_lines, 2, 2].
line_seg2: list of line segments in image 2, with shape [num_lines, 2, 2].
@@ -135,7 +140,7 @@ class SOLD2(nn.Module):
desc2: semi-dense descriptor map of image 2, with shape [1, 128, H/4, W/4].
Returns:
- A np.array of size [num_lines1] indicating the index in line_seg2 of the matched line,
+ An integer tensor of size [num_lines1] indicating the index in line_seg2 of the matched line,
for each line in line_seg1. -1 means that the line is not matched.
"""
@@ -203,9 +208,10 @@ class WunschLineMatcher(nn.Module):
line_points1 = line_points1.reshape(-1, 2)
line_points2 = line_points2.reshape(-1, 2)
- # Extract the descriptors for each point
- grid1 = keypoints_to_grid(line_points1, img_size1)
- grid2 = keypoints_to_grid(line_points2, img_size2)
+ # Extract the descriptors for each point. F.grid_sample needs the grid in the dtype of the map it samples,
+ # and the segments need not share it (SOLD2.forward returns float32 segments whatever the model dtype).
+ grid1 = keypoints_to_grid(line_points1, img_size1).to(desc1.dtype)
+ grid2 = keypoints_to_grid(line_points2, img_size2).to(desc2.dtype)
desc1 = F.normalize(F.grid_sample(desc1, grid1, align_corners=False)[0, :, :, 0], dim=0)
desc2 = F.normalize(F.grid_sample(desc2, grid2, align_corners=False)[0, :, :, 0], dim=0)
@@ -312,7 +318,7 @@ class WunschLineMatcher(nn.Module):
# Recalibrate the scores to get a gap score of 0
gap = 0.1
B, N, M = scores.shape
- dp = torch.zeros(B, N + 1, M + 1, device=scores.device)
+ dp = torch.zeros(B, N + 1, M + 1, device=scores.device, dtype=scores.dtype)
S = scores - gap
for k in range(2, N + M + 1):
i_min = max(1, k - M)
@@ -321,8 +327,8 @@ class WunschLineMatcher(nn.Module):
j = k - i
up = dp[:, i - 1, j]
left = dp[:, i, j - 1]
- torch.diag = dp[:, i - 1, j - 1] + S[:, i - 1, j - 1]
- dp[:, i, j] = torch.max(torch.max(up, left), torch.diag)
+ diag = dp[:, i - 1, j - 1] + S[:, i - 1, j - 1]
+ dp[:, i, j] = torch.max(torch.max(up, left), diag)
return dp[:, -1, -1]
diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.py
index e6d1d6eac..617fd5728 100644
--- a/tests/feature/test_sold2.py
+++ b/tests/feature/test_sold2.py
@@ -21,9 +21,9 @@ import torch.nn.functional as F
from kornia.core.check import ShapeError
from kornia.feature.sold2 import SOLD2, SOLD2_detector
-from kornia.feature.sold2.sold2 import keypoints_to_grid
+from kornia.feature.sold2.sold2 import WunschLineMatcher, keypoints_to_grid
from kornia.feature.sold2.sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions
-from kornia.feature.sold2.structures import LineDetectorCfg
+from kornia.feature.sold2.structures import DetectorCfg, LineDetectorCfg
from testing.base import BaseTester
@@ -178,6 +178,79 @@ class TestSOLD2(BaseTester):
model_jit = torch.jit.script(model)
self.assert_close(model(img), model_jit(img))
+ def test_config_is_not_modified_5722(self):
+ cfg = DetectorCfg()
+ assert cfg.use_descriptor is False
+ sold2 = SOLD2(pretrained=False, config=cfg)
+ assert cfg.use_descriptor is False
+ assert sold2.config is not cfg
+ assert sold2.config.use_descriptor is True
+
+ def test_config_dict_is_not_modified_5722(self):
+ cfg = {"grid_size": 4}
+ sold2 = SOLD2(pretrained=False, config=cfg)
+ assert cfg == {"grid_size": 4}
+ assert sold2.config.grid_size == 4
+ assert sold2.config.use_descriptor is True
+
+ def test_detector_config_is_not_modified_5722(self):
+ cfg = DetectorCfg()
+ detector = SOLD2_detector(pretrained=False, config=cfg)
+ assert cfg.use_descriptor is False
+ assert detector.config.use_descriptor is False
+
+ def test_match_keeps_torch_diag_5722(self, device, dtype):
+ sold2 = SOLD2(pretrained=False).to(device, dtype)
+ diag = torch.diag
+ seg1 = torch.tensor([[[10.0, 10.0], [60.0, 90.0]], [[20.0, 70.0], [80.0, 20.0]]], device=device, dtype=dtype)
+ desc = torch.randn(1, 128, 24, 32, device=device, dtype=dtype)
+ sold2.match(seg1, seg1 + 1.0, desc, desc.flip(-1))
+ assert torch.diag is diag
+ assert callable(torch.diag)
+ self.assert_close(
+ torch.diag(torch.ones(3, device=device, dtype=dtype)), torch.eye(3, device=device, dtype=dtype)
+ )
+
+ def test_match_segment_dtype_differs_from_descriptors_5722(self, device, dtype):
+ # SOLD2.forward returns float32 segments whatever the model dtype, so match must accept segments whose
+ # dtype differs from the descriptor map's, in both directions.
+ sold2 = SOLD2(pretrained=False).to(device, dtype)
+ seg = torch.tensor(
+ [[[10.0, 10.0], [60.0, 90.0]], [[20.0, 70.0], [80.0, 20.0]], [[85.0, 5.0], [85.0, 120.0]]], device=device
+ )
+ desc = torch.randn(1, 128, 24, 32, device=device, dtype=dtype)
+ # identical segments and descriptors in both images: every line matches itself
+ assert sold2.match(seg, seg, desc, desc).tolist() == [0, 1, 2]
+ desc32 = desc.float()
+ assert sold2.match(seg.to(dtype), seg.to(dtype), desc32, desc32).tolist() == [0, 1, 2]
+
+
+class TestWunschLineMatcher(BaseTester):
+ def test_needleman_wunsch_keeps_torch_diag_5722(self, device, dtype):
+ diag = torch.diag
+ scores = torch.rand(2, 3, 5, device=device, dtype=dtype)
+ out = WunschLineMatcher().needleman_wunsch(scores)
+ assert out.shape == (2,)
+ assert torch.diag is diag
+ self.assert_close(
+ torch.diag(torch.ones(3, device=device, dtype=dtype)), torch.eye(3, device=device, dtype=dtype)
+ )
+
+ def test_needleman_wunsch_float64_matches_float32_5722(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ scores = torch.rand(2, 3, 5, device=device, dtype=torch.float32)
+ out32 = WunschLineMatcher().needleman_wunsch(scores)
+ out64 = WunschLineMatcher().needleman_wunsch(scores.double())
+ assert out64.dtype == torch.float64
+ self.assert_close(out64.float(), out32, low_tolerance=True)
+
+ def test_needleman_wunsch_value(self, device, dtype):
+ # one-to-one alignment: dp[-1, -1] is the best sum of (score - 0.1) over a monotone matching
+ scores = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]]], device=device, dtype=dtype)
+ out = WunschLineMatcher().needleman_wunsch(scores)
+ self.assert_close(out, torch.tensor([2.8], device=device, dtype=dtype), low_tolerance=True)
+
class TestKeypointsToGrid(BaseTester):
# keypoints_to_grid feeds F.grid_sample(..., align_corners=False) in WunschLineMatcher, so its