Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): interp computes half-precision results in float32; no overflow for integer or half coordinates (#6059)

Dmytro Mishkin85fe10dc2e59
diff --git a/changelog.d/5978.added.md b/changelog.d/5978.added.md
index e99ec191e..462b88250 100644
--- a/changelog.d/5978.added.md
+++ b/changelog.d/5978.added.md
@@ -1 +1 @@
-`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5967).
+`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defect links its issue (#5956).
diff --git a/changelog.d/6059.fixed.md b/changelog.d/6059.fixed.md
new file mode 100644
index 000000000..cfe22705c
--- /dev/null
+++ b/changelog.d/6059.fixed.md
@@ -0,0 +1 @@
+`kornia.contrib.interp` computes a `float16` or `bfloat16` result in `float32` and rounds once, so every half-precision result can differ from before (it was up to about five ulps of the larger end value off in an ordinary segment). Integer coordinates, and half-precision coordinates, with a difference above 65504 no longer overflow the weight: `interp(x=100000, xp=[0, 200000], fp=float16 [0, 2])` gave NaN, `x = 60000` and `x = 1000` gave a silent 0 where the values are 0.6 and 0.01, and `float16` coordinates `[-60000, 60000]` with `fp = [0, 2]` gave NaN or 0 where the values are in `[0, 2]`. An integer `x` or `xp` mixed with half-precision coordinates is no longer rounded onto the half-precision grid: `interp(x=3001, xp=float16 [3000, 3010], fp=float16 [-40000, 40000])` gave -40000 where the value is -32000. A segment whose value difference overflows the half dtype is within about half an ulp of its larger end value, and its knots are exact.
diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.py
index cb49a3e37..09e69185d 100644
--- a/kornia/contrib/histogram_matching.py
+++ b/kornia/contrib/histogram_matching.py
@@ -101,9 +101,13 @@ def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
- ``xp`` and ``fp`` are 1-D; ``x`` can have any shape, which the output keeps. ``xp`` must be increasing, which
is not checked. The output dtype is the promoted dtype of ``x``, ``xp`` and ``fp``, or the default float
dtype when all three are integer.
- - Known defects: with integer ``x`` and ``xp`` and a ``float16`` ``fp``, any coordinate difference above 65504
- overflows, and the result can be NaN, inf or silently wrong, such as 0; in ``float16`` a segment whose ``fp``
- difference overflows can be about one ulp off (`#5967 <https://github.com/kornia/kornia/issues/5967>`_).
+ - A ``float16`` or ``bfloat16`` result is computed in ``float32`` and cast to the output dtype once, so
+ coordinate differences above 65504 do not overflow the weight and a segment whose ``fp`` difference overflows
+ the output dtype stays finite. Inside a segment the result is within about half an ulp of the segment's
+ larger end value, and the knots are exact. ``float32`` and ``float64`` results are computed in their own
+ dtype. An integer ``x`` or ``xp`` mixed with floating coordinates is converted to the dtype the result is
+ computed in, so in ``float32`` it is exact only up to :math:`2^{24}`: larger integer knots can merge and
+ larger integer queries are rounded.
Args:
x: the :math:`x`-coordinates at which to evaluate the interpolated
@@ -130,17 +134,22 @@ def _interp_real(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.T
# All-integer inputs interpolate in the default float dtype (read from a factory: TorchScript has no
# torch.get_default_dtype).
dtype = torch.empty(0, device=fp.device).dtype
+ # Half-precision values (float16, bfloat16) are interpolated in float32 and cast to the output dtype once: their
+ # coordinate differences and weights overflow or lose bits in half precision (65504 in float16). float32 and
+ # float64 values are interpolated in their own dtype.
# Integer coordinates are searched, compared and subtracted in int64 (as float32 they round past 2**24, and uint8
# differences wrap); only the two differences that form each weight are converted. Floating coordinates are
- # converted to the value dtype, which never narrows them.
- coord_dtype = dtype if float_coords else torch.int64
- x, xp, fp = x.to(coord_dtype), xp.to(coord_dtype), fp.to(dtype)
+ # converted to the working dtype, which never narrows them. An integer coordinate mixed with floating ones is
+ # converted too, so it is exact only up to 2**24 in float32.
+ cdtype = torch.promote_types(dtype, torch.float32)
+ coord_dtype = cdtype if float_coords else torch.int64
+ x, xp, fp = x.to(coord_dtype), xp.to(coord_dtype), fp.to(cdtype)
i = torch.clip(torch.searchsorted(xp, x, right=True), 1, len(xp) - 1)
x0, x1, f0, f1 = xp[i - 1], xp[i], fp[i - 1], fp[i]
dx = x1 - x0
zero_width = dx == 0
- dx = torch.where(zero_width, torch.ones_like(dx), dx).to(dtype)
- w = (x - x0).to(dtype) / dx
+ dx = torch.where(zero_width, torch.ones_like(dx), dx).to(cdtype)
+ w = (x - x0).to(cdtype) / dx
d = f1 - f0
# f1 - f0 can overflow while both ends are finite. The value is then the weighted sum of the two ends, with each
# weight divided by dx on its own, so that d/dx is the slope wherever the slope is representable. The other
@@ -166,9 +175,9 @@ def _interp_real(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.T
torch.where(x == x1, torch.where(torch.isnan(b), f1, b), out),
)
# The weighted sum is exact at the knots too: its weights are 1 and 0 there.
- out = torch.where(overflow, f0 * ((x1 - x).to(dtype) / dx) + f1 * w, out)
+ out = torch.where(overflow, f0 * ((x1 - x).to(cdtype) / dx) + f1 * w, out)
# A zero-width (repeated) segment is reached only at a clipped end: below a repeated first knot the value is
# fp[0], at or above a repeated last knot fp[-1].
out = torch.where(zero_width, torch.where(x < x0, f0, f1), out)
# A NaN query is NaN, also on a flat or zero-width segment (np.interp).
- return torch.where(torch.isnan(x), torch.full_like(out, float("nan")), out)
+ return torch.where(torch.isnan(x), torch.full_like(out, float("nan")), out).to(dtype)
diff --git a/tests/contrib/test_hist_match.py b/tests/contrib/test_hist_match.py
index 2265521bd..9414e0e8f 100644
--- a/tests/contrib/test_hist_match.py
+++ b/tests/contrib/test_hist_match.py
@@ -392,14 +392,128 @@ class TestHistMatch(BaseTester):
expected = torch.tensor([[6.0, 5.0], [-2.0, -6.0]], device=device, dtype=dtype)
self.assert_close(kornia.contrib.interp(x, xp, fp), expected)
- def test_wart_interp_integer_x_with_half_fp_overflows_5967(self, device):
- # The weight is formed in float16 from integer differences above 65504. x = 100000 gives NaN where the right
- # value is 1.0; x = 60000 overflows only the segment width and gives a silent 0.0 where the right value is 0.6.
- x = torch.tensor([100000, 60000], device=device)
+ @pytest.mark.parametrize(
+ ("dtype_", "xp", "big"),
+ [
+ (torch.float16, [0.0, 4.0], 40000.0),
+ (torch.float16, [-2.71875, 0.0012], 40000.0), # a spacing float16 holds only approximately
+ (torch.bfloat16, [0.0, 3.0], 3e38),
+ ],
+ )
+ def test_half_overflow_segment_matches_float64(self, dtype_, xp, big, device):
+ # f1 - f0 = 2 * big overflows the half dtype while both ends are finite. Over 481 points of the segment and 10 %
+ # beyond it, the extrapolated ones included, every value equals the float64 result rounded to the dtype.
+ # Reference: fp0 + (fp1 - fp0) * (x - xp0) / (xp1 - xp0) evaluated in float64 on the half inputs. (Not every
+ # point of every segment is: float32 intermediates round a few near-ties the other way, by one ulp.)
+ xp = torch.tensor(xp, dtype=dtype_)
+ fp = torch.tensor([-big, big], dtype=dtype_)
+ span = float(xp[1] - xp[0])
+ x = torch.linspace(float(xp[0]) - 0.1 * span, float(xp[1]) + 0.1 * span, 481, dtype=torch.float64).to(dtype_)
+ xp64, fp64 = xp.double(), fp.double()
+ expected = (fp64[0] + (fp64[1] - fp64[0]) * (x.double() - xp64[0]) / (xp64[1] - xp64[0])).to(dtype_)
+ out = kornia.contrib.interp(x.to(device), xp.to(device), fp.to(device))
+ assert out.dtype == dtype_
+ assert torch.equal(out.cpu(), expected)
+
+ def test_half_overflow_segment_is_exact_at_its_knots_for_inexact_spacing(self, device):
+ # float16 rounds the spacing 4.349121 to 4.347656, which used to make the knot weights sum to 1.0003 and the
+ # first knot -inf.
+ xp = torch.tensor([-4.71875, -0.36962890625], device=device, dtype=torch.float16)
+ fp = torch.tensor([-65504.0, 42240.0], device=device, dtype=torch.float16)
+ assert torch.equal(kornia.contrib.interp(xp, xp, fp), fp)
+
+ def test_half_overflow_segments_are_exact_at_their_knots(self, device):
+ g = torch.Generator().manual_seed(0)
+ for _ in range(300):
+ xp = torch.sort(torch.randn(2, generator=g) * 3).values.to(torch.float16)
+ sign = 1.0 if torch.rand(1, generator=g) < 0.5 else -1.0
+ fp = (sign * torch.tensor([-1.0, 1.0]) * (33000 + 32000 * torch.rand(2, generator=g))).to(torch.float16)
+ if xp[0] == xp[1]:
+ continue
+ assert torch.equal(kornia.contrib.interp(xp.to(device), xp.to(device), fp.to(device)), fp.to(device))
+
+ def test_half_coordinates_with_a_difference_above_65504(self, device):
+ # 60000 - (-60000) overflows float16; the weights are formed in float32.
+ x = torch.tensor([0.0, -30000.0, 30000.0], device=device, dtype=torch.float16)
+ xp = torch.tensor([-60000.0, 60000.0], device=device, dtype=torch.float16)
+ fp = torch.tensor([0.0, 2.0], device=device, dtype=torch.float16)
+ # fp0 + (fp1 - fp0) * (x - xp0) / (xp1 - xp0): (1, 0.5, 1.5), exact in float16 for these x
+ expected = torch.tensor([1.0, 0.5, 1.5], dtype=torch.float16)
+ assert torch.equal(kornia.contrib.interp(x, xp, fp).cpu(), expected)
+
+ @pytest.mark.parametrize(
+ ("x", "x_dtype", "xp", "xp_dtype", "fp_dtype", "expected"),
+ [
+ # 3001 is not a float16 number (it rounds to 3000): an integer x rounded onto the float16 grid gave fp[0]
+ (3001, torch.int64, [3000, 3010], torch.float16, torch.float16, -32000.0),
+ # 2999 rounds to 3000 in float16: an integer xp rounded onto the float16 grid gave fp[0] at x = 3000
+ (3000, torch.float16, [2999, 3009], torch.int64, torch.float16, -32000.0),
+ # bfloat16 keeps 8 bits: 3001 and 3009 would round to 3008, merging the knots
+ (3008, torch.bfloat16, [3001, 3009], torch.int64, torch.bfloat16, 29952.0),
+ ],
+ )
+ def test_integer_coordinates_mixed_with_half_coordinates_are_not_rounded_to_half(
+ self, x, x_dtype, xp, xp_dtype, fp_dtype, expected, device
+ ):
+ # Expected: fp0 + (fp1 - fp0) * (x - xp0) / (xp1 - xp0) in float64 on the fp_dtype ends, rounded to fp_dtype:
+ # -40000 + 80000 / 10 in float16, and -39936 + 79872 * 7 / 8 in bfloat16 (where 40000 is 39936).
+ fp = torch.tensor([-40000.0, 40000.0], device=device, dtype=fp_dtype)
+ out = kornia.contrib.interp(
+ torch.tensor([x], device=device, dtype=x_dtype), torch.tensor(xp, device=device, dtype=xp_dtype), fp
+ )
+ assert out.dtype == fp_dtype
+ assert out.cpu().tolist() == [expected]
+
+ @pytest.mark.parametrize("dtype_", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize(
+ ("x", "xp", "expected"),
+ [
+ # Each expected value is fp0 + (fp1 - fp0) * (x - xp0) / (xp1 - xp0) in float64 with fp = [0, 2], rounded to
+ # the dtype.
+ (100000, [0, 200000], 1.0), # x - xp0 = 100000 used to overflow float16 to inf: NaN
+ (60000, [0, 200000], 0.6), # the spacing 200000 used to overflow to inf, so the weight was a silent 0
+ (1000, [0, 200000], 0.01), # the same silent 0
+ (100000, [0, 10], 20000.0), # x - xp0 = 100000 used to overflow to inf
+ ],
+ )
+ def test_integer_coordinates_with_half_fp(self, x, xp, expected, dtype_, device):
+ out = kornia.contrib.interp(
+ torch.tensor([x], device=device),
+ torch.tensor(xp, device=device),
+ torch.tensor([0.0, 2.0], device=device, dtype=dtype_),
+ )
+ assert out.dtype == dtype_
+ assert torch.equal(out.cpu(), torch.tensor([expected], dtype=torch.float64).to(dtype_))
+
+ def test_integer_coordinates_with_half_fp_are_interpolated_in_float32(self, device):
+ # The weight and the interpolation are computed in float32 and rounded once: xp = [0, 10, 25], fp = [0, 3, -7]
+ # at x = -4 is -1.2 -> float16 -1.2001953125 (the weight rounded to float16 first gave -1.19921875).
+ out = kornia.contrib.interp(
+ torch.tensor([-4], device=device),
+ torch.tensor([0, 10, 25], device=device),
+ torch.tensor([0.0, 3.0, -7.0], device=device, dtype=torch.float16),
+ )
+ assert out.cpu().tolist() == [-1.2001953125]
+
+ @pytest.mark.parametrize(("dtype_", "big"), [(torch.float16, 40000.0), (torch.bfloat16, 3e38)])
+ def test_integer_coordinates_with_half_fp_far_from_zero(self, dtype_, big, device):
+ # The offsets are subtracted in int64: as float32 the 2**40 offset swallows them and every value is -big. The
+ # bfloat16 segment also overflows the dtype, so it goes through the overflow branch.
+ x = torch.tensor([2**40, 2**40 + 1, 2**40 + 3, 2**40 + 4], device=device)
+ xp = torch.tensor([2**40, 2**40 + 4], device=device)
+ fp = torch.tensor([-big, big], device=device, dtype=dtype_)
+ # halves of a half-precision number are exact
+ expected = torch.tensor([-big, -big / 2, big / 2, big], dtype=dtype_)
+ assert torch.equal(kornia.contrib.interp(x, xp, fp).cpu(), expected)
+
+ def test_interp_integer_coordinates_with_half_fp_are_exact_at_knots_and_give_the_weights_as_fp_gradient(
+ self, device
+ ):
+ x = torch.tensor([0, 100000, 200000], device=device)
xp = torch.tensor([0, 200000], device=device)
- out = kornia.contrib.interp(x, xp, torch.tensor([0.0, 2.0], device=device, dtype=torch.float16))
- assert out.dtype == torch.float16
- assert torch.isnan(out[0])
- assert out[1].item() == 0.0
- reference = kornia.contrib.interp(x, xp, torch.tensor([0.0, 2.0], device=device))
- self.assert_close(reference, torch.tensor([1.0, 0.6], device=device))
+ fp = torch.tensor([-40000.0, 40000.0], device=device, dtype=torch.float16, requires_grad=True)
+ out = kornia.contrib.interp(x, xp, fp)
+ assert out.tolist() == [-40000.0, 0.0, 40000.0]
+ out.sum().backward()
+ # weights (1, .5, 0) and (0, .5, 1) summed
+ assert fp.grad.tolist() == [1.5, 1.5]