π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): scale the sub-pixel Cramer solve so flat float32 images keep a finite gradient (#6113)
Dmytro Mishkin6c3aa89cde59
diff --git a/changelog.d/5087.breaking.md b/changelog.d/5087.breaking.mdindex 67801910e..7368b17f5 100644--- a/changelog.d/5087.breaking.md+++ b/changelog.d/5087.breaking.md@@ -1 +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)+`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. The solve is scaled so that its largest Hessian entry is about 1, so a flat image region, whose Hessian entries are rounding noise, keeps a finite `float32` image gradient. (#5065)diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 8870f80d8..bf9352df0 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -17,6 +17,7 @@from __future__ import annotations+import mathimport warningsfrom typing import Optional@@ -674,6 +675,52 @@ class SpatialSoftArgmax2d(nn.Module):return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)+def _scale_to_unit_hessian(+ dxx: torch.Tensor,+ dyy: torch.Tensor,+ dss: torch.Tensor,+ dxy: torch.Tensor,+ dxs: torch.Tensor,+ dys: torch.Tensor,+ r0: torch.Tensor,+ r1: torch.Tensor,+ r2: torch.Tensor,+) -> tuple[torch.Tensor, ...]:+ """Scale a Cramer system by the power of two that brings its largest Hessian magnitude to about 1.++ On a flat float32 image the Hessian entries are rounding noise of about 1e-15. Their determinants reach float32's+ smallest subnormal, and the relative floor ``eps * m**3`` underflows to 0, so tiny determinants count as solved,+ their shifts are inaccurate, and the backward of ``num / det``, ``(num / det) / det``, is inf: NaN behind the+ callers' masks, which then spreads to every pixel. Scaled, the largest Hessian magnitude is about 1. Cramer's shifts+ do not change when H and the right-hand side are scaled together, and a power of two scales every product exactly,+ so wherever the unscaled solve neither underflows nor overflows, the shifts and the ``solved`` mask stay the same,+ bit for bit. A factor above 1 is capped so that it takes the right-hand side no higher than ``2**64``: a tiny+ Hessian next to a large finite right-hand side would otherwise scale it to inf. The cap never scales a system+ down, so a large right-hand side alone leaves the system as it is.+ """++ def _exponent(*entries: torch.Tensor) -> torch.Tensor:+ magnitude = torch.stack([t.abs() for t in entries]).amax(0).detach()+ usable = torch.isfinite(magnitude) & (magnitude > 0)+ exponent = torch.floor(torch.log2(torch.where(usable, magnitude, torch.ones_like(magnitude))))+ # An unusable magnitude imposes no cap on the right-hand side.+ return torch.where(usable, exponent, torch.full_like(exponent, -math.inf))++ # The largest exponent whose power of two and its reciprocal are both normal numbers: 126 in float32.+ limit = -math.log2(torch.finfo(dxx.dtype).tiny)+ hessian = _exponent(dxx, dyy, dss, dxy, dxs, dys)+ hessian = torch.where(torch.isfinite(hessian), hessian, torch.zeros_like(hessian))+ # 2**-exponent scales max |H| to [1, 2). An upward factor stops at 2**(63 - exponent_r), which keeps max |r| below+ # 2**64; the cap is at most 0, so it never scales down a system the Hessian alone would leave as it is.+ exponent = torch.maximum(hessian, (_exponent(r0, r1, r2) - 63).clamp(max=0)).clamp(-limit, limit)+ # 2**-exponent. In eager mode, exp2 of a negative integer is one ulp below its power of two on MPS, and exp2 of a+ # non-negative integer and its reciprocal are exact: build the factor from those. (MPS inductor's exp2 is inexact+ # from 2**13; the refiners do not compile on MPS today.)+ power = torch.exp2(exponent.abs())+ factor = torch.where(exponent > 0, power.reciprocal(), power)+ return tuple(t * factor for t in (dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2))++def _solve_cramer_sym3x3_cuda(dxx: torch.Tensor,dyy: torch.Tensor,@@ -695,7 +742,7 @@ def _solve_cramer_sym3x3_cuda(All inputs must be 1-D tensors of the same length: the packed layout indexesa single batch dimension and silently reshapes anything wider."""- system = torch.stack((dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2), 1)+ system = torch.stack(_scale_to_unit_hessian(dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2), 1)# Row-major H followed by H with successive columns replaced by the RHS.indices = torch.tensor((@@ -713,6 +760,8 @@ def _solve_cramer_sym3x3_cuda(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))+ # An unsolved shift is 0, as in the scalar solve.+ shifts = torch.where(solved, shifts, torch.zeros_like(shifts))sx, sy, ss = shifts.unbind(1)return sx, sy, ss, solved[:, 0]@@ -765,8 +814,7 @@ def _solve_cramer_sym3x3(Returns:(sx, sy, ss, solved) where ``solved`` is a bool mask for well-conditioned- systems (``|det| > eps * m**3``). Outputs for unsolved entries are numerically- meaningless and should be discarded by the caller.+ systems (``|det| > eps * m**3``). The shifts of an unsolved system are 0."""# The packed solve indexes one batch dimension, while the scalar code below# is rank-agnostic. Dispatch only where the two agree, so a wider caller@@ -774,18 +822,16 @@ def _solve_cramer_sym3x3(if dxx.is_cuda and dxx.ndim == 1 and dxx.dtype in (torch.float32, torch.float64):return _solve_cramer_sym3x3_cuda(dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2, eps)- # 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- # 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- # to NaN. bfloat16 keeps float32's exponent range and is unaffected.+ # float16 is solved in float32 and the shifts are rounded once: the relative+ # floor of the scaled system, about 1e-7, is below float16's smallest normal+ # number (finfo.tiny is 6.1e-5). bfloat16 keeps float32's exponent range and+ # is solved in its own dtype, as before.in_dtype = dxx.dtypeif in_dtype == torch.float16:dxx, dyy, dss = dxx.float(), dyy.float(), dss.float()dxy, dxs, dys = dxy.float(), dxs.float(), dys.float()r0, r1, r2 = r0.float(), r1.float(), r2.float()+ dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2 = _scale_to_unit_hessian(dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2)cf00 = dyy * dss - dys * dys # cofactor M00cf01 = dxy * dss - dys * dxs # cofactor M01@@ -800,6 +846,9 @@ def _solve_cramer_sym3x3(sx = (r0 * cf00 - dxy * (r1 * dss - dys * r2) + dxs * (r1 * dys - dyy * r2)) / safe_detsy = (dxx * (r1 * dss - dys * r2) - r0 * cf01 + dxs * (dxy * r2 - r1 * dxs)) / safe_detss = (dxx * (dyy * r2 - r1 * dys) - dxy * (dxy * r2 - r1 * dxs) + r0 * cf02) / safe_det+ # An unsolved shift is 0, not the numerator: on the scaled system that can exceed float16's range, and the callers+ # multiply it by the gradient before masking, where an inf would make the backward NaN.+ sx, sy, ss = (torch.where(solved, t, torch.zeros_like(t)) for t in (sx, sy, ss))if in_dtype == torch.float16:sx, sy, ss = sx.to(in_dtype), sy.to(in_dtype), ss.to(in_dtype)diff --git a/testing/base.py b/testing/base.pyindex 084efc264..ffbc92227 100644--- a/testing/base.py+++ b/testing/base.py@@ -19,8 +19,9 @@ from __future__ import annotationsimport mathimport sys+from contextlib import contextmanagerfrom functools import cache-from typing import Any, Callable, Optional, Sequence, Union+from typing import Any, Callable, Iterator, Optional, Sequence, Unionimport pytestimport torch@@ -39,6 +40,27 @@ DYNAMIC_EXPORT_UNAVAILABLE_REASON = ()+@contextmanager+def deterministic_algorithms_on_cuda(device: torch.device) -> Iterator[None]:+ """Run the block with deterministic algorithms on CUDA, and restore the caller's mode afterwards.++ Some CUDA backward kernels accumulate with atomics, so two backward passes of one graph can round differently.+ Deterministic algorithms fix the accumulation order (CPU kernels already have one). ``warn_only`` keeps an op+ without a deterministic CUDA kernel running, as it does by default; it only warns. A strict mode the caller+ already set is kept.+ """+ if device.type != "cuda":+ yield+ return+ enabled = torch.are_deterministic_algorithms_enabled()+ warn_only = torch.is_deterministic_algorithms_warn_only_enabled()+ torch.use_deterministic_algorithms(True, warn_only=warn_only if enabled else True)+ try:+ yield+ finally:+ torch.use_deterministic_algorithms(enabled, warn_only=warn_only)++def dynamo_is_available() -> bool:"""Return whether this Torch/Python pair can run Dynamo-backed capture."""return not (diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 2516a5704..223766846 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -15,9 +15,6 @@# limitations under the License.#-from contextlib import contextmanager-from typing import Iterator-import pytestimport torchfrom torch.utils._python_dispatch import TorchDispatchMode@@ -38,6 +35,7 @@ from kornia.geometry.transform import ScalePyramidfrom testing.base import (DYNAMO_UNAVAILABLE_REASON,BaseTester,+ deterministic_algorithms_on_cuda,dynamo_is_available,supports_conv2d,supports_reflect_padding,@@ -47,24 +45,6 @@ from testing.base import (from testing.default_device import default_device-@contextmanager-def _deterministic_algorithms_on_cuda(device: torch.device) -> Iterator[None]:- # Some CUDA backward kernels accumulate with atomics, so two backward passes of one graph can round differently.- # Deterministic algorithms fix the accumulation order (CPU kernels already have one). `warn_only` keeps an op- # without a deterministic CUDA kernel running, as it does by default; it only warns. A strict mode the caller- # already set is kept.- if device.type != "cuda":- yield- return- enabled = torch.are_deterministic_algorithms_enabled()- warn_only = torch.is_deterministic_algorithms_warn_only_enabled()- torch.use_deterministic_algorithms(True, warn_only=warn_only if enabled else True)- try:- yield- finally:- torch.use_deterministic_algorithms(enabled, warn_only=warn_only)--def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:# torch 2.5.1 has no float16 CPU reflection_pad2d or replication_pad2d; these pins blur (reflect) and take# gradients (replicate).@@ -202,7 +182,7 @@ class TestScaleSpaceDetector(BaseTester):# tolerance -- so about a third of the runs failed, the capped variant too, where both detectors take the# same separate path. Deterministic algorithms give both passes one accumulation order: the two detectors# then agree bit for bit on CUDA, as they do on CPU, and the default tolerance stands.- with _deterministic_algorithms_on_cuda(device):+ with deterministic_algorithms_on_cuda(device):actual = detector(joint)(img, mask)expected = detector(separate)(img, mask)assert actual[0].ne(0).any()@@ -286,6 +266,27 @@ class TestScaleSpaceDetector(BaseTester):# An image without candidates has no gradient to give.assert torch.count_nonzero(img.grad) == 0+ @pytest.mark.parametrize("subpix_type", [IterativeQuadInterp3d, ConvQuadInterp3d])+ @pytest.mark.parametrize("image", ["flat", "ramp", "near-flat"])+ def test_a_flat_image_has_a_finite_gradient(self, device, dtype, subpix_type, image):+ # On a flat float32 image the Hessian entries of the sub-pixel fit are rounding noise of about 1e-15. Their+ # determinants reach float32's smallest subnormal, under a relative floor that underflowed to 0, and the+ # backward of the Cramer solve divided by them twice: the inf times a later mask's zero gradient made every+ # pixel's gradient NaN.+ _skip_without_half_padding(device, dtype)+ generator = torch.Generator().manual_seed(0)+ if image == "flat":+ img = torch.full((1, 1, 64, 80), 0.5)+ elif image == "ramp":+ img = torch.linspace(0, 1, 80).expand(1, 1, 64, 80).clone()+ else:+ img = 0.5 + 1e-6 * torch.rand(1, 1, 64, 80, generator=generator)+ img = img.to(device, dtype).requires_grad_()+ det = ScaleSpaceDetector(10, subpix_module=subpix_type()).to(device, dtype)+ lafs, resps = det(img)+ (lafs.sum() + resps.sum()).backward()+ assert bool(torch.isfinite(img.grad).all())+@pytest.mark.parametrize("img_tail, mask_shape, error",[diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 17f0d912e..7187e41b6 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -31,7 +31,7 @@ from kornia.geometry.subpix.spatial_soft_argmax import (conv_quad_interp3d,)-from testing.base import BaseTester+from testing.base import BaseTester, deterministic_algorithms_on_cudaclass TestStridedSubpixel(BaseTester):@@ -1309,6 +1309,96 @@ class TestPackedQuadraticFit(BaseTester):solved = getattr(subpix, solver)(*system)[3]assert solved.tolist() == [True] + [False] * 8+ @pytest.mark.parametrize("solver", ["_solve_cramer_sym3x3", "_solve_cramer_sym3x3_cuda"])+ def test_cramer_backward_of_a_tiny_system_is_finite(self, device, dtype, solver):+ 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")+ if solver == "_solve_cramer_sym3x3_cuda" and device.type not in ("cpu", "cuda"):+ pytest.skip("the packed solve runs on CUDA only; CPU checks it bit for bit against the scalar one")+ # On a flat float32 image the Hessian entries of a BlobHessian response are rounding noise of about 1e-15.+ # Their determinants reach float32's smallest subnormal, 1.4e-45, and the relative floor 1e-7 * m**3+ # underflows to 0: the shifts were inaccurate, and the backward of num / det, (num / det) / det, was inf. The+ # first rows sit just above the floor; the rest are well conditioned. The solve scales the system by a power+ # of two first, so the same system scaled by 2**-50 gives the same shifts and mask bit for bit and gradients+ # 2**50 times larger.+ generator = torch.Generator().manual_seed(0)+ system = torch.randn(9, 64, generator=generator)+ system[:3] -= 4.0+ system[:, :4] = 0.0+ system[0:2, :4] = -1.0+ system[2, :4] = torch.tensor([-2e-7, -4e-7, -1e-6, -1e-5])+ system[6:, :4] = 1.0+ system = system.to(device, dtype).requires_grad_()+ tiny = (system.detach() * 2.0**-50).requires_grad_()+ expected = getattr(subpix, solver)(*system)+ actual = getattr(subpix, solver)(*tiny)+ assert bool(expected[3].all())+ for got, want in zip(actual, expected):+ self.assert_close(got, want, atol=0, rtol=0)+ weights = torch.linspace(0.1, 0.9, 64, device=device, dtype=dtype)+ # On CUDA the packed solve's repeated-index `index_select` backward accumulates with atomics in no fixed+ # order, so two backward passes differ in the last bits; deterministic algorithms give both one order.+ with deterministic_algorithms_on_cuda(device):+ grad = torch.autograd.grad(sum((v * weights).sum() for v in actual[:3]), tiny)[0]+ grad_ref = torch.autograd.grad(sum((v * weights).sum() for v in expected[:3]), system)[0]+ assert bool(torch.isfinite(grad).all())+ self.assert_close(grad, grad_ref * 2.0**50, atol=0, rtol=0)++ @pytest.mark.parametrize("solver", ["_solve_cramer_sym3x3", "_solve_cramer_sym3x3_cuda"])+ @pytest.mark.parametrize("power", [64, 100, 120])+ def test_cramer_large_right_hand_side_is_not_rescaled(self, device, dtype, solver, power):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if dtype != torch.float32:+ pytest.skip("float32 only: there a scaled-down determinant underflows")+ if solver == "_solve_cramer_sym3x3_cuda" and device.type not in ("cpu", "cuda"):+ pytest.skip("the packed solve runs on CUDA only; CPU checks it bit for bit against the scalar one")+ # A well-conditioned Hessian of order 1 needs no scaling. A large right-hand side must not scale it down:+ # 2**-57 would take det = 1e-6 to 2**-171 * 1e-6, which underflows to 0 and rejects a solvable system.+ system = torch.tensor([1.0, 1.0, 1e-6, 0.0, 0.0, 0.0, 2.0**power, 0.0, 0.0], device=device, dtype=dtype)+ sx, sy, ss, solved = getattr(subpix, solver)(*system[:, None])+ assert bool(solved.all())+ self.assert_close(sx, system[6:7], atol=0, rtol=0)+ assert torch.stack([sy, ss]).eq(0).all()++ @pytest.mark.parametrize("solver", ["_solve_cramer_sym3x3", "_solve_cramer_sym3x3_cuda"])+ @pytest.mark.parametrize(+ ("system", "solve_dtype"),+ [+ # A tiny Hessian next to a large finite right-hand side: scaling H to about 1 would take r0 = 2**70 to+ # 2**130, inf in float32, so the factor is capped by the right-hand side.+ ((0.0, 2.0**-60, 2.0**-60, 0.0, 0.0, 0.0, 2.0**70, 0.0, 0.0), torch.float32),+ # Singular in float16: on the scaled system the numerator is -2**19, beyond float16's range, where the+ # unscaled one rounded to 0, so an unsolved shift is returned as 0.+ ((0.0, 2.0**-19, 2.0**-19, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0), torch.float16),+ # A subnormal Hessian: its exponent, -133, is clamped to -126, or the factor 2**133 would be inf in float32+ # and the backward of the scaling NaN.+ ((1e-40, 1e-40, 0.0, 0.0, 0.0, 0.0, 1e-40, 0.0, 0.0), torch.float32),+ ],+ ids=["large-rhs-float32", "singular-float16", "subnormal-hessian-float32"],+ )+ def test_cramer_unsolved_system_is_zero_with_a_finite_backward(self, device, system, solve_dtype, solver):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if solver == "_solve_cramer_sym3x3_cuda" and solve_dtype != torch.float32:+ pytest.skip("the packed solve is dispatched only for float32/float64")+ if solver == "_solve_cramer_sym3x3_cuda" and device.type not in ("cpu", "cuda"):+ pytest.skip("the packed solve runs on CUDA only; CPU checks it bit for bit against the scalar one")+ if solve_dtype == torch.float16 and device.type == "mps":+ pytest.skip("checked on CPU and CUDA")+ entries = [torch.tensor([v], device=device, dtype=solve_dtype, requires_grad=True) for v in system]+ sx, sy, ss, solved = getattr(subpix, solver)(*entries)+ assert not bool(solved.any())+ assert torch.stack([sx, sy, ss]).eq(0).all()+ # The callers form gradient * shift for every row before they keep the solved ones (``gds_u`` in+ # conv_quad_interp3d): a non-finite unsolved shift would turn the zero gradient of the dropped row into NaN.+ gradient = torch.ones(1, device=device, dtype=solve_dtype, requires_grad=True)+ kept = torch.where(solved, gradient * sx, torch.zeros_like(sx))+ grads = torch.autograd.grad(kept.sum() + sy.sum() + ss.sum(), [*entries, gradient])+ assert all(bool(torch.isfinite(g).all()) for g in grads)+@pytest.mark.parametrize("count", [0, 19])def test_patch_derivatives(self, device, dtype, count):from kornia.geometry.subpix import spatial_soft_argmax as subpix