π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): make the quad-interp Hessian determinant floor relative (#5087)
Mohammad Hijjawidf086b3163ec
diff --git a/changelog.d/5087.breaking.md b/changelog.d/5087.breaking.mdnew file mode 100644index 000000000..67801910e--- /dev/null+++ b/changelog.d/5087.breaking.md@@ -0,0 +1 @@+`conv_quad_interp3d`, `iterative_quad_interp3d` and their modules now treat a fit as singular when `|det H| <= 1e-7 * m**3`, with `m` the largest magnitude among the Hessian entries. Previously the floor was an absolute `|det H| <= 1e-7`, and the determinant is cubic in the response amplitude, so well-conditioned maxima of a low-amplitude response kept their integer coordinates: `ScaleSpaceDetector` on a `[0, 1]` image returned almost every keypoint unrefined. Those keypoints are now refined to sub-pixel positions, which changes detector output. (#5065)diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.pyindex 390d87743..f521d8307 100644--- a/kornia/feature/sift/scale_space.py+++ b/kornia/feature/sift/scale_space.py@@ -299,7 +299,9 @@ class _SIFTScaleSpaceDetector(nn.Module):)determinants = m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20)det = determinants[:, 0:1]- solved = det.abs() > 1e-7+ # The relative floor of _solve_cramer_sym3x3, which the eager path calls; columns 0-5 hold the Hessian.+ scale = system[:, :6].abs().amax(1, keepdim=True)+ solved = det.abs() > 1e-7 * scale * scale * scaleshifts = determinants[:, 1:] / torch.where(solved, det, torch.ones_like(det))alive = alive & solved[:, 0] & torch.isfinite(shifts).all(1)move = alive & (shifts.abs() >= 0.5).any(1)diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 8f334db3c..74efc5038 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -689,7 +689,8 @@ def _solve_cramer_sym3x3_cuda(a, b, c, d, e, f, g, h, i = system.index_select(1, indices).reshape(-1, 4, 9).unbind(2)determinants = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)det = determinants[:, 0:1]- solved = det.abs() > eps+ scale = system[:, :6].abs().amax(1, keepdim=True)+ solved = det.abs() > eps * scale * scale * scaleshifts = determinants[:, 1:] / torch.where(solved, det, torch.ones_like(det))sx, sy, ss = shifts.unbind(1)return sx, sy, ss, solved[:, 0]@@ -736,12 +737,14 @@ def _solve_cramer_sym3x3(r0: right-hand side component along x.r1: right-hand side component along y.r2: right-hand side component along s.- eps: determinant magnitude below which the system is treated as singular.+ eps: relative determinant floor. The system is treated as singular when+ ``|det| <= eps * m**3``, where ``m`` is the largest magnitude among the+ Hessian entries, so the test does not depend on the response amplitude.Near-singular systems can produce numerically unstable (huge) shifts.Returns:(sx, sy, ss, solved) where ``solved`` is a bool mask for well-conditioned- systems (``|det| > eps``). Outputs for unsolved entries are numerically+ systems (``|det| > eps * m**3``). Outputs for unsolved entries are numericallymeaningless and should be discarded by the caller."""# The packed solve indexes one batch dimension, while the scalar code below@@ -752,7 +755,7 @@ def _solve_cramer_sym3x3(# float16 cannot carry this solve. The determinant is a product of three# second derivatives, so for a [0, 1] response it lands around 1e-4 and- # below β still above ``eps``, so ``solved`` admits it. The forward divides+ # far below, and the relative floor admits it. The forward divides# by it once and stays finite, but the backward of ``num / safe_det``# scales by ``1 / safe_det**2``, and that square is not representable in# float16 (finfo.tiny is 6.1e-5), so the gradient becomes inf and reduces@@ -767,7 +770,10 @@ def _solve_cramer_sym3x3(cf01 = dxy * dss - dys * dxs # cofactor M01cf02 = dxy * dys - dyy * dxs # cofactor M02det = dxx * cf00 - dxy * cf01 + dxs * cf02- solved = det.abs() > eps+ # The determinant is cubic in the response amplitude, so the floor is relative to the largest Hessian entry:+ # an absolute floor rejected every well-conditioned fit of a low-amplitude response.+ scale = torch.stack((dxx.abs(), dyy.abs(), dss.abs(), dxy.abs(), dxs.abs(), dys.abs())).amax(0)+ solved = det.abs() > eps * scale * scale * scale# Avoid division by zero for singular/near-singular cases; outputs are discarded via solved.safe_det = torch.where(solved, det, torch.ones_like(det))sx = (r0 * cf00 - dxy * (r1 * dss - dys * r2) + dxs * (r1 * dys - dyy * r2)) / safe_det@@ -816,14 +822,11 @@ def conv_quad_interp3d(indices of the input: only refined maxima move off their own grid index. At a refined maximum ``y_max`` isthe quadratic fit's value at the refined point; non-maxima keep their input value.- A maximum is not refined, and keeps its grid coordinates, when the determinant of its fit's Hessian is at- most ``1e-7`` in magnitude, when a move would reach the border voxels, when its centre leaves the voxels- precomputed for ``dilation_radius``, when the final shift exceeds ``1.5`` voxels on any axis, or when it- still requires an integer-centre move on the last iteration. A volume with a side shorter than 3 is returned- unrefined.- - Known defect: the ``1e-7`` determinant floor is absolute while the determinant is cubic in the response- amplitude, so low-amplitude maxima stay unrefined, among them most keypoints of the default- :class:`~kornia.feature.ScaleSpaceDetector` on a ``[0, 1]`` image- (`#5065 <https://github.com/kornia/kornia/issues/5065>`_).+ most ``1e-7 * m**3`` in magnitude, where ``m`` is the largest magnitude among the Hessian entries (so the+ test does not depend on the response amplitude), when a move would reach the border voxels, when its centre+ leaves the voxels precomputed for ``dilation_radius``, when the final shift exceeds ``1.5`` voxels on any+ axis, or when it still requires an integer-centre move on the last iteration. A volume with a side shorter+ than 3 is returned unrefined.Args:input: response pyramid with shape :math:`(B, C, D, H, W)`.diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 125a93af8..5a1cbc551 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -94,7 +94,9 @@ class TestScaleSpaceDetector(BaseTester):pytest.skip("ConvQuadInterp3d has no candidate cap")torch.manual_seed(17)img = torch.rand(batch, 1, 96, 99, device=device, dtype=dtype, requires_grad=True)- mask = torch.rand(batch, 1, 96, 99, device=device, dtype=dtype)+ mask = torch.rand(batch, 1, 96, 99, device=device, dtype=dtype).clamp_min(0.05)+ # Zero only the top band: a float16 draw also rounds a few scattered weights to exactly 0, and the refined+ # centre of a candidate beside one fails the mask re-check, which left this fixture without a detection.mask[..., :8, :] = 0def detector(subpix):diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pyindex 52709a1c8..2dc10cdd0 100644--- a/tests/feature/test_sift_scale_space.py+++ b/tests/feature/test_sift_scale_space.py@@ -428,7 +428,7 @@ def _quadratic_dog(class TestSIFTScaleSpaceDetector(BaseTester):- @pytest.mark.parametrize("case", ["random", "quadratic", "singular", "outside"])+ @pytest.mark.parametrize("case", ["random", "quadratic", "singular", "outside", "ramp", "flat_scale", "saddle"])def test_cuda_refinement_matches_reference(self, device, dtype, case):if device.type not in ("cpu", "cuda"):pytest.skip("CUDA implementation; CPU checks its arithmetic against the reference")@@ -448,6 +448,18 @@ class TestSIFTScaleSpaceDetector(BaseTester):# fixed-trip CUDA iterations must not introduce NaNs in backward.dog.fill_(float("nan"))s = index * 0 - 1+ elif case in ("ramp", "flat_scale", "saddle"):+ # A steep x ramp under a shallow cap: normalised by the gradient, the Hessian is small, and its tiny scale+ # curvature puts the determinant on the other side of the relative floor of #5065 from a variant rule.+ # "ramp" is solved where an absolute floor, or a floor on m**2, rejects it; "flat_scale" and "saddle" are+ # rejected where a floor that leaves the diagonal or the (largest) off-diagonal term out of m solves them.+ # float64 resolves these determinants; in float32 the scale curvature rounds away on both paths alike.+ yy, xx = torch.meshgrid(torch.arange(32, dtype=dtype), torch.arange(32, dtype=dtype), indexing="ij")+ scale_curvature = {"ramp": 1e-5, "flat_scale": 1e-8, "saddle": 5e-8}[case]+ dog = _quadratic_dog(torch.device("cpu"), dtype, 1e-3, (scale_curvature, 1.0, 1.0)) + xx+ if case == "saddle":+ dog = dog + 8e-3 * (xx - 11.2) * (yy - 10.3)+ s, y, x = index * 0 + 2, index % 3 + 9, index % 4 + 10reference_image = dog.clone().requires_grad_()image = dog.to(device).requires_grad_()detector = _SIFTScaleSpaceDetector(24, nn.Identity())diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 271434ae5..6f70ac283 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -928,6 +928,32 @@ class TestConvQuadInterp3d(BaseTester):expected_val = torch.zeros((), device=device, dtype=dtype) if converged else sample[0, 0, 2, 2, 5]self.assert_close(val[0, 0, 2, 2, 5], expected_val, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize("op", ["conv_quad_interp3d", "iterative_quad_interp3d"])+ @pytest.mark.parametrize("amplitude", [1.0, 1e-2, 1e-3])+ def test_determinant_floor_is_relative_5065(self, device, dtype, op, amplitude):+ # A maximum with a neighbour of half its value to the right: the fit is the same parabola at every amplitude+ # and peaks at x = 5 + 1/6. The determinant of its Hessian is cubic in the amplitude (-6e-9 at 1e-3), and the+ # absolute floor |det H| > 1e-7 rejected the fit as singular below an amplitude of about 2.6e-3, leaving x = 5.+ fn = getattr(kornia.geometry.subpix, op)+ volume = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=dtype)+ volume[0, 0, 1, 2, 5] = amplitude+ volume[0, 0, 1, 2, 6] = 0.5 * amplitude+ coords, vals = fn(volume)+ expected = torch.tensor([1.0, 5 + 1 / 6, 2.0], device=device, dtype=dtype)+ self.assert_close(coords[0, 0, :, 1, 2, 5], expected, atol=1e-4, rtol=1e-4)+ # the fit's value at its peak, 1 + 1/48 of the maximum, scales with the amplitude as well+ self.assert_close(vals[0, 0, 1, 2, 5], torch.tensor(49 / 48 * amplitude, device=device, dtype=dtype))++ # A fit that is singular at any amplitude is still rejected: the same x profile repeated at every depth+ # has no curvature along the scale axis, so the candidate keeps its grid coordinates.+ flat = torch.zeros_like(volume)+ flat[0, 0, :, 2, 5] = amplitude+ flat[0, 0, :, 2, 6] = 0.5 * amplitude+ mask = torch.zeros_like(flat, dtype=torch.bool)+ mask[0, 0, 1, 2, 5] = True+ coords, _ = fn(flat, precomputed_nms_mask=mask)+ self.assert_close(coords[0, 0, :, 1, 2, 5], torch.tensor([1.0, 5.0, 2.0], device=device, dtype=dtype))+class TestAdaptiveQuadInterp3d(BaseTester):def test_smoke(self, device, dtype):@@ -1063,6 +1089,34 @@ class TestPackedQuadraticFit(BaseTester):assert got.shape == (2, 5)self.assert_close(got.reshape(-1), want, atol=0, rtol=0)+ @pytest.mark.parametrize("solver", ["_solve_cramer_sym3x3", "_solve_cramer_sym3x3_cuda"])+ @pytest.mark.parametrize("amplitude", [1e-3, 1.0, 1e3])+ def test_cramer_relative_floor_5065(self, device, dtype, solver, amplitude):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Packed quadratic fit is dispatched only for float32/float64")+ # Rows are (dxx, dyy, dss, dxy, dxs, dys). A fit is singular when |det| <= 1e-7 * m**3, with m the largest+ # Hessian magnitude, so each row keeps its status at every amplitude. The first row sits a decade above that+ # floor and the second a decade below. Each later singular row has its unique largest entry in a different+ # slot and would be solved if that slot were left out of m; the last row is all zero.+ e, t = -1e-4, -1e-8+ hessians = [+ (-1.0, -1.0, -1e-6, 0.0, 0.0, 0.0),+ (-1.0, -1.0, -1e-8, 0.0, 0.0, 0.0),+ (-1.0, e, e, 0.0, 0.0, 0.0),+ (e, -1.0, e, 0.0, 0.0, 0.0),+ (e, e, -1.0, 0.0, 0.0, 0.0),+ (e, e, t, 1.0, 0.0, 0.0),+ (e, t, e, 0.0, 1.0, 0.0),+ (t, e, e, 0.0, 0.0, 1.0),+ (0.0, 0.0, 0.0, 0.0, 0.0, 0.0),+ ]+ # The right-hand side is larger than the Hessian and must not enter m.+ system = torch.tensor([h + (10.0, 10.0, 10.0) for h in hessians], device=device, dtype=dtype).T * amplitude+ solved = getattr(subpix, solver)(*system)[3]+ assert solved.tolist() == [True] + [False] * 8+@pytest.mark.parametrize("count", [0, 19])def test_patch_derivatives(self, device, dtype, count):from kornia.geometry.subpix import spatial_soft_argmax as subpix@@ -1357,11 +1411,11 @@ class TestConventionsQuadInterp3d(BaseTester):self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(7.4, device=device, dtype=dtype))@pytest.mark.parametrize("fn", _FUNCTIONS, ids=["conv", "iterative"])- def test_wart_quad_interp3d_absolute_determinant_floor_5065(self, device, dtype, fn):- # #5065: the absolute Hessian determinant floor refines this peak at unit amplitude but rejects it at 1e-3.- for amplitude, expected_x in ((1.0, 5 + 1 / 6), (1e-3, 5.0)):+ def test_convention_quad_interp3d_relative_determinant_floor_5065(self, device, dtype, fn):+ # #5065: the Hessian determinant floor is relative, so this peak is refined at unit amplitude and at 1e-3.+ for amplitude in (1.0, 1e-3):volume = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=dtype)volume[0, 0, 1, 2, 5] = amplitudevolume[0, 0, 1, 2, 6] = 0.5 * amplitudecoords, _ = fn(volume)- self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(expected_x, device=device, dtype=dtype))+ self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(5 + 1 / 6, device=device, dtype=dtype))