Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): finite float16 gradients in LoFTR FineMatching std on torch < 2.14 (#4614)

Mohansree Vijayakumare9f3207844b7
diff --git a/changelog.d/4614.fixed.md b/changelog.d/4614.fixed.md
new file mode 100644
index 000000000..5c083a083
--- /dev/null
+++ b/changelog.d/4614.fixed.md
@@ -0,0 +1 @@
+`LoFTR` fine matching returns finite gradients through `expec_f` in `float16` on torch older than 2.14. The `1e-10` floor under `sqrt` underflows to zero in `float16`, so a peaked heatmap -- what a confident match produces, not a degenerate corner -- sent `sqrt'(0) = inf` back into the features; since `std` is summed into the loss, one such match is enough to make the whole gradient `nan`.
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index c30a3b782..047681402 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -80,7 +80,13 @@ class FineMatching(nn.Module):
# compute std over <x, y>
var = torch.sum(grid_normalized**2 * heatmap.view(-1, WW, 1), dim=1) - coords_normalized**2 # [M, 2]
- std = torch.sum(torch.sqrt(torch.clamp(var, min=1e-10)), -1) # [M] clamp needed for numerical stability
+ # A clamp floor under sqrt bounds the value, not the gradient: 1e-10 is 0 in float16, and torch < 2.14 passes
+ # clamp's gradient through at the bound, so sqrt'(0) = inf reached the features as nan (#4229). Differentiate
+ # sqrt only above the floor; at or below it the value is still sqrt(floor), with zero gradient.
+ floor = torch.full_like(var, 1e-10)
+ above = var > floor
+ safe_var = torch.where(above, var, torch.ones_like(var))
+ std = torch.sum(torch.where(above, safe_var.sqrt(), floor.sqrt()), -1) # [M]
# for fine-level supervision
data.update({"expec_f": torch.cat([coords_normalized, std.unsqueeze(1)], -1)})
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index f36a6398d..1fb6508dc 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -22,6 +22,7 @@ import torch
from kornia.feature import LoFTR
from kornia.feature.loftr.utils.coarse_matching import CoarseMatching
+from kornia.feature.loftr.utils.fine_matching import FineMatching
from kornia.geometry import resize
from testing.base import BaseTester
@@ -191,3 +192,52 @@ class TestCoarseMatching(BaseTester):
assert out["mconf"].dtype == torch.float32
assert out["gt_mask"].sum() == 0
assert out["mconf"].numel() == out["b_ids"].shape[0] == self.N_PRED
+
+
+class TestFineMatching(BaseTester):
+ @staticmethod
+ def _run(device, dtype, peaked):
+ """Run FineMatching on a peaked or a uniform heatmap; return `std` and the input it flows back to."""
+ M, W, C = 4, 5, 8
+ feat_f0 = torch.zeros(M, W * W, C, device=device, dtype=dtype)
+ feat_f1 = torch.zeros(M, W * W, C, device=device, dtype=dtype)
+ if peaked:
+ # One dominant cell, so the softmax is a spike and the variance of both coordinates is zero.
+ feat_f0[:, W * W // 2, 0] = 30.0
+ feat_f1[:, W * W // 2, 0] = 30.0
+ feat_f1.requires_grad_(True)
+ data = {
+ "hw0_i": (40, 40),
+ "hw0_f": (20, 20),
+ "mkpts0_c": torch.zeros(M, 2, device=device, dtype=dtype),
+ "mkpts1_c": torch.zeros(M, 2, device=device, dtype=dtype),
+ "mconf": torch.ones(M, device=device, dtype=dtype),
+ "b_ids": torch.zeros(M, dtype=torch.long, device=device),
+ }
+ FineMatching()(feat_f0, feat_f1, data)
+ return data["expec_f"][:, 2], feat_f1
+
+ def test_regression_std_gradient_is_finite_on_a_peaked_heatmap_4229(self, device, dtype):
+ # A heatmap peaked on one cell has zero variance. `std` was sqrt(clamp(var, min=1e-10)): in float16 the
+ # floor is 0, and torch < 2.14 passes clamp's gradient through at the bound, so sqrt'(0) = inf reached
+ # the features as nan. torch 2.14 zeroes clamp's gradient at the bound, so on 2.14 this passes on the
+ # old code too; the torch 2.5.1 / 2.9.1 legs are the ones that discriminate.
+ std, feat_f1 = self._run(device, dtype, peaked=True)
+ std.sum().backward()
+ assert bool(torch.isfinite(feat_f1.grad).all()), feat_f1.grad
+ # The value is unchanged, and it is `2 * sqrt(floor)`, not `sqrt(floor)`: `std` sums over the two
+ # coordinate axes, so both floored terms land in it. Asserted exactly -- the sum of two identical
+ # terms is their double in every dtype -- because the default tolerance is wider than the quantity
+ # being pinned, and would accept `std == 0`, a dropped `sqrt` and a `1e-12` floor alike.
+ self.assert_close(std, torch.full_like(std, 1e-10).sqrt() * 2, rtol=0.0, atol=0.0)
+
+ def test_std_is_the_real_deviation_above_the_floor(self, device, dtype):
+ # The floor branch is only half the behaviour: nothing else in the repo reads `expec_f` or `std` at
+ # all -- the pretrained tests compare keypoints, which come from `coords_normalized` -- so without
+ # this, forcing the floor branch to be taken always, which corrupts `std` for every real heatmap,
+ # passes the whole file. A uniform heatmap over the normalized grid `linspace(-1, 1, 5)` has
+ # `var = mean(g**2) = 0.5` on each axis, so `std` is `2 * sqrt(0.5)` rather than the floor.
+ std, feat_f1 = self._run(device, dtype, peaked=False)
+ self.assert_close(std, torch.full_like(std, 0.5).sqrt() * 2)
+ std.sum().backward()
+ assert bool(torch.isfinite(feat_f1.grad).all()), feat_f1.grad