Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): CoarseMatching training-mode gt-padding crash + dtype leak (#4359)

tritsystem8ca60bc34b76
diff --git a/changelog.d/4359.fixed.md b/changelog.d/4359.fixed.md
new file mode 100644
index 000000000..dc7a42116
--- /dev/null
+++ b/changelog.d/4359.fixed.md
@@ -0,0 +1,8 @@
+`kornia.feature.loftr`'s `CoarseMatching` no longer crashes in training mode. Its gt-padding
+branch called `zip()` with four separate 2-element lists instead of two 4-element lists, so
+every resulting tuple failed to unpack (`ValueError: too many values to unpack`) on every call;
+no existing test exercised this path. Restructured the `zip()` to pair each real tensor with its
+ground-truth counterpart. Once reachable, a second bug surfaced: the padding tensor `mconf_gt`
+was built without `dtype=`, defaulting to float32 regardless of `mconf`'s own dtype (which can be
+float16/bfloat16 under autocast) and silently promoting the concatenated result. Fixed by building
+`mconf_gt` in `mconf.dtype`.
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 0e0e66936..2e985447f 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -267,15 +267,16 @@ class CoarseMatching(nn.Module):
(max(num_matches_train - num_matches_pred, self.train_pad_num_gt_min),),
device=_device,
)
- mconf_gt = torch.zeros(len(data["spv_b_ids"]), device=_device) # set conf of gt paddings to all zero
+ # set conf of gt paddings to all zero, in mconf's own dtype -- mconf can be
+ # float16/bfloat16 under autocast, and defaulting this to float32 would
+ # silently upcast the padded mconf below via torch.cat's type promotion.
+ mconf_gt = torch.zeros(len(data["spv_b_ids"]), device=_device, dtype=mconf.dtype)
b_ids, i_ids, j_ids, mconf = ( # type: ignore
torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0)
for x, y in zip(
- [b_ids, data["spv_b_ids"]],
- [i_ids, data["spv_i_ids"]],
- [j_ids, data["spv_j_ids"]],
- [mconf, mconf_gt],
+ [b_ids, i_ids, j_ids, mconf],
+ [data["spv_b_ids"], data["spv_i_ids"], data["spv_j_ids"], mconf_gt],
)
)
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 50cb5551d..f36a6398d 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -21,6 +21,7 @@ import pytest
import torch
from kornia.feature import LoFTR
+from kornia.feature.loftr.utils.coarse_matching import CoarseMatching
from kornia.geometry import resize
from testing.base import BaseTester
@@ -107,3 +108,86 @@ class TestLoFTR(BaseTester):
out_jit = model_jit(sample)
for k, v in out.items():
self.assert_close(v, out_jit[k])
+
+
+class TestCoarseMatching(BaseTester):
+ """CoarseMatching.get_coarse_match's training-mode gt-padding branch
+ (self.training=True) previously crashed unconditionally: zip() was
+ called with 4 separate 2-element lists instead of 2 separate
+ 4-element lists, so `for x, y in zip(...)` tried to unpack each
+ resulting 4-tuple into 2 variables and raised
+ `ValueError: too many values to unpack (expected 2)` on every call.
+ No existing test exercised this training-mode path at all.
+
+ The grid is deliberately asymmetric (L=16, S=12) and the predictions
+ deterministic (no RNG) so the pairing/ordering/count the fix changes
+ -- not just "does it crash" or "is the dtype right" -- are pinned.
+ Verified against 8 single-token mutations of the production fix
+ (reverting the zip() shape, dropping the dtype fix, swapping the gt
+ id lists, swapping the concat order, swapping which side is padding,
+ flipping the zero-fill to ones, and disabling the branch entirely):
+ all 8 are killed by this test, where the previous dtype-only
+ assertions caught only 2 of the 8."""
+
+ CFG = {
+ "thr": 0.01,
+ "border_rm": 0,
+ "train_coarse_percent": 0.5,
+ "train_pad_num_gt_min": 2,
+ "match_type": "dual_softmax",
+ "dsmax_temperature": 0.1,
+ }
+ H0C, W0C, H1C, W1C = 4, 4, 3, 4 # L=16, S=12 -- i/j ranges are distinguishable
+ N_PRED, N_GT = 5, 20
+
+ def _data(self, device):
+ L, S = self.H0C * self.W0C, self.H1C * self.W1C
+ return {
+ "hw0_c": (self.H0C, self.W0C),
+ "hw1_c": (self.H1C, self.W1C),
+ "hw0_i": (self.H0C * 8, self.W0C * 8),
+ "hw1_i": (self.H1C * 8, self.W1C * 8),
+ "spv_b_ids": torch.zeros(self.N_GT, dtype=torch.long, device=device),
+ "spv_i_ids": torch.full((self.N_GT,), L - 1, dtype=torch.long, device=device),
+ "spv_j_ids": torch.full((self.N_GT,), S - 1, dtype=torch.long, device=device),
+ }
+
+ def _conf(self, device, dtype):
+ L, S = self.H0C * self.W0C, self.H1C * self.W1C
+ conf = torch.zeros(1, L, S, device=device, dtype=dtype)
+ for k in range(self.N_PRED): # exactly N_PRED mutual-NN matches, no RNG
+ conf[0, k, k] = 0.5 + 0.01 * k
+ return conf
+
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
+ def test_training_gt_padding(self, device, dtype):
+ cm = CoarseMatching(self.CFG).to(device)
+ cm.train()
+ out = cm.get_coarse_match(self._conf(device, dtype), self._data(device))
+
+ L, S = self.H0C * self.W0C, self.H1C * self.W1C
+ n_train = int(max(L, S) * self.CFG["train_coarse_percent"]) # 8
+ n_pad = max(n_train - self.N_PRED, self.CFG["train_pad_num_gt_min"]) # 3
+ assert out["b_ids"].shape[0] == self.N_PRED + n_pad
+ assert (out["b_ids"] == 0).all()
+ assert (out["i_ids"] < L).all() and (out["j_ids"] < S).all()
+ assert out["i_ids"][: self.N_PRED].tolist() == list(range(self.N_PRED))
+ assert out["j_ids"][: self.N_PRED].tolist() == list(range(self.N_PRED))
+ assert (out["i_ids"][self.N_PRED :] == L - 1).all()
+ assert (out["j_ids"][self.N_PRED :] == S - 1).all()
+ assert not out["gt_mask"][: self.N_PRED].any()
+ assert out["gt_mask"][self.N_PRED :].all()
+ assert out["mconf"].numel() == self.N_PRED
+ assert out["mconf"].dtype == dtype
+ assert out["mkpts0_c"].shape == (self.N_PRED, 2)
+
+ def test_eval_path_unaffected(self, device):
+ """Eval mode skips the gt-padding branch entirely -- assert that
+ directly (gt_mask all False, count == predictions only), not just
+ a dtype that would also hold if the branch silently ran."""
+ cm = CoarseMatching(self.CFG).to(device)
+ cm.eval()
+ out = cm.get_coarse_match(self._conf(device, torch.float32), self._data(device))
+ assert out["mconf"].dtype == torch.float32
+ assert out["gt_mask"].sum() == 0
+ assert out["mconf"].numel() == out["b_ids"].shape[0] == self.N_PRED