Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): exact patch recombination and knot-exact histogram matching (#5960)

Dmytro Mishkin2ad86f17bf47
diff --git a/changelog.d/5960.breaking.md b/changelog.d/5960.breaking.md
new file mode 100644
index 000000000..76e7f1488
--- /dev/null
+++ b/changelog.d/5960.breaking.md
@@ -0,0 +1 @@
+`histogram_matching` with an empty template now raises a `ValueError` ("histogram_matching needs a non-empty template."); it used to raise an `IndexError` from inside the quantile computation. Passing `eps=` to `combine_tensor_patches` inside `torch.compile(fullgraph=True)` compiled before; `eps` now emits a `DeprecationWarning`, which makes that call fail with `Unsupported` under the default TorchDynamo configuration, so drop `eps` from the call.
diff --git a/changelog.d/5960.fixed.md b/changelog.d/5960.fixed.md
new file mode 100644
index 000000000..e8ac941de
--- /dev/null
+++ b/changelog.d/5960.fixed.md
@@ -0,0 +1,16 @@
+`combine_tensor_patches` and `extract_tensor_patches` now recombine and extract patches exactly:
+
+- An all-zero padding or unpadding tuple such as `(0, 0)` or `(0, 0, 0, 0)` no longer switches off `allow_auto_padding` / `allow_auto_unpadding`: a 5 x 7 image with 2 x 2 windows gave 6 patches and dropped the last row and column, and now gives the same 12 patches as `padding=0`.
+- `combine_tensor_patches` divides each covered pixel by its exact overlap count instead of `count + eps`, so a `float64` value of `1000.0` is no longer returned as `999.99999`. Pixels no patch covers are `0`, where `eps=0` gave `nan` at them and a negative `eps` gave `inf` at singly covered pixels.
+- `combine_tensor_patches` recombines integer patches in `int64` without overflow, so `16777217` is no longer returned as `16777216` and `2**63 - 2` no longer as `2**63 - 1`: the overlap mean is exact for every integer value and truncates toward zero. On MPS this needs torch 2.9 or newer: older torch keeps the float32 sum, exact up to 2**24. Complex patches are folded as complex instead of losing their imaginary part.
+- `combine_tensor_patches` sums `float16` and `bfloat16` patches in `float32`: 289 overlapping values up to 255 overflowed to `inf` in `float16` and were off by 64 in `bfloat16`.
+- The `eps` argument of `combine_tensor_patches` is deprecated and has no effect; a value other than the default used to change every recombined pixel. Passing it emits a `DeprecationWarning`.
+
+`histogram_matching` and `interp` now return exact values:
+
+- `interp` returns `fp` exactly at a knot, and `np.interp`'s `5.0` instead of `6.0` left of a repeated first knot (`interp([-1, 0, 0.5], [0, 0, 1], [5, 6, 7])`).
+- Matching an image to itself is the identity (132 of 5328 `float32` and 178 of 5328 `float64` pixels used to change), `[3, 1, 2]` matched onto `[10, 20, 30]` gives `[30, 10, 20]` instead of `[29.999998, 10, 20]` (which became `29` as `uint8`), and a `float32` result no longer leaves the template's range by one ulp.
+- An empty source returns an empty tensor of the same shape instead of raising `IndexError`.
+- `interp` keeps non-finite `fp` values as `np.interp` does: `interp([0.5, 1, 1.5, 2], [0, 1, 2], [3, 4, inf])` gives `[3.5, 4, inf, inf]`, where it used to give `[3.5, nan, inf, inf]`.
+- `interp` returns `nan` for a `nan` query on a repeated last knot, as `np.interp` does: `interp([nan], [0, 1, 1], [5, 6, 7])` gave `7.0`.
+- `interp` subtracts integer coordinates in `int64`: `uint8` `x = [0, 3]` with `xp = [1, 2]` and `fp = [10, 20]` gives `[0, 30]` instead of the wrapped `[5120, 2590]`.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index ea72b26ac..6ccf9c905 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -981,7 +981,7 @@ A(
K.contrib.combine_tensor_patches,
[_patches_o],
{"original_size": (32, 48), "window_size": (8, 12), "stride": (4, 6), "unpadding": (2, 3)},
- note="overlapping windows: divides by ones-fold count (eps=1e-8)",
+ note="overlapping windows: divides by the exact ones-fold overlap count",
)
)
_patches_a = K.contrib.extract_tensor_patches(_x, window_size=10, stride=7, allow_auto_padding=True)
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 101647374..69d7a6801 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import warnings
from math import ceil
from typing import Optional, Tuple, Union, cast
from warnings import warn
@@ -24,6 +25,8 @@ import torch.nn.functional as F
from torch import nn
from torch.nn.modules.utils import _pair
+from kornia.core._compat import torch_version_lt
+
FullPadType = Tuple[int, int, int, int]
TuplePadType = Union[Tuple[int, int], FullPadType]
PadType = Union[int, TuplePadType]
@@ -266,7 +269,6 @@ class CombineTensorPatches(nn.Module):
unpadding: remove the padding added to both side of the input.
allow_auto_unpadding: whether to allow automatic unpadding of the input
if the window and stride do not fit into the original_size.
- eps: small value used to prevent division by zero.
Shape:
- Input: :math:`(B, N, C, H_{out}, W_{out})`
@@ -346,7 +348,7 @@ def combine_tensor_patches(
stride: Union[int, Tuple[int, int]],
allow_auto_unpadding: bool = False,
unpadding: PadType = 0,
- eps: float = 1e-8,
+ eps: Optional[float] = None,
) -> torch.Tensor:
r"""Restore input from patches.
@@ -360,7 +362,8 @@ def combine_tensor_patches(
unpadding: remove the padding added to both side of the input.
allow_auto_unpadding: whether to allow automatic unpadding of the input
if the window and stride do not fit into the original_size.
- eps: small value used to prevent division by zero.
+ eps: deprecated, has no effect. Each covered pixel is divided by its exact overlap count and a pixel no patch
+ covers is 0.
Return:
The combined patches in an image torch.Tensor with shape :math:`(B, C, H, W)`.
@@ -391,7 +394,8 @@ def combine_tensor_patches(
# if padding is specified, we leave it up to the user to ensure it fits
# otherwise we check here if it will fit and offer to calculate padding
- if not unpadding and not _check_patch_fit(original_size, window_size, stride):
+ unpadding_tuple = create_padding_tuple(unpadding, unpadding=True)
+ if not any(unpadding_tuple) and not _check_patch_fit(original_size, window_size, stride):
if not allow_auto_unpadding:
warn(
f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
@@ -403,50 +407,121 @@ def combine_tensor_patches(
stacklevel=1,
)
else:
- unpadding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
- # TODO: Can't we just do actual size minus original size to get padding?
-
- if unpadding:
- unpadding = create_padding_tuple(unpadding)
-
+ unpadding_tuple = create_padding_tuple(
+ compute_padding(original_size=original_size, window_size=window_size, stride=stride)
+ )
+ has_unpadding = any(unpadding_tuple)
+
+ if eps is not None:
+ warnings.warn(
+ "`eps` is deprecated and has no effect: each covered pixel is divided by its exact overlap count and a "
+ "pixel no patch covers is 0. It will be removed in a future release; stop passing it.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ out_dtype = patches.dtype
+ is_integer = not patches.is_floating_point() and not patches.is_complex()
+ if is_integer:
+ # Checked before the dtype/device branches so that one message holds on every path.
+ target = _patch_target_index(patches, original_size, window_size, stride, unpadding_tuple, has_unpadding)
+ # MPS before torch 2.9 raises "index_add(): Expected non int64 dtype for source." there, so integer and bool
+ # patches keep the float32 fold: exact up to 2**24, then cast back.
+ if not (patches.device.type == "mps" and torch_version_lt(2, 9, 0)):
+ return _combine_integer_patches(patches, target)
+
+ # Fold half precision in float32: float16 overflows past 65504 and bfloat16 rounds the overlap sums. Complex
+ # patches are folded as two real tensors: MPS has no complex col2im kernel.
+ half = patches.dtype in (torch.float16, torch.bfloat16)
+ work_dtype = patches.real.dtype if patches.is_complex() else patches.dtype
+ if is_integer or half:
+ work_dtype = torch.float32
ones_tensor = torch.ones(
- patches.shape[0],
- patches.shape[2],
- original_size[0],
- original_size[1],
- device=patches.device,
- dtype=patches.dtype,
+ patches.shape[0], patches.shape[2], original_size[0], original_size[1], device=patches.device, dtype=work_dtype
)
-
- if unpadding:
- ones_tensor = F.pad(ones_tensor, pad=unpadding)
+ if has_unpadding:
+ ones_tensor = F.pad(ones_tensor, list(unpadding_tuple))
restored_size = ones_tensor.shape[2:]
-
- patches = patches.permute(0, 2, 3, 4, 1)
- patches = patches.flatten(1, 3)
- int_flag = 0
- if not torch.is_floating_point(patches):
- int_flag = 1
- dtype = patches.dtype
- patches = patches.float()
- ones_tensor = ones_tensor.float()
-
- # Calculate normalization map
+ patches = patches.permute(0, 2, 3, 4, 1).flatten(1, 3)
unfold_ones = F.unfold(ones_tensor, kernel_size=window_size, stride=stride)
norm_map = F.fold(input=unfold_ones, output_size=restored_size, kernel_size=window_size, stride=stride)
- if unpadding:
- norm_map = F.pad(norm_map, [-i for i in unpadding])
+ fold_kwargs = {"output_size": restored_size, "kernel_size": window_size, "stride": stride}
+ if patches.is_complex():
+ folded = [F.fold(input=part, **fold_kwargs) for part in (patches.real, patches.imag)]
+ else:
+ folded = [F.fold(input=patches.to(work_dtype), **fold_kwargs)]
+ if has_unpadding:
+ norm_map = F.pad(norm_map, [-i for i in unpadding_tuple])
+ folded = [F.pad(part, [-i for i in unpadding_tuple]) for part in folded]
+ # A covered pixel has an integer overlap count >= 1 and is divided by it exactly. A pixel no patch covers (patches
+ # that do not fit, the warned path) has count 0 and sum 0, and stays 0. Complex parts are divided separately: a
+ # complex division by the real count rounds on some torch versions.
+ count = torch.where(norm_map == 0, torch.ones_like(norm_map), norm_map)
+ restored = torch.complex(folded[0] / count, folded[1] / count) if patches.is_complex() else folded[0] / count
+ return restored.to(out_dtype)
+
+
+def _patch_target_index(
+ patches: torch.Tensor,
+ original_size: Tuple[int, int],
+ window_size: Tuple[int, int],
+ stride: Tuple[int, int],
+ unpadding_tuple: FullPadType,
+ has_unpadding: bool,
+) -> Tuple[torch.Tensor, Tuple[int, int, int, int], Tuple[int, int]]:
+ """Return the target pixel of every patch element, the (left, right, top, bottom) crop and the padded size."""
+ N = patches.shape[1]
+ pad_l, pad_r, pad_t, pad_b = unpadding_tuple if has_unpadding else (0, 0, 0, 0) # F.pad order, as the float path
+ Hr, Wr = original_size[0] + pad_t + pad_b, original_size[1] + pad_l + pad_r
+ index = torch.arange(Hr * Wr, device=patches.device).view(1, 1, Hr, Wr)
+ index_patches = _extract_tensor_patchesnd(index, window_size, stride)
+ if (N, *patches.shape[3:]) != (index_patches.shape[1], *index_patches.shape[3:]):
+ raise RuntimeError(
+ f"Given patches of shape {tuple(patches.shape)}, expected {index_patches.shape[1]} patches of window size "
+ f"{window_size} for output_size={(Hr, Wr)} and stride={stride}."
+ )
+ return index_patches.flatten(), (pad_l, pad_r, pad_t, pad_b), (Hr, Wr)
- # Restored torch.Tensor
- saturated_restored_tensor = F.fold(input=patches, output_size=restored_size, kernel_size=window_size, stride=stride)
- if unpadding:
- saturated_restored_tensor = F.pad(saturated_restored_tensor, [-i for i in unpadding])
- # Remove satuation effect due to multiple summations
- restored_tensor = saturated_restored_tensor / (norm_map + eps)
- if int_flag:
- restored_tensor = restored_tensor.to(dtype)
- return restored_tensor
+def _combine_integer_patches(
+ patches: torch.Tensor, target: Tuple[torch.Tensor, Tuple[int, int, int, int], Tuple[int, int]]
+) -> torch.Tensor:
+ # F.fold has no integer kernel ("col2im_out_cpu" not implemented for 'Long'), and a float sum rounds above 2**24
+ # (float32) or 2**53 (float64). Scatter-add in int64 instead. The overlap mean truncates toward zero, as a float
+ # mean cast back to an integer dtype does.
+ flat_index, pads, (Hr, Wr) = target
+ B, C = patches.shape[0], patches.shape[2]
+ values = patches.to(torch.int64).permute(0, 2, 1, 3, 4).flatten(2)
+ # The int64 cast wraps uint64 values from 2**63 up to negatives. Flipping the sign bit maps [0, 2**64) onto
+ # [-2**63, 2**63) in order (v - 2**63), where the mean below is exact; the bit is flipped back on the result.
+ unsigned64 = patches.dtype == torch.uint64
+ if unsigned64:
+ values = torch.bitwise_xor(values, -(2**63))
+ zeros = torch.zeros(B, C, Hr * Wr, dtype=torch.int64, device=patches.device)
+ if patches.dtype == torch.bool:
+ # Bool patches are True wherever any covering patch is True.
+ out = zeros.index_add(-1, flat_index, values) != 0
+ else:
+ # An overlap sum of int64 values can leave int64, so each value v is split by the overlap count c of its pixel
+ # as v = q * c + r (q truncated, |r| < c). The q sum to at most max |v| in magnitude and the r to less than
+ # c**2, so the mean sum(q) + sum(r) / c is exact for every int64 input.
+ counts = torch.zeros(Hr * Wr, dtype=torch.int64, device=patches.device)
+ counts = counts.index_add_(0, flat_index, torch.ones_like(flat_index))
+ covered = counts > 0
+ counts = counts.clamp_min(1)
+ count = counts[flat_index]
+ q = torch.div(values, count, rounding_mode="trunc")
+ sum_r = zeros.index_add(-1, flat_index, values - q * count)
+ out = zeros.index_add(-1, flat_index, q) + torch.div(sum_r, counts, rounding_mode="floor")
+ if unsigned64:
+ # A uint64 mean is non-negative, so its truncation is the floor, which the shift by 2**63 preserves. A
+ # pixel no patch covers stays 0 rather than flipping to 2**63.
+ out = torch.where(covered, torch.bitwise_xor(out, -(2**63)), torch.zeros_like(out))
+ else:
+ # The floor of the mean, moved toward zero where the mean is negative and not an integer.
+ out = out + ((out < 0) & (torch.remainder(sum_r, counts) != 0)).to(torch.int64)
+ # Negative unpadding pads the result with zeros, as the float path's inverse F.pad does.
+ out = F.pad(out.view(B, C, Hr, Wr), [-p for p in pads])
+ return out.to(patches.dtype)
def _extract_tensor_patchesnd(
@@ -510,7 +585,8 @@ def extract_tensor_patches(
# if padding is specified, we leave it up to the user to ensure it fits
# otherwise we check here if it will fit and offer to calculate padding
- if not padding and not _check_patch_fit(original_size, window_size, stride):
+ padding_tuple = create_padding_tuple(padding)
+ if not any(padding_tuple) and not _check_patch_fit(original_size, window_size, stride):
if not allow_auto_padding:
warn(
f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
@@ -520,10 +596,11 @@ def extract_tensor_patches(
stacklevel=1,
)
else:
- padding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
+ padding_tuple = create_padding_tuple(
+ compute_padding(original_size=original_size, window_size=window_size, stride=stride)
+ )
- if padding:
- padding = create_padding_tuple(padding)
- input = F.pad(input, padding)
+ if any(padding_tuple):
+ input = F.pad(input, list(padding_tuple))
return _extract_tensor_patchesnd(input, window_size, stride)
diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.py
index adacd566d..4eadc6918 100644
--- a/kornia/contrib/histogram_matching.py
+++ b/kornia/contrib/histogram_matching.py
@@ -41,6 +41,12 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
"""
oldshape = source.shape
+ compute_dtype = torch.float64 if source.dtype == torch.float64 else torch.float32
+ out_dtype = source.dtype if source.is_floating_point() else compute_dtype
+ if template.numel() == 0:
+ raise ValueError("histogram_matching needs a non-empty template.")
+ if source.numel() == 0:
+ return source.to(out_dtype)
source = source.ravel()
template = template.ravel()
@@ -53,7 +59,6 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
# template images (maps pixel value --> quantile). The counts are summed in int64 and the quantiles computed
# in float32 (float64 for float64 input): a uint8 sum wraps past 255, and float16/bfloat16 sums stop being exact
# past 2048/256, which repeats quantiles and makes interp divide by zero.
- compute_dtype = torch.float64 if source.dtype == torch.float64 else torch.float32
s_quantiles = torch.cumsum(s_counts, dim=0).to(compute_dtype)
s_quantiles = s_quantiles / s_quantiles[-1]
t_quantiles = torch.cumsum(t_counts, dim=0).to(compute_dtype)
@@ -69,7 +74,6 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
interp_t_values = interp(s_quantiles, t_quantiles, t_values)
# A floating source keeps its dtype; an integer source returns float32.
- out_dtype = source.dtype if source.is_floating_point() else compute_dtype
return interp_t_values[bin_idx].reshape(oldshape).to(out_dtype)
@@ -92,13 +96,60 @@ def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
the interpolated values, same size as `x`.
"""
+ if fp.is_complex():
+ # The real and imaginary parts are interpolated separately, as np.interp does.
+ return torch.complex(_interp_real(x, xp, fp.real), _interp_real(x, xp, fp.imag))
+ return _interp_real(x, xp, fp)
+
+
+def _interp_real(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
+ # interp for a real fp. A separate function, not a recursive call from interp: TorchScript rejects recursion.
+ # Tensor.is_floating_point() rather than dtype.is_floating_point, which TorchScript does not support.
+ float_coords = x.is_floating_point() or xp.is_floating_point()
+ dtype = torch.promote_types(torch.promote_types(x.dtype, xp.dtype), fp.dtype)
+ if not (float_coords or fp.is_floating_point()):
+ # 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
+ # 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)
i = torch.clip(torch.searchsorted(xp, x, right=True), 1, len(xp) - 1)
-
- # A zero-width segment (repeated xp) is selected only at a clipped end: x >= xp[-1] when the last xp repeats, or
- # x < xp[0] when the first one does. Dividing by its width gave NaN, e.g. when float32 rounds the last cumulative
- # counts of a 2**24-pixel template to the same quantile. Divide by a safe width there and return fp[i], which at
- # the upper end is fp[-1], as np.interp gives for x >= xp[-1].
- dx = xp[i] - xp[i - 1]
+ x0, x1, f0, f1 = xp[i - 1], xp[i], fp[i - 1], fp[i]
+ dx = x1 - x0
zero_width = dx == 0
- out = (fp[i - 1] * (xp[i] - x) + fp[i] * (x - xp[i - 1])) / torch.where(zero_width, torch.ones_like(dx), dx)
- return torch.where(zero_width, fp[i], out)
+ dx = torch.where(zero_width, torch.ones_like(dx), dx).to(dtype)
+ w = (x - x0).to(dtype) / 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
+ # formulas see zeros there, so their discarded backward does not multiply a zero gradient by the infinite f1 - f0.
+ overflow = torch.isinf(d) & torch.isfinite(f0) & torch.isfinite(f1)
+ zero = torch.zeros_like(d)
+ f0s, f1s = torch.where(overflow, zero, f0), torch.where(overflow, zero, f1)
+ ds = f1s - f0s
+ # lerp is exact at w = 0 and w = 1, so a point on a knot returns fp at that knot; outside [xp[0], xp[-1]] it
+ # extrapolates the end segment.
+ out = torch.lerp(f0s, f1s, w)
+ a = f0s + w * ds
+ b = f1s - ds * (1 - w)
+ # lerp's two halves meet an infinite end as inf - inf; try each half in turn, as np.interp does
+ out = torch.where(torch.isnan(out), a, out)
+ out = torch.where(torch.isnan(out), b, out)
+ out = torch.where(torch.isnan(out) & (f0 == f1), f0, out)
+ # A point on a knot returns fp there even when the neighbouring fp is infinite (np.interp). The segment formulas
+ # keep d/dx = slope at the knot; the bare fp is used only where they are NaN.
+ out = torch.where(
+ x == x0,
+ torch.where(torch.isnan(a), f0, a),
+ 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)
+ # 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)
diff --git a/tests/contrib/test_combine_tensor_patch.py b/tests/contrib/test_combine_tensor_patch.py
index a06a13203..a8ef7ea9c 100644
--- a/tests/contrib/test_combine_tensor_patch.py
+++ b/tests/contrib/test_combine_tensor_patch.py
@@ -15,10 +15,13 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
import kornia
+from kornia.core._compat import torch_version_lt
from testing.base import BaseTester
@@ -251,3 +254,210 @@ class TestCombineTensorPatches(BaseTester):
actual = torch_optimizer(module)(patches)
assert actual.shape == (batch_size, 3, 8, 12)
self.assert_close(actual, module(patches))
+
+ def test_all_zero_unpadding_means_no_unpadding(self, device, dtype):
+ img = torch.arange(1, 36, device=device, dtype=dtype).view(1, 1, 5, 7)
+ patches = kornia.contrib.extract_tensor_patches(img, 2, 2, allow_auto_padding=True)
+ out = kornia.contrib.combine_tensor_patches(patches, (5, 7), 2, 2, allow_auto_unpadding=True, unpadding=(0, 0))
+ self.assert_close(out, img)
+
+ @pytest.mark.parametrize("stride", [2, 1])
+ def test_float64_round_trip_is_exact(self, stride, device):
+ # A-9: eps was added to every divisor, so 1000.0 came back as 999.99999.
+ if device.type == "mps":
+ pytest.skip("MPS has no float64")
+ g = torch.Generator().manual_seed(0)
+ img = (torch.rand(1, 2, 4, 6, generator=g, dtype=torch.float64) * 1000).to(device)
+ out = kornia.contrib.combine_tensor_patches(
+ kornia.contrib.extract_tensor_patches(img, 2, stride), (4, 6), 2, stride
+ )
+ assert torch.equal(out, img) # overlap counts are 1, 2 or 4: the mean of identical copies is exact
+
+ @pytest.mark.parametrize("stride", [2, 1])
+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int32, torch.int64])
+ def test_integer_round_trip_is_exact(self, stride, int_dtype, device):
+ # A-10: integers went through float32, so 16777217 came back as 16777216. Plan review P4: float64 would still
+ # round 2**53 + 1. Integer patches are summed in int64, exactly (on MPS from torch 2.9; older torch keeps the
+ # float32 fold). At stride 1 a pixel is covered up to 4 times, so 4 * (2**60 + 1) still fits int64.
+ if int_dtype != torch.uint8 and device.type == "mps" and torch_version_lt(2, 9, 0):
+ pytest.skip("MPS index_add_ has no int64 source before torch 2.9: the float32 fold is exact only to 2**24")
+ big = {torch.uint8: 255, torch.int32: 2**31 - 1, torch.int64: 2**60 + 1}[int_dtype]
+ img = torch.full((1, 2, 4, 6), 7, dtype=int_dtype, device=device)
+ img[0, 0, 1, 2] = big
+ img[0, 1, 2, 3] = big - 2
+ out = kornia.contrib.combine_tensor_patches(
+ kornia.contrib.extract_tensor_patches(img, 2, stride), (4, 6), 2, stride
+ )
+ assert out.dtype == int_dtype
+ assert torch.equal(out, img)
+
+ def test_integer_overlap_mean_truncates_toward_zero(self, device):
+ # A-6: overlapping, non-identical integer patches. Pixel (0, 1) is covered by patches 0 and 1: (5 + 2) / 2 = 3.5
+ # -> 3, and (-5 - 2) / 2 = -3.5 -> -3 (toward zero, as a float mean cast to an integer dtype does).
+ patches = torch.zeros(1, 6, 1, 2, 2, dtype=torch.int32, device=device) # 3 x 4 image, 2 x 2 windows, stride 1
+ patches[0, 0, 0, 0, 1] = 5
+ patches[0, 1, 0, 0, 0] = 2
+ out = kornia.contrib.combine_tensor_patches(patches, (3, 4), 2, 1)
+ assert out[0, 0, 0, 1].item() == 3
+ out = kornia.contrib.combine_tensor_patches(-patches, (3, 4), 2, 1)
+ assert out[0, 0, 0, 1].item() == -3
+
+ def test_bool_overlap_keeps_main_result(self, device):
+ # Probe on main (4863aed8a): bool patches went through float32, the overlap mean was cast back to bool, so a
+ # pixel is True when any covering patch is True. Literal produced by:
+ # p = torch.zeros(1, 6, 1, 2, 2, dtype=torch.bool); p[0, 0] = True; p[0, 1] = True
+ # combine_tensor_patches(p, (3, 4), 2, 1).tolist()
+ patches = torch.zeros(1, 6, 1, 2, 2, dtype=torch.bool, device=device)
+ patches[0, 0] = True
+ patches[0, 1] = True
+ out = kornia.contrib.combine_tensor_patches(patches, (3, 4), 2, 1)
+ assert out.dtype == torch.bool
+ assert out.tolist() == [[[[True, True, True, False], [True, True, True, False], [False, False, False, False]]]]
+
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
+ def test_empty_batch_integer_patches(self, int_dtype, device):
+ patches = kornia.contrib.extract_tensor_patches(torch.zeros(0, 3, 8, 12, dtype=int_dtype, device=device), 4, 4)
+ out = kornia.contrib.combine_tensor_patches(patches, (8, 12), 4, 4)
+ assert out.shape == (0, 3, 8, 12)
+ assert out.dtype == int_dtype
+
+ def test_integer_unpadding_crops_the_right_sides(self, device):
+ # Non-symmetric unpadding, (top, bottom, left, right) = (0, 2, 1, 3): a top/bottom or left/right swap
+ # in the crop changes the result.
+ img = torch.arange(1, 1 + 2 * 5 * 7, device=device, dtype=torch.int64).view(1, 2, 5, 7)
+ patches = kornia.contrib.extract_tensor_patches(img, 3, 2, padding=(0, 2, 1, 3))
+ out = kornia.contrib.combine_tensor_patches(patches, (5, 7), 3, 2, unpadding=(0, 2, 1, 3))
+ assert torch.equal(out, img)
+ out_f = kornia.contrib.combine_tensor_patches(patches.float(), (5, 7), 3, 2, unpadding=(0, 2, 1, 3))
+ assert torch.equal(out, out_f.long())
+
+ @pytest.mark.parametrize("patch_dtype", [torch.int64, torch.int32, torch.bool, torch.float32])
+ def test_negative_unpadding_restores_a_zero_border(self, patch_dtype, device):
+ # padding=-1 crops a 4 x 6 image to its 2 x 4 interior; unpadding=-1 pads the recombined interior back to
+ # 4 x 6 with zeros (False for bool), on the integer path as on the float one. Slicing gave a 1 x 1 tensor.
+ img = (torch.arange(1, 25, device=device).view(1, 1, 4, 6) % 3 + 1).to(patch_dtype)
+ patches = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=-1)
+ out = kornia.contrib.combine_tensor_patches(patches, (4, 6), 2, 2, unpadding=-1)
+ expected = torch.zeros_like(img)
+ expected[..., 1:-1, 1:-1] = img[..., 1:-1, 1:-1]
+ assert out.dtype == patch_dtype
+ assert torch.equal(out, expected)
+
+ def test_int64_overlap_mean_is_exact_at_the_int64_limits(self, device):
+ # Overlapping copies of 2**63 - 1 or -2**63 overflowed the int64 sum (they came back as -1 and 0). The mean is
+ # built from per-element quotients and remainders by the overlap count, so no partial sum leaves int64.
+ if device.type == "mps" and torch_version_lt(2, 9, 0):
+ pytest.skip("MPS index_add_ has no int64 source before torch 2.9: the float32 fold is exact only to 2**24")
+ for value in (2**63 - 1, -(2**63)):
+ img = torch.full((1, 2, 3, 5), value, dtype=torch.int64, device=device)
+ out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 2, 1), (3, 5), 2, 1)
+ assert torch.equal(out, img)
+ # Two patches over one pixel with opposite extremes: (2**63 - 1 - 2**63) / 2 = -0.5 truncates to 0.
+ patches = torch.zeros(1, 8, 1, 2, 2, dtype=torch.int64, device=device) # 3 x 5 image, 2 x 2 windows, stride 1
+ patches[0, 0, 0, 0, 1] = 2**63 - 1
+ patches[0, 1, 0, 0, 0] = -(2**63)
+ assert kornia.contrib.combine_tensor_patches(patches, (3, 5), 2, 1)[0, 0, 0, 1].item() == 0
+ # Random values over the whole int64 range, against the exact truncated mean in Python integers.
+ g = torch.Generator().manual_seed(0)
+ patches = torch.randint(-(2**63), 2**63 - 1, (2, 8, 2, 2, 2), generator=g, dtype=torch.int64)
+ target = kornia.contrib.extract_tensor_patches(torch.arange(15).view(1, 1, 3, 5), 2, 1)[0, :, 0].flatten()
+ expected = []
+ for b in range(2):
+ for c in range(2):
+ covering = [[] for _ in range(15)]
+ for value, pixel in zip(patches[b, :, c].flatten().tolist(), target.tolist()):
+ covering[pixel].append(value)
+ means = [abs(sum(v)) // len(v) * (1 if sum(v) >= 0 else -1) for v in covering]
+ expected.append(means)
+ out = kornia.contrib.combine_tensor_patches(patches.to(device), (3, 5), 2, 1)
+ assert out.flatten(2).flatten(0, 1).tolist() == expected
+
+ def test_uint64_overlap_mean_is_exact_above_2pow63(self, device):
+ # Codex review on #5960: an int64 cast wrapped 2**63 to -2**63, so (2**63 + 0) / 2 came back as 3 * 2**62.
+ # Main (4863aed8a) returned 2**62 here: 2**63 is exact in its float fold.
+ if device.type == "mps" and torch_version_lt(2, 9, 0):
+ pytest.skip("MPS index_add_ has no int64 source before torch 2.9: the float32 fold is exact only to 2**24")
+ # The values are set in int64 and viewed as uint64 (v - 2**64 for v >= 2**63): torch 2.5.1 cannot set a uint64
+ # element from a Python int >= 2**63 ("Overflow when unpacking long").
+ signed = torch.zeros(1, 6, 1, 2, 2, dtype=torch.int64, device=device) # 3 x 4 image, 2 x 2 windows, stride 1
+ signed[0, 1, 0, 0, 0] = -(2**63) # 2**63
+ out = kornia.contrib.combine_tensor_patches(signed.view(torch.uint64), (3, 4), 2, 1)
+ assert out.dtype == torch.uint64
+ assert out[0, 0, 0, 1].item() == 2**62
+ # Near the top of the range: (2**64 - 1 + 2**64 - 3) / 2 = 2**64 - 2, beyond a float64 fold's precision.
+ signed[0, 0, 0, 0, 1] = -1 # 2**64 - 1
+ signed[0, 1, 0, 0, 0] = -3 # 2**64 - 3
+ assert (
+ kornia.contrib.combine_tensor_patches(signed.view(torch.uint64), (3, 4), 2, 1)[0, 0, 0, 1].item()
+ == 2**64 - 2
+ )
+ # Patches that do not fit (6 patches of a 4 x 6 image recombined to 5 x 7, the warned path) leave row 4 and
+ # column 6 uncovered: they stay 0, not 2**63.
+ img = torch.full((1, 1, 4, 6), 2**64 - 1, dtype=torch.uint64, device=device)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning) # the existing "does not fit" warning
+ out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 2, 2), (5, 7), 2, 2)
+ expected = torch.full((1, 1, 5, 7), 2**64 - 1, dtype=torch.uint64)
+ expected[..., 4, :] = 0
+ expected[..., :, 6] = 0
+ assert torch.equal(out.cpu(), expected) # MPS has no uint64 eq kernel
+ # Random values over the whole uint64 range, against the exact floor mean in Python integers.
+ g = torch.Generator().manual_seed(0)
+ patches = torch.randint(-(2**63), 2**63 - 1, (2, 8, 2, 2, 2), generator=g, dtype=torch.int64).view(torch.uint64)
+ target = kornia.contrib.extract_tensor_patches(torch.arange(15).view(1, 1, 3, 5), 2, 1)[0, :, 0].flatten()
+ expected_means = []
+ for b in range(2):
+ for c in range(2):
+ covering = [[] for _ in range(15)]
+ for value, pixel in zip(patches[b, :, c].flatten().tolist(), target.tolist()):
+ covering[pixel].append(value)
+ expected_means.append([sum(v) // len(v) for v in covering])
+ out = kornia.contrib.combine_tensor_patches(patches.to(device), (3, 5), 2, 1)
+ assert out.flatten(2).flatten(0, 1).tolist() == expected_means
+
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
+ def test_integer_patch_count_mismatch_raises(self, int_dtype, device):
+ patches = torch.zeros(1, 5, 1, 2, 2, dtype=int_dtype, device=device) # a 4 x 6 image at stride 2 needs 6
+ with pytest.raises(RuntimeError, match="window size"):
+ kornia.contrib.combine_tensor_patches(patches, (4, 6), 2, 2)
+ patches = torch.zeros(1, 6, 1, 3, 3, dtype=int_dtype, device=device) # window size 3, not 2
+ with pytest.raises(RuntimeError, match="window size"):
+ kornia.contrib.combine_tensor_patches(patches, (4, 6), 2, 2)
+
+ def test_complex_round_trip(self, device):
+ # Complex patches are not integers: main cast them to float and discarded the imaginary part. They are folded
+ # as two real tensors, since MPS has no complex col2im kernel.
+ if device.type == "mps" and torch_version_lt(2, 9, 0):
+ pytest.skip("complex MPS tensors abort the process in unfold on torch 2.5.1")
+ g = torch.Generator().manual_seed(0)
+ img = torch.randn(1, 2, 4, 6, generator=g, dtype=torch.complex64).to(device)
+ out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 2, 1), (4, 6), 2, 1)
+ assert out.dtype == torch.complex64
+ self.assert_close(out, img)
+
+ def test_eps_is_deprecated_and_has_no_effect(self, device, dtype):
+ # Plan review P7: eps was added to every divisor (A-9), and clamp_min(eps) would still have turned a singly
+ # covered 7 into 3.5 at eps=2. On main, eps=0 gave NaN and eps=-1 gave inf. Patches that do not fit
+ # (6 patches of a 4 x 6 image recombined to 5 x 7, the warned path) leave row 4 and column 6 uncovered: they
+ # stay 0 for every eps.
+ img = torch.arange(1, 25, device=device, dtype=dtype).view(1, 1, 4, 6)
+ patches = kornia.contrib.extract_tensor_patches(img, 2, 2)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning) # the existing "does not fit" warning
+ expected = kornia.contrib.combine_tensor_patches(patches, (5, 7), 2, 2)
+ assert (expected[..., 4, :] == 0).all()
+ assert (expected[..., :, 6] == 0).all()
+ self.assert_close(expected[..., :4, :6], img)
+ for eps in (1e-8, 2.0, 0.0, -1.0):
+ with pytest.warns(DeprecationWarning, match="eps"):
+ out = kornia.contrib.combine_tensor_patches(patches, (5, 7), 2, 2, eps=eps)
+ assert torch.equal(out, expected)
+
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])
+ def test_half_precision_heavy_overlap_round_trip_is_exact(self, half, device):
+ # A-11: 289 overlapping 0..255 values summed in float16 overflowed (51 inf); bfloat16 was off by 64.
+ g = torch.Generator().manual_seed(0)
+ img = (torch.rand(1, 3, 40, 52, generator=g) * 255).round().to(device, half)
+ out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 17, 1), (40, 52), 17, 1)
+ assert out.dtype == half
+ assert torch.equal(out, img)
diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.py
index dc5411309..0d3aa3705 100644
--- a/tests/contrib/test_extract_tensor_patch.py
+++ b/tests/contrib/test_extract_tensor_patch.py
@@ -221,7 +221,7 @@ class TestExtractTensorPatches(BaseTester):
)
with pytest.raises(RuntimeError, match=r"step.*> 0"):
kornia.contrib.extract_tensor_patches(
- torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), 4, 0, padding=(0, 0, 0, 0)
+ torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), 4, 0, padding=(1, 1, 1, 1)
)
@pytest.mark.parametrize("batch_size", [0, 2])
@@ -231,3 +231,12 @@ class TestExtractTensorPatches(BaseTester):
actual = torch_optimizer(module)(image)
assert actual.shape == (batch_size, 6, 3, 4, 4)
self.assert_close(actual, module(image), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("padding", [(0, 0), (0, 0, 0, 0)])
+ def test_all_zero_padding_means_no_padding(self, padding, device, dtype):
+ # A-5: a zero tuple used to switch off allow_auto_padding (N 6 instead of 12, last row/column dropped).
+ img = torch.arange(1, 36, device=device, dtype=dtype).view(1, 1, 5, 7)
+ expected = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=0, allow_auto_padding=True)
+ out = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=padding, allow_auto_padding=True)
+ assert out.shape == (1, 12, 1, 2, 2)
+ self.assert_close(out, expected)
diff --git a/tests/contrib/test_hist_match.py b/tests/contrib/test_hist_match.py
index 8c1644237..f1d161460 100644
--- a/tests/contrib/test_hist_match.py
+++ b/tests/contrib/test_hist_match.py
@@ -22,6 +22,8 @@ import kornia
from testing.base import BaseTester
+inf = float("inf")
+
class TestHistMatch(BaseTester):
def test_interp(self, device, dtype):
@@ -140,3 +142,230 @@ class TestHistMatch(BaseTester):
src = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
dst = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
self.gradcheck(kornia.contrib.histogram_matching, (src, dst))
+
+ def test_interp_is_exact_at_its_knots(self, device, dtype):
+ xp = torch.tensor([0.0, 0.1, 0.35, 0.7, 1.0], device=device, dtype=dtype)
+ fp = torch.tensor([10.0, 20.0, 30.0, 47.0, 51.0], device=device, dtype=dtype)
+ assert torch.equal(kornia.contrib.interp(xp, xp, fp), fp)
+
+ def test_interp_left_of_a_repeated_first_knot(self, device, dtype):
+ # A-31: np.interp([-1, 0, 0.5], [0, 0, 1], [5, 6, 7]) == [5, 6, 6.5]; kornia returned 6.0 left of the step.
+ x = torch.tensor([-1.0, 0.0, 0.5], device=device, dtype=dtype)
+ xp = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ fp = torch.tensor([5.0, 6.0, 7.0], device=device, dtype=dtype)
+ assert kornia.contrib.interp(x, xp, fp).tolist() == [5.0, 6.0, 6.5]
+
+ def test_matching_an_image_to_itself_is_the_identity(self, device, dtype):
+ # A-21: 132 (float32) / 178 (float64) of 5328 pixels changed.
+ g = torch.Generator().manual_seed(0)
+ x = (torch.rand(2, 3, 24, 37, generator=g) * 255).round().to(device, dtype)
+ assert torch.equal(kornia.contrib.histogram_matching(x, x), x)
+
+ def test_uint8_result_survives_a_uint8_cast(self, device):
+ # A-21: [3, 1, 2] onto [10, 20, 30] gave [29.999998, 10, 20], i.e. 29 after .to(torch.uint8).
+ src = torch.tensor([3, 1, 2], dtype=torch.uint8, device=device)
+ tpl = torch.tensor([10, 20, 30], dtype=torch.uint8, device=device)
+ assert kornia.contrib.histogram_matching(src, tpl).to(torch.uint8).tolist() == [30, 10, 20]
+
+ def test_float32_output_stays_inside_the_template_range(self, device):
+ # A-22: #5794's range guarantee leaked one ulp in 24-49 of 300 random float32 pairs.
+ outside = 0
+ for seed in range(300):
+ g = torch.Generator().manual_seed(seed)
+ n1, n2 = torch.randint(2, 60, (2,), generator=g).tolist()
+ src = (torch.rand(n1, generator=g) * 3).to(device)
+ tpl = (torch.rand(n2, generator=g) * 3).to(device)
+ out = kornia.contrib.histogram_matching(src, tpl)
+ outside += int(bool((out > tpl.max()).any() or (out < tpl.min()).any()))
+ assert outside == 0
+
+ def test_empty_source_gives_an_empty_output(self, device, dtype):
+ out = kornia.contrib.histogram_matching(
+ torch.zeros(0, 3, 4, 5, device=device, dtype=dtype), torch.rand(1, 3, 4, 5, device=device, dtype=dtype)
+ )
+ assert out.shape == (0, 3, 4, 5)
+ assert out.dtype == dtype
+
+ def test_empty_template_raises(self, device, dtype):
+ with pytest.raises(ValueError, match="template"):
+ kornia.contrib.histogram_matching(
+ torch.rand(1, 3, 4, 5, device=device, dtype=dtype), torch.zeros(0, 3, 4, 5, device=device, dtype=dtype)
+ )
+
+ def test_interp_integer_inputs_return_floats(self, device):
+ # All-integer inputs interpolate in the default float dtype: lerp has no integer kernel.
+ x = torch.tensor([4, 5, 6], device=device)
+ xp = torch.tensor([1, 2, 3], device=device)
+ fp = torch.tensor([4, 2, 0], device=device)
+ out = kornia.contrib.interp(x, xp, fp)
+ assert out.dtype == torch.get_default_dtype()
+ assert out.tolist() == [-2.0, -4.0, -6.0]
+
+ @pytest.mark.parametrize(
+ ("fp", "x", "expected"),
+ [
+ # np.interp(x, [0, 1, 2, 3], fp) for each case
+ ([3.0, 4.0, inf, inf], [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0], [3.0, 3.5, 4.0, inf, inf, inf, inf]),
+ ([-inf, 2.0, 3.0, 4.0], [0.0, 0.25, 0.5, 1.0, 1.5, 2.0, 3.0], [-inf, -inf, -inf, 2.0, 2.5, 3.0, 4.0]),
+ ([3.0, 4.0, 5.0, 5.0], [0.5, 1.5, 2.5, 3.0], [3.5, 4.5, 5.0, 5.0]),
+ ],
+ )
+ def test_interp_non_finite_fp_matches_numpy(self, fp, x, expected, device, dtype):
+ xp = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=dtype)
+ out = kornia.contrib.interp(
+ torch.tensor(x, device=device, dtype=dtype), xp, torch.tensor(fp, device=device, dtype=dtype)
+ )
+ assert out.tolist() == expected
+
+ def test_template_with_minus_inf_maps_the_lowest_value_to_minus_inf(self, device):
+ src = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device)
+ tpl = torch.tensor([-inf, 2.0, 3.0, 4.0], device=device)
+ out = kornia.contrib.histogram_matching(src, tpl)
+ assert out.tolist() == [-inf, 2.0, 3.0, 4.0]
+
+ def test_interp_propagates_nan(self, device, dtype):
+ xp = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ nan = float("nan")
+ out = kornia.contrib.interp(torch.tensor([nan, 0.5], device=device, dtype=dtype), xp, xp)
+ assert out[0].isnan()
+ assert out[1] == 0.5
+ out = kornia.contrib.interp(
+ torch.tensor([0.5, 1.0], device=device, dtype=dtype),
+ xp,
+ torch.tensor([0.0, nan], device=device, dtype=dtype),
+ )
+ assert out.isnan().all()
+ # A NaN query stays NaN on a flat segment and on a repeated last knot too: np.interp([nan], [0, 1], [5, 5])
+ # and np.interp([nan], [0, 1, 1], [5, 6, 7]) are both nan (they gave 5.0 and 7.0).
+ for xp_values, fp_values in (([0.0, 1.0], [5.0, 5.0]), ([0.0, 1.0, 1.0], [5.0, 6.0, 7.0])):
+ out = kornia.contrib.interp(
+ torch.tensor([nan], device=device, dtype=dtype),
+ torch.tensor(xp_values, device=device, dtype=dtype),
+ torch.tensor(fp_values, device=device, dtype=dtype),
+ )
+ assert out.isnan().all()
+
+ def test_interp_flat_segment_with_an_infinite_knot_keeps_its_value(self, device, dtype):
+ # Only a NaN query is excluded from the flat-segment value: here the weight is inf / inf = nan, but the
+ # segment is flat, and np.interp([-0.5], [-inf, 0, 1], [5, 5, 6]) == [5.0].
+ out = kornia.contrib.interp(
+ torch.tensor([-0.5], device=device, dtype=dtype),
+ torch.tensor([-inf, 0.0, 1.0], device=device, dtype=dtype),
+ torch.tensor([5.0, 5.0, 6.0], device=device, dtype=dtype),
+ )
+ assert out.tolist() == [5.0]
+
+ def test_interp_integer_coordinates_above_2_24_are_exact(self, device):
+ # Integer coordinates are compared and subtracted as integers: as float32, 16777217 rounds to 16777216.
+ # np.interp([16777217], [16777216, 16777218], [0, 2]) == [1.0]; the float32 cast gave [0.0].
+ out = kornia.contrib.interp(
+ torch.tensor([16777217], device=device),
+ torch.tensor([16777216, 16777218], device=device),
+ torch.tensor([0, 2], device=device),
+ )
+ assert out.tolist() == [1.0]
+ # A knot whose right neighbour rounds onto it in float32: np.interp([16777216], [0, 16777216, 16777217],
+ # [0, 5, 1]) == [5.0]; the float32 cast saw a zero-width segment and gave [1.0].
+ out = kornia.contrib.interp(
+ torch.tensor([16777216], device=device),
+ torch.tensor([0, 16777216, 16777217], device=device),
+ torch.tensor([0, 5, 1], device=device),
+ )
+ assert out.tolist() == [5.0]
+ # uint8 coordinates are widened before they are subtracted: 0 - 1 does not wrap to 255.
+ out = kornia.contrib.interp(
+ torch.tensor([0, 3], dtype=torch.uint8, device=device),
+ torch.tensor([1, 2], dtype=torch.uint8, device=device),
+ torch.tensor([10.0, 20.0], device=device),
+ )
+ assert out.tolist() == [0.0, 30.0]
+
+ @pytest.mark.parametrize("complex_dtype", [torch.complex64, torch.complex128])
+ def test_interp_complex_fp(self, complex_dtype, device):
+ # The real and imaginary parts are interpolated separately, as np.interp does:
+ # np.interp([0, 0.5, 1, 1.5], [0, 1], [1+2j, 3+4j]) gives [1+2j, 2+3j, 3+4j, 3+4j]; kornia extrapolates the
+ # last point to 4+5j.
+ if device.type == "mps" and complex_dtype == torch.complex128:
+ pytest.skip("MPS has no float64")
+ real_dtype = torch.float32 if complex_dtype == torch.complex64 else torch.float64
+ x = torch.tensor([0.0, 0.5, 1.0, 1.5], device=device, dtype=real_dtype)
+ xp = torch.tensor([0.0, 1.0], device=device, dtype=real_dtype)
+ out = kornia.contrib.interp(x, xp, torch.tensor([1 + 2j, 3 + 4j], device=device, dtype=complex_dtype))
+ assert out.dtype == complex_dtype
+ assert out.tolist() == [1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j]
+
+ def test_interp_half_x_with_float32_fp_keeps_float32_precision(self, device):
+ # np.interp([0.3, 0.77, 1.4], [0, 1, 2], [10, 20.001, 45.123456]) in float64 with the half x rounded first:
+ # [13.000788165, 17.700964891, 30.059795149]. Computing the weight in half precision was off by 2e-3.
+ x = torch.tensor([0.3, 0.77, 1.4], device=device, dtype=torch.float16)
+ xp = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=torch.float16)
+ fp = torch.tensor([10.0, 20.001, 45.123456], device=device)
+ out = kornia.contrib.interp(x, xp, fp)
+ expected = torch.tensor([13.000788165, 17.700964891, 30.059795149], device=device)
+ assert out.dtype == torch.float32
+ assert (out - expected).abs().max() < 1e-5
+
+ def test_interp_gradient_at_knots_is_the_segment_slope(self, device):
+ x = torch.tensor([1.0, 2.0, 2.5, 4.0], device=device, requires_grad=True)
+ xp = torch.arange(5.0, device=device)
+ kornia.contrib.interp(x, xp, 3 * xp).sum().backward()
+ assert x.grad.tolist() == [3.0, 3.0, 3.0, 3.0]
+
+ def test_interp_gradcheck(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS has no float64")
+ xp = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=torch.float64)
+ x = torch.tensor([0.3, 1.7, 2.2, 3.4], device=device, dtype=torch.float64, requires_grad=True)
+ fp = torch.tensor([1.0, -2.0, 5.0, 4.0], device=device, dtype=torch.float64, requires_grad=True)
+ assert torch.autograd.gradcheck(lambda a, c: kornia.contrib.interp(a, xp, c), (x, fp))
+
+ @pytest.mark.parametrize(("float_dtype", "big"), [(torch.float32, 3e38), (torch.float16, 40000.0)])
+ def test_interp_finite_ends_give_finite_values_when_their_difference_overflows(self, float_dtype, big, device):
+ # f1 - f0 overflows (6e38 > float32 max, 8e4 > float16 max) but every interpolated value is finite.
+ x = torch.tensor([0.0, 0.25, 0.5, 0.75, 1.0], device=device, dtype=float_dtype)
+ xp = torch.tensor([0.0, 1.0], device=device, dtype=float_dtype)
+ out = kornia.contrib.interp(x, xp, torch.tensor([-big, big], device=device, dtype=float_dtype))
+ expected = torch.tensor([-big, -big / 2, 0.0, big / 2, big], device=device, dtype=float_dtype)
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize(
+ ("float_dtype", "big"), [(torch.float64, 1e308), (torch.float32, 3e38), (torch.float16, 40000.0)]
+ )
+ def test_interp_gradient_is_the_slope_when_the_difference_overflows(self, float_dtype, big, device):
+ # f1 - f0 = 2 * big overflows, but the slope 2 * big / 4 = big / 2 is representable, at the knots too. The
+ # formulas the overflow branch replaces used to multiply their zero gradient by the infinite difference: nan.
+ if device.type == "mps" and float_dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ x = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=float_dtype, requires_grad=True)
+ xp = torch.tensor([0.0, 4.0], device=device, dtype=float_dtype)
+ out = kornia.contrib.interp(x, xp, torch.tensor([-big, big], device=device, dtype=float_dtype))
+ out.sum().backward()
+ expected = torch.tensor([-big, -big / 2, 0.0, big / 2, big], device=device, dtype=float_dtype)
+ self.assert_close(out.detach(), expected)
+ assert torch.equal(x.grad, torch.full_like(x, big) / 2)
+
+ def test_interp_extrapolation_that_overflows_stays_infinite(self, device):
+ out = kornia.contrib.interp(
+ torch.tensor([10.0], device=device),
+ torch.tensor([0.0, 1.0], device=device),
+ torch.tensor([3e38, 3.4e38], device=device),
+ )
+ assert out.tolist() == [float("inf")]
+
+ def test_jit_script(self, device, dtype):
+ # Codex review on #5960: a recursive interp (for the complex parts) made both public functions unscriptable,
+ # also for real inputs; main (4863aed8a) scripted them.
+ interp_script = torch.jit.script(kornia.contrib.interp)
+ x = torch.linspace(-1.0, 2.0, 13, device=device, dtype=dtype)
+ xp = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=dtype)
+ fp = torch.tensor([1.0, 3.0, -2.0], device=device, dtype=dtype)
+ self.assert_close(interp_script(x, xp, fp), kornia.contrib.interp(x, xp, fp))
+ ints = torch.tensor([4, 5, 6], device=device), torch.tensor([1, 2, 3], device=device)
+ out = interp_script(*ints, torch.tensor([4, 2, 0], device=device))
+ assert out.dtype == torch.get_default_dtype() # all-integer inputs, as in eager
+ assert out.tolist() == [-2.0, -4.0, -6.0]
+ g = torch.Generator().manual_seed(0)
+ source = torch.rand(1, 3, 8, 9, generator=g).to(device, dtype)
+ template = (torch.rand(1, 3, 10, 7, generator=g) ** 2).to(device, dtype)
+ matched = torch.jit.script(kornia.contrib.histogram_matching)(source, template)
+ self.assert_close(matched, kornia.contrib.histogram_matching(source, template))