Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): solve the quad-interp Hessian in float32 for float16 input (#4305)

Ethan Stonercb3c36967682
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 47f8a7a5d..5404c4187 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -381,6 +381,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
constructor argument with the probe result (and so always equalled the argument, because SDPA is
present on every supported torch), was renamed to `Attention.allow_flash`. (#4287)
+* `ConvQuadInterp3d` / `conv_quad_interp3d` no longer return NaN gradients for `float16` input. The
+ Hessian determinant `_solve_cramer_sym3x3` divides by is a product of three second derivatives, so for
+ a `[0, 1]` response it lands around 1e-4 and below and still clears the `eps` gate. The forward divides
+ by it once and stays finite, but the backward scales by `1 / det**2`, which `float16` cannot represent
+ (`finfo(float16).tiny` is 6.1e-5), so the gradient overflowed and reduced to NaN over part of the
+ volume. The solve is now promoted to `float32` for `float16` input and the shifts cast back, as #4231
+ already does for the half-precision meshgrid. `bfloat16` keeps `float32`'s exponent range and was never
+ affected; `bfloat16` and `float32` outputs are unchanged. (#4305)
+
* `RandAugment`, `AutoAugment`, `TrivialAugment` and `AugMix` no longer silently upcast half-precision
batches to `float32`. `OperationBase.forward` β€” the shared gate every auto-augment op routes through β€”
moved its `batch_prob` mask to `input.device` but not `input.dtype`, and since `batch_prob` is `float32`
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index da106f2c5..884d78ab1 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -652,6 +652,19 @@ def _solve_cramer_sym3x3(
systems (``|det| > eps``). Outputs for unsolved entries are numerically
meaningless and should be discarded by the caller.
"""
+ # 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
+ # 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.
+ in_dtype = dxx.dtype
+ if 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()
+
cf00 = dyy * dss - dys * dys # cofactor M00
cf01 = dxy * dss - dys * dxs # cofactor M01
cf02 = dxy * dys - dyy * dxs # cofactor M02
@@ -662,6 +675,9 @@ def _solve_cramer_sym3x3(
sx = (r0 * cf00 - dxy * (r1 * dss - dys * r2) + dxs * (r1 * dys - dyy * r2)) / safe_det
sy = (dxx * (r1 * dss - dys * r2) - r0 * cf01 + dxs * (dxy * r2 - r1 * dxs)) / safe_det
ss = (dxx * (dyy * r2 - r1 * dys) - dxy * (dxy * r2 - r1 * dxs) + r0 * cf02) / safe_det
+
+ if in_dtype == torch.float16:
+ sx, sy, ss = sx.to(in_dtype), sy.to(in_dtype), ss.to(in_dtype)
return sx, sy, ss, solved
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 548a6557c..9667a01e8 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -134,11 +134,6 @@ class TestScaleSpaceDetector(BaseTester):
# stacks both signs into one call, unless a candidate cap keeps it on the separate path.
assert len(separate_calls) > 0 and len(separate_calls) % 2 == 0
assert len(joint_calls) == (len(separate_calls) if max_candidates is not None else len(separate_calls) // 2)
- if dtype is torch.float16:
- # ConvQuadInterp3d's float16 backward is NaN over part of the image on CPU (#4257), on
- # `main` as well as here and on both paths, and `assert_close` treats matching NaNs as a
- # mismatch. The gradient half of this pin runs in the other dtypes.
- return
actual_grad = torch.autograd.grad(sum(x.sum() for x in actual), img, retain_graph=True)[0]
expected_grad = torch.autograd.grad(sum(x.sum() for x in expected), img)[0]
self.assert_close(actual_grad, expected_grad)
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index ce39a62ce..095e3844f 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -661,6 +661,18 @@ class TestConvQuadInterp3d(BaseTester):
self.assert_close(op(sample)[0], op_opt(sample)[0])
self.assert_close(op(sample)[1], op_opt(sample)[1])
+ def test_float16_backward_is_finite(self, device):
+ # The Hessian determinant is a product of three second derivatives, so for a
+ # [0, 1] response it lands around 1e-4 and below. The forward divides by it
+ # once and stays finite, but the backward scales by 1 / det**2, which float16
+ # cannot represent, so the gradient used to be NaN over part of the volume.
+ # Pinned in float16 specifically: bfloat16 keeps float32's exponent range.
+ torch.manual_seed(0)
+ sample = torch.rand(1, 1, 5, 40, 40, device=device, dtype=torch.float16, requires_grad=True)
+ coords, vals = kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0.0)(sample)
+ grad = torch.autograd.grad(coords.sum() + vals.sum(), sample)[0]
+ assert torch.isfinite(grad).all()
+
def test_peak_at_center(self, device, dtype):
# A clear peak at scale=1, h=2, w=2 should return coords close to (1, 2, 2).
sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)