Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Compute half precision endpoint errors before rounding (#5781)

AhmetHakanBezire247bf92cf8c
diff --git a/changelog.d/5781.fixed.md b/changelog.d/5781.fixed.md
new file mode 100644
index 000000000..6ea34f3e6
--- /dev/null
+++ b/changelog.d/5781.fixed.md
@@ -0,0 +1 @@
+`aepe` and `AEPE` compute float16 and bfloat16 flows in float32 and return the result in the input dtype. In float16 the squared distance overflowed, so an endpoint error of 256 px or more came back as `inf`, turned the mean into `inf`, and had a zero gradient.
diff --git a/kornia/metrics/endpoint_error.py b/kornia/metrics/endpoint_error.py
index f05ba47dd..6740c3ab6 100644
--- a/kornia/metrics/endpoint_error.py
+++ b/kornia/metrics/endpoint_error.py
@@ -42,6 +42,7 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
``'none'`` returns the :math:`(*)` map. There is no valid mask: mask sparse ground truth on the ``'none'``
map. An unknown ``reduction`` raises ``NotImplementedError``.
- :func:`~kornia.metrics.aepe` and :func:`~kornia.metrics.average_endpoint_error` are the same function.
+ - Float16 and bfloat16 inputs are computed in float32 and the result is returned in their promoted dtype.
Args:
input: the input flow map with shape :math:`(*, 2)`.
@@ -71,6 +72,11 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
input.shape == target.shape, f"input and target shapes must be the same. Got: {input.shape} and {target.shape}"
)
+ output_dtype = torch.promote_types(input.dtype, target.dtype)
+ # The distance can be representable even when its squared components overflow or underflow in half precision.
+ if output_dtype in (torch.float16, torch.bfloat16):
+ input, target = input.float(), target.float()
+
epe: Tensor = ((input[..., 0] - target[..., 0]) ** 2 + (input[..., 1] - target[..., 1]) ** 2).sqrt()
if reduction == "mean":
@@ -82,7 +88,7 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
else:
raise NotImplementedError("Invalid reduction option.")
- return epe
+ return epe.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else epe
class AEPE(nn.Module):
diff --git a/tests/metrics/test_aepe.py b/tests/metrics/test_aepe.py
index 85f2884f1..c0545fe1c 100644
--- a/tests/metrics/test_aepe.py
+++ b/tests/metrics/test_aepe.py
@@ -118,3 +118,28 @@ class TestConventionsAepe(BaseTester):
# average_endpoint_error is aepe itself, and AEPE(reduction) calls it
assert kornia.metrics.average_endpoint_error is kornia.metrics.aepe
self.assert_close(kornia.metrics.AEPE("sum")(flow, target), torch.tensor(7.0, device=device, dtype=dtype))
+
+
+class TestAepeHalfPrecision(BaseTester):
+ @pytest.mark.parametrize("scale", [1e-4, 100.0])
+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
+ def test_representable_distance_and_gradient(self, device, dtype, scale, reduction):
+ flow = torch.tensor([[3 * scale, 4 * scale], [0.0, 5 * scale]], device=device, dtype=dtype, requires_grad=True)
+ target = torch.zeros_like(flow, requires_grad=True)
+ reference = flow.detach().cpu().double()
+ norm = torch.hypot(reference[:, 0], reference[:, 1])
+ expected = norm if reduction == "none" else norm.mean() if reduction == "mean" else norm.sum()
+ actual = kornia.metrics.aepe(flow, target, reduction=reduction)
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, expected.to(flow))
+ self.assert_close(kornia.metrics.AEPE(reduction)(flow, target), actual)
+ grad_flow, grad_target = torch.autograd.grad(actual.sum(), (flow, target))
+ expected_grad = reference / norm[:, None]
+ if reduction == "mean":
+ expected_grad = expected_grad / norm.numel()
+ expected_grad = expected_grad.to(flow)
+ assert torch.isfinite(grad_flow).all()
+ assert torch.isfinite(grad_target).all()
+ self.assert_close(grad_flow, expected_grad)
+ self.assert_close(grad_target, -expected_grad)