π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): keep the gftt_response gradient finite on flat patches (#5653)
εΊζ’η4787ff3133b5
diff --git a/changelog.d/5653.fixed.md b/changelog.d/5653.fixed.mdnew file mode 100644index 000000000..dc217ab78--- /dev/null+++ b/changelog.d/5653.fixed.md@@ -0,0 +1 @@+`gftt_response` returned a NaN gradient wherever the discriminant `trace**2 - 4 * det` of the structure tensor rounded to exactly 0: on every flat 9 x 9 patch of the image (zero padding, a black border, a saturated region) in every dtype, and in float16 and bfloat16 on many textured pixels too (766 float16 and 3364 bfloat16 pixels of a random `(2, 3, 33, 29)` image, out of 5742). The gradient is now finite, and 0 on flat patches. The discriminant is now computed as `(dx2 - dy2)**2 + 4 * dxy**2`, so the response values also move at rounding level, toward the exact smaller eigenvalue: in float32 the largest deviation from it falls from up to 2e-5 to below 2e-7 of the largest response.diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex e9f33328b..85e0b8d14 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -187,13 +187,15 @@ def gftt_response(dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))- det_m: torch.Tensor = dx2 * dy2 - dxy * dxytrace_m: torch.Tensor = dx2 + dy2- e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))- e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))+ # trace^2 - 4 det as a sum of squares: it is never negative, and the sqrt below gets a zero gradient instead+ # of 0 / 0 = nan where the structure tensor vanishes, which is every flat 9 x 9 patch of the image.+ disc: torch.Tensor = (dx2 - dy2) ** 2 + 4.0 * dxy * dxy+ positive = disc > 0+ root: torch.Tensor = torch.where(positive, torch.where(positive, disc, torch.ones_like(disc)).sqrt(), 0.0)- scores: torch.Tensor = torch.min(e1, e2)+ scores: torch.Tensor = 0.5 * (trace_m - root) # the smaller eigenvalueif sigmas is not None:scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.pyindex ceb9acfb7..eeec94b26 100644--- a/tests/feature/test_responces_local_features.py+++ b/tests/feature/test_responces_local_features.py@@ -263,6 +263,32 @@ class TestCornerGFTT(BaseTester):img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)self.gradcheck(kornia.feature.gftt_response, (img), nondet_tol=1e-4)+ def test_flat_patch_gradient(self, device, dtype):+ # the structure tensor is exactly zero inside a flat 12 x 12 patch, where the old sqrt(abs(trace^2 - 4 det))+ # backward was 0 * inf = nan for the whole image+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)+ img[..., 8:20, 8:20] = 0.5+ img.requires_grad_(True)+ # anomaly mode also sees a nan that a ``torch.where`` masks out of the result, i.e. a sqrt evaluated at 0+ with torch.autograd.detect_anomaly():+ scores = kornia.feature.gftt_response(img)+ (grad,) = torch.autograd.grad(scores.sum(), img)+ assert torch.isfinite(scores).all()+ assert torch.isfinite(grad).all()+ self.assert_close(scores[..., 14, 14], torch.zeros_like(scores[..., 14, 14]))+ self.assert_close(grad[..., 14, 14], torch.zeros_like(grad[..., 14, 14]))++ def test_smaller_eigenvalue(self, device, dtype):+ img = torch.rand(2, 3, 24, 20, device=device, dtype=dtype)+ gradients = kornia.filters.spatial_gradient(img)+ dx, dy = gradients[:, :, 0], gradients[:, :, 1]+ dx2 = kornia.filters.gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))+ dy2 = kornia.filters.gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))+ dxy = kornia.filters.gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))+ structure = torch.stack((torch.stack((dx2, dxy), -1), torch.stack((dxy, dy2), -1)), -2)+ expected = torch.linalg.eigvalsh(structure.cpu().double())[..., 0].to(device, dtype)+ self.assert_close(kornia.feature.gftt_response(img), expected)+class TestBlobHessian(BaseTester):def test_shape(self, device):