Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): make TPS kernel finite in float16 (#4565)

Hrithik Sharmaedb0c1ba2f5e
diff --git a/changelog.d/4565.fixed.md b/changelog.d/4565.fixed.md
new file mode 100644
index 000000000..d29f15831
--- /dev/null
+++ b/changelog.d/4565.fixed.md
@@ -0,0 +1 @@
+Fix float16 NaNs in thin-plate-spline transforms by handling zero kernel distances safely.
diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.py
index 450916f89..f5be67588 100644
--- a/docs/export_support/cases_geomA.py
+++ b/docs/export_support/cases_geomA.py
@@ -265,7 +265,7 @@ CASES = [
T.warp_points_tps,
[tps_src.clone(), tps_src, tps_kernel_w, tps_affine_w],
tags=("points",),
- note="query points == kernel centers (zero distance) -> exercises the eps guard in _kernel_distance",
+ note="query points == kernel centers (zero distance) -> exercises zero-distance handling in _kernel_distance",
),
case("transform.warp_image_tps", G, T.warp_image_tps, [img, tps_src, tps_kernel_w, tps_affine_w]),
case(
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 45e552908..cf8120055 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -4903,9 +4903,9 @@
"export_detail": "",
"graph_breaks": 0,
"name": "transform.warp_points_tps[at_centers]",
- "note": "query points == kernel centers (zero distance) -> exercises the eps guard in _kernel_distance",
- "onnx": "mismatch",
- "onnx_detail": "runs, but the result differs from eager: out0: NaN pattern differs (torch 0, ort 10 NaNs)",
+ "note": "query points == kernel centers (zero distance) -> exercises zero-distance handling in _kernel_distance",
+ "onnx": "ok",
+ "onnx_detail": "",
"operator": "warp_points_tps",
"package": "kornia.geometry",
"ref": "kornia.geometry.transform.warp_points_tps",
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index b8766dea0..e67aa6c97 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -42,13 +42,7 @@ class RandomThinPlateSpline(AugmentationBase2D):
additional limitations; see `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
With zero scale, the image warp is identity up to numerical precision for either ``align_corners``
- setting with float32, float64, and bfloat16 inputs.
-
- .. warning::
- Float16 has a kernel-epsilon underflow that produces non-finite weights and NaN output for either
- ``align_corners`` setting; this is tracked in `#4557 <https://github.com/kornia/kornia/issues/4557>`_.
- The solve has additional dtype limitations documented on
- :func:`~kornia.geometry.transform.get_tps_transform`.
+ setting with float16, float32, float64, and bfloat16 inputs.
Args:
scale: the non-negative scale factor to apply to the destination points.
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index df34fbaa2..4273ee35f 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -42,15 +42,19 @@ def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torc
return square_dist
-def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+def _kernel_distance(squared_distances: torch.Tensor) -> torch.Tensor:
r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, where `r` is the euclidean distance.
Since
:math: `\log(r) = 1/2 \log(r^2)`, this function takes the squared distance matrix and calculates
:math: `0.5 r^2 log(r^2)`.
"""
- # r^2 * log(r) = 1/2 * r^2 * log(r^2)
- return 0.5 * squared_distances * squared_distances.add(eps).log()
+ safe = torch.where(squared_distances > 0, squared_distances, torch.ones_like(squared_distances))
+ return torch.where(
+ squared_distances > 0,
+ 0.5 * squared_distances * safe.log(),
+ torch.zeros_like(squared_distances),
+ )
def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
@@ -68,7 +72,7 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
mapping (``points_src == points_dst``) yields kernel weights and an affine
that are mathematically zero/identity, realized only up to linear-solver
(LU) round-off β€” not bit-exact in general, and the residual size is
- dtype- and backend-dependent; float16 currently produces NaN weights
+ dtype- and backend-dependent
- neither :func:`warp_points_tps` nor :func:`warp_image_tps` calls this
function β€” the caller composes them explicitly; whichever tensor is
passed as this function's **second** positional argument is
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 318f421e9..eb113c71e 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -460,7 +460,6 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWar
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y_large[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_z[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_thin_plate_spline.py::TestWarpImage::test_identity_warp_align_corners[cpu-float16-1]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_batch_color_no_batch[cpu-float16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_batch_variable_size[cpu-float16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_circle[cpu-float16]
diff --git a/tests/augmentation/test_conventions_geometric_dense.py b/tests/augmentation/test_conventions_geometric_dense.py
index c4a5b42cc..cfd8524e7 100644
--- a/tests/augmentation/test_conventions_geometric_dense.py
+++ b/tests/augmentation/test_conventions_geometric_dense.py
@@ -34,11 +34,6 @@ class TestDenseGeometricConventions(BaseTester):
if not supports_bilinear_2d_grid_sample(device, dtype):
pytest.skip("2D bilinear grid sampling is unavailable for this device/dtype")
- @staticmethod
- def require_tps(dtype):
- if dtype == torch.float16:
- pytest.skip("#4557: the TPS kernel epsilon underflows in float16, producing non-finite weights")
-
@pytest.mark.parametrize("align_corners", [False, True])
def test_convention_elastic_zero_displacement(self, device, dtype, align_corners):
image = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7) / 35
@@ -108,15 +103,12 @@ class TestDenseGeometricConventions(BaseTester):
@pytest.mark.parametrize("align_corners", [False, True])
def test_convention_thin_plate_spline_identity_grid_3928(self, device, dtype, align_corners):
- self.require_tps(dtype)
image = torch.ones(1, 1, 3, 3, device=device, dtype=dtype)
aug = K.RandomThinPlateSpline(scale=0, align_corners=align_corners, p=1)
self.assert_close(aug(image), image)
@pytest.mark.parametrize("kind", ["elastic", "fisheye", "tps"])
def test_convention_dense_shape_and_matrix_interface(self, device, dtype, kind):
- if kind == "tps":
- self.require_tps(dtype)
aug = {
"elastic": lambda: K.RandomElasticTransform(kernel_size=(3, 3), p=1),
"fisheye": lambda: K.RandomFisheye(
@@ -125,6 +117,9 @@ class TestDenseGeometricConventions(BaseTester):
"tps": lambda: K.RandomThinPlateSpline(scale=0, p=1),
}[kind]()
image = torch.ones(2, 1, 5, 7, device=device, dtype=dtype)
- assert aug(image).shape == image.shape
+ output = aug(image)
+ assert output.shape == image.shape
+ if kind == "tps":
+ assert torch.isfinite(output).all()
assert not hasattr(aug, "transform_matrix")
assert not hasattr(aug, "inverse")
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index 8177df3a6..01b162d42 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -15,10 +15,13 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
import kornia
+from kornia.geometry.transform.thin_plate_spline import _kernel_distance
from testing.base import BaseTester, supports_2d_border_padding
@@ -66,6 +69,19 @@ class TestTransformParameters(BaseTester):
src = torch.rand(batch_size, 5)
assert kornia.geometry.transform.get_tps_transform(src, src)
+ def test_kernel_distance_values(self, device, dtype):
+ d2 = torch.tensor([0.0, 1.0, math.e**2], device=device, dtype=dtype)
+ expected = torch.tensor([0.0, 0.0, math.e**2], device=device, dtype=dtype)
+ self.assert_close(_kernel_distance(d2), expected)
+
+ @pytest.mark.parametrize("grad_dtype", [torch.float32, torch.float64])
+ def test_kernel_distance_zero_gradient(self, device, grad_dtype):
+ if device.type == "mps" and grad_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ squared_distances = torch.tensor([0.0, 1.0], device=device, dtype=grad_dtype, requires_grad=True)
+ grad = torch.autograd.grad(_kernel_distance(squared_distances).sum(), squared_distances)[0]
+ assert torch.isfinite(grad).all()
+
@pytest.mark.parametrize("batch_size", [1, 3])
@pytest.mark.parametrize("requires_grad", [True, False])
def test_gradcheck(self, batch_size, device, dtype, requires_grad):