Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): give each LoFTR its own copy of the config (#5720)

Dmytro Mishkin0756d9ba51aa
diff --git a/changelog.d/5720.fixed.md b/changelog.d/5720.fixed.md
new file mode 100644
index 000000000..ce2416fb2
--- /dev/null
+++ b/changelog.d/5720.fixed.md
@@ -0,0 +1 @@
+`LoFTR("indoor_new")` no longer switches every LoFTR created afterwards in the same process to the `indoor_new` positional encoding. It used to write `temp_bug_fix = True` into the shared module-level `default_cfg` (and into a config dict passed by the caller), so a later `LoFTR("outdoor")` ran with the wrong positional encoding and matched almost nothing. Each `LoFTR` now works on its own deep copy of the config.
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index aa69f8662..80cfe63a7 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import copy
from typing import Any, Optional
import torch
@@ -86,10 +87,12 @@ class LoFTR(nn.Module):
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
Args:
- config: Dict with initialization parameters. Do not pass it, unless you know what you are doing`.
- pretrained: Download and set pretrained weights to the model. Options: 'outdoor', 'indoor'.
- 'outdoor' is trained on the MegaDepth dataset and 'indoor'
- on the ScanNet.
+ config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.
+ The model works on its own deep copy, so the dict you pass is never modified.
+ pretrained: Download and set pretrained weights to the model. Options: 'outdoor', 'indoor', 'indoor_new'.
+ 'outdoor' is trained on the MegaDepth dataset and 'indoor' and 'indoor_new'
+ on the ScanNet. 'indoor_new' also switches the positional encoding of the copy
+ to ``temp_bug_fix=True``, which is what its checkpoint was trained with.
Returns:
Dictionary with image correspondences and confidence scores.
@@ -106,9 +109,11 @@ class LoFTR(nn.Module):
def __init__(self, pretrained: Optional[str] = "outdoor", config: dict[str, Any] = default_cfg) -> None:
super().__init__()
# Misc
- self.config = config
+ # Each instance owns its config: neither the module-level ``default_cfg`` nor a caller-passed dict is mutated.
+ config = copy.deepcopy(config)
if pretrained == "indoor_new":
- self.config["coarse"]["temp_bug_fix"] = True
+ config["coarse"]["temp_bug_fix"] = True
+ self.config = config
# Modules
self.backbone = build_backbone(config)
self.pos_encoding = PositionEncodingSine(
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 87fc1972b..185fba6e9 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -15,12 +15,15 @@
# limitations under the License.
#
+import copy
import sys
import pytest
import torch
from kornia.feature import LoFTR
+from kornia.feature.loftr import loftr as loftr_module
+from kornia.feature.loftr.loftr import default_cfg
from kornia.feature.loftr.utils.coarse_matching import CoarseMatching
from kornia.feature.loftr.utils.fine_matching import FineMatching
from kornia.geometry import resize
@@ -111,6 +114,50 @@ class TestLoFTR(BaseTester):
self.assert_close(v, out_jit[k])
+class TestLoFTRConfigIsPerInstance(BaseTester):
+ """Building a LoFTR must not write into ``default_cfg`` or into a caller-passed config."""
+
+ @pytest.fixture
+ def offline_pretrained(self, monkeypatch):
+ """Let ``LoFTR(pretrained=name)`` run its config selection without downloading a checkpoint."""
+ state = {"state_dict": LoFTR(None).state_dict()}
+ monkeypatch.setattr(loftr_module, "load_state_dict_from_url", lambda *args, **kwargs: state)
+
+ def test_indoor_new_leaves_default_cfg_untouched_5719(self, offline_pretrained):
+ before = copy.deepcopy(default_cfg)
+ LoFTR("indoor_new")
+ assert default_cfg == before
+ assert default_cfg["coarse"]["temp_bug_fix"] is False
+
+ def test_indoor_new_uses_the_fixed_positional_encoding_5719(self, offline_pretrained):
+ indoor_new = LoFTR("indoor_new")
+ assert indoor_new.config["coarse"]["temp_bug_fix"] is True
+ assert indoor_new.pos_encoding.temp_bug_fix is True
+ assert not torch.allclose(indoor_new.pos_encoding.pe, LoFTR(None).pos_encoding.pe)
+
+ def test_later_default_model_keeps_the_outdoor_positional_encoding_5719(self, offline_pretrained):
+ expected_pe = LoFTR(None).pos_encoding.pe.clone()
+ LoFTR("indoor_new")
+ later = LoFTR(None)
+ assert later.config["coarse"]["temp_bug_fix"] is False
+ assert later.pos_encoding.temp_bug_fix is False
+ self.assert_close(later.pos_encoding.pe, expected_pe)
+
+ def test_caller_config_is_not_mutated_5719(self, offline_pretrained):
+ config = copy.deepcopy(default_cfg)
+ before = copy.deepcopy(config)
+ model = LoFTR("indoor_new", config=config)
+ assert config == before
+ assert model.config is not config
+ assert model.config["coarse"]["temp_bug_fix"] is True
+
+ def test_instances_do_not_share_config_5719(self):
+ a, b = LoFTR(None), LoFTR(None)
+ assert a.config is not b.config
+ assert a.config["coarse"] is not b.config["coarse"]
+ assert a.config is not default_cfg
+
+
class TestCoarseMatching(BaseTester):
"""CoarseMatching.get_coarse_match's training-mode gt-padding branch
(self.training=True) previously crashed unconditionally: zip() was