Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: guard zero-distance gradients in _cdist (#4233)

sunny2c25e1b3b844
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1741406dd..c746a4146 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -401,6 +401,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `Z1Projection.unproject` now materialises a python `int`/`float` `depth` on the device and
in the dtype of `points`; it used to build a CPU float32 tensor, which raised `RuntimeError`
on every accelerator and widened float16/bfloat16 results to float32. (#4340)
+* `_cdist` replaces `dm.clamp(min=0.0).sqrt()` with a masked argument substitution, avoiding `NaN` gradients for
+ exact zero-distance pairs on PyTorch 2.5.1 and 2.9.1 where `clamp`'s boundary gradient passed through to `sqrt(0)`.
+ PyTorch 2.14.0 was already finite, and forward behavior and computed distances are unchanged. (#4233)
* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`
resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 60e6cb83b..824582df9 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -48,8 +48,10 @@ def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:
d1_sq = (d1**2).sum(dim=1, keepdim=True)
d2_sq = (d2**2).sum(dim=1, keepdim=True)
dm = d1_sq.repeat(1, d2.size(0)) + d2_sq.repeat(1, d1.size(0)).t() - 2.0 * d1 @ d2.t()
- dm = dm.clamp(min=0.0).sqrt()
- return dm
+ dm = dm.clamp(min=0.0)
+ mask = dm > 0.0
+ safe_dm = torch.where(mask, dm, torch.ones_like(dm))
+ return torch.where(mask, safe_dm.sqrt(), torch.zeros_like(dm))
def _get_default_fginn_params() -> Dict[str, Any]:
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index 95729912d..fd9831187 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -25,6 +25,7 @@ from kornia.feature.matching import (
DescriptorMatcher,
DescriptorMatcherWithSteerer,
GeometryAwareDescriptorMatcher,
+ _cdist,
match_adalam,
match_fginn,
match_mnn,
@@ -687,3 +688,21 @@ class TestMatchSteererLocal(BaseTester):
self.assert_close(idxs, expected_idx)
assert num_rot is None
+
+
+class TestCDist(BaseTester):
+ @pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16])
+ def test_half_precision_zero_distance_gradient(self, device, desc_dtype):
+ if not supports_matmul(device, desc_dtype):
+ pytest.skip(f"no matmul kernel for {desc_dtype} on {device.type}")
+ d1 = torch.tensor([[1.0, 2.0], [3.0, 4.0], [1.0, 2.0]], device=device, dtype=desc_dtype, requires_grad=True)
+ d2 = torch.tensor([[1.0, 2.0], [5.0, 6.0], [3.0, 4.0]], device=device, dtype=desc_dtype, requires_grad=True)
+ dists = _cdist(d1, d2)
+ assert torch.isfinite(dists).all()
+ assert dists[0, 0] == 0.0
+ assert dists[2, 0] == 0.0
+ assert dists[1, 2] == 0.0
+ loss = dists.sum()
+ loss.backward()
+ assert d1.grad is not None and torch.isfinite(d1.grad).all()
+ assert d2.grad is not None and torch.isfinite(d2.grad).all()