Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): exact int64 component labels, distance-transform h guards, KMeans termination (#5961)

Dmytro Mishkin22e6894f0818
diff --git a/changelog.d/5961.breaking.md b/changelog.d/5961.breaking.md
new file mode 100644
index 000000000..59ef9651c
--- /dev/null
+++ b/changelog.d/5961.breaking.md
@@ -0,0 +1,9 @@
+`connected_components` now returns `int64` labels with exact ids. It used to return the input dtype, which merged distinct components in `float16`, `bfloat16`, `bool` and `uint8` inputs (ids lost precision or wrapped) and, in any dtype, above 2**24 pixels. On MPS, which has no `float64`, an image of more than 2**24 pixels (a single image, not the batch) now raises `ValueError` instead of returning merged labels.
+
+`KMeans(tolerance=None, max_iterations=0)`, a negative `max_iterations` and a negative `tolerance` now raise `BaseError`. The first never stopped fitting. A negative `max_iterations` used to stop the fit after one iteration, and a negative `tolerance` used to be accepted and never triggered the early stop.
+
+`KMeans.predict` with a 1-D input now raises `ShapeError` instead of `IndexError`.
+
+`distance_transform` and `DistanceTransform` now reject an `h` so small that the kernel's corner tap `exp(-sqrt(ndim) * (kernel_size // 2) / h)` underflows, which the old axis-tap check let through. Such calls used to return wrong distances (for example float32 17.78 instead of 21.21 at `kernel_size=31`, `h=0.18`).
+
+`distance_transform` and `DistanceTransform` now reject an `h` above a bound that depends on `kernel_size` and the working precision: in 2-D `h < 0.5624` at `kernel_size=3` (`0.5626` in `float64`) and about `0.50` at larger kernels, in 3-D `h < 0.4070` at `kernel_size=3` (`0.4071` in `float64`) and about `0.38` at larger kernels. The bound leaves the off-centre kernel taps a margin below 1 for the rounding of the working precision. Such an `h` used to return 0, as if on the foreground, at background pixels whose window was full of reached pixels.
diff --git a/changelog.d/5961.fixed.md b/changelog.d/5961.fixed.md
new file mode 100644
index 000000000..600c1d5b3
--- /dev/null
+++ b/changelog.d/5961.fixed.md
@@ -0,0 +1,5 @@
+`connected_components` accepts batches that cannot be viewed as one block (for example permuted leading dimensions) and inputs with `H = 0` or `W = 0`, which used to crash.
+
+`KMeans.fit` with `tolerance=0.0` now stops at the fixed point instead of never returning, and a second `fit` samples fresh initial centres from its own data (it reused the first fit's centres, and raised for data of another dimension) unless explicit `cluster_centers` were given. Distances in `fit` and `predict` are computed in at least `float32` (and in the promoted dtype of data and centres), so `float16` squared distances no longer overflow to `inf` and pick cluster 0. Integer data against integer centres is handled in `int64`: it was compared and summed in the narrow integer dtype, which wraps (`uint8` data: the mean of 200 and 210 came out as `[77, 77]`), and the convergence shift wrapped the same way, so the fit could stop while the centres were still moving. `predict` checks that its input is 2-D.
+
+`Lambda` names the right argument (`func`) in its non-callable error message; it used to name a non-existent `lambd` argument.
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 25773be4c..3e5dbb9e1 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -255,12 +255,12 @@ It is useful for segmentation masks containing long structures such as vessels,
roads and text strokes. Its convergence checks synchronize the accelerator with
the host, and the result is not differentiable.
-``connected_components`` retains its fixed-count pooling implementation and its
-existing output dtype and label convention. When using it, choose enough
-iterations for the largest component's graph diameter: the default 100 steps
-can leave a long component split into multiple labels. A small fixed budget may
-be faster than union-find for small or fragmented masks, but does not guarantee
-convergence. The two implementations produce different numerical label IDs;
+``connected_components`` retains its fixed-count pooling implementation; it
+returns ``int64`` labels like ``connected_components_union_find`` but keeps its
+own label convention. When using it, choose enough iterations for the largest
+component's graph diameter: the default 100 steps can leave a long component
+split into multiple labels. A small fixed budget may be faster than union-find
+for small or fragmented masks, but does not guarantee convergence. The two implementations produce different numerical label IDs;
compare their foreground partitions instead of comparing label values directly.
Segment Anything (SAM)
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index f34bc0fc1..849d22e26 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -40,7 +40,7 @@ def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torc
num_iterations: the number of iterations to make the algorithm to converge.
Return:
- The labels image with the same shape of the input image.
+ int64 labels with the shape of the input.
Example:
>>> img = torch.rand(2, 1, 4, 5)
@@ -57,21 +57,37 @@ def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torc
raise ValueError(f"Input image shape must be (*,1,H,W). Got: {image.shape}")
H, W = image.shape[-2:]
- image_view = image.view(-1, 1, H, W)
+ # Before the reshape: reshape(-1, 1, 0, W) cannot infer -1 from zero elements.
+ if image.numel() == 0:
+ return torch.zeros(image.shape, dtype=torch.int64, device=image.device)
+ image_view = image.reshape(-1, 1, H, W)
+ B = image_view.shape[0]
+ num_ids = H * W
+ # Pooling never mixes batch planes, so every plane is labelled with its own ids 1..H*W and the plane offset is added
+ # in int64 afterwards. Labels are pooled as floats (max_pool2d has no integer kernel): float32 holds every integer
+ # up to 2**24 exactly; larger planes need float64, which MPS does not have.
+ id_dtype = torch.float32
+ if num_ids > 2**24:
+ if image.device.type == "mps":
+ raise ValueError(
+ f"connected_components labels {num_ids} pixels in one image; on MPS (no float64) the limit is 2**24 "
+ "pixels per image. Run it on the CPU instead."
+ )
+ id_dtype = torch.float64
# precompute a mask with the valid values
mask = image_view == 1
-
- # allocate the output tensors for labels
- B, _, _, _ = image_view.shape
- out = torch.arange(1, B * H * W + 1, device=image.device, dtype=torch.float32).view((-1, 1, H, W))
- out[~mask] = 0
+ out = torch.arange(1, num_ids + 1, device=image.device, dtype=id_dtype).view(1, 1, H, W).expand(B, 1, H, W)
+ out = out * mask
for _ in range(num_iterations):
out = F.max_pool2d(out, kernel_size=3, stride=1, padding=1)
out = torch.mul(out, mask) # mask using element-wise multiplication
- return out.to(image.dtype).view_as(image)
+ labels = out.to(torch.int64)
+ offset = torch.arange(B, device=image.device, dtype=torch.int64).view(-1, 1, 1, 1) * num_ids
+ # Shift the foreground labels by the plane offset in place; the mask zeroes the background again.
+ return labels.add_(offset).mul_(mask).view(image.shape)
def connected_components_union_find(image: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 9201cbc5d..5cd104662 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -37,23 +37,53 @@ def _compute_dtype(dtype: torch.dtype) -> torch.dtype:
return dtype
-def _check_h_range(kernel_size: int, h: float, dtype: torch.dtype) -> None:
- # The kernel's corner tap (distance sqrt(dims)*k_half) decays fast enough that losing it is
- # harmless -- its contribution to the soft-min is negligible by construction. It is the
- # axis-aligned tap, at distance k_half along a single axis, that has to survive: losing it is
- # what actually corrupts the result, so it -- not the corner -- is the discriminating case.
- # Checked against `finfo.tiny` -- the smallest positive *normal* value -- rather than the true
- # (device-dependent) smallest subnormal: MPS flushes subnormals to zero while CPU does not, so
- # a subnormal-aware threshold would silently disagree across devices for the same dtype and h,
- # which is the inconsistency this guard exists to rule out.
+def _check_h_range(kernel_size: int, h: float, dtype: torch.dtype, ndim: int) -> None:
+ # The cascade needs every tap of the exp(-dist/h) kernel. The farthest one, the corner at distance
+ # sqrt(ndim) * k_half, underflows first; losing it changes the soft-min wherever the nearest source is diagonal.
+ # Checked against finfo.tiny (smallest normal), because MPS flushes subnormals to zero and CPU does not.
k_half = kernel_size // 2
- smallest_tap = math.exp(-k_half / h)
+ farthest_tap = math.exp(-math.sqrt(ndim) * k_half / h)
KORNIA_CHECK(
- smallest_tap >= torch.finfo(dtype).tiny,
- f"h={h} is too small for kernel_size={kernel_size} at working precision {dtype}: the axis-aligned "
- f"kernel tap exp(-{k_half}/h) underflows to zero, so the convolution silently drops it and "
- "distance_transform returns a wrong or all-zero result. Increase h or decrease kernel_size.",
+ farthest_tap >= torch.finfo(dtype).tiny,
+ f"h={h} is too small for kernel_size={kernel_size} at working precision {dtype}: the corner kernel tap "
+ f"exp(-sqrt({ndim})*{k_half}/h) falls below the smallest normal number of that precision and the result "
+ "would be wrong. Increase h or decrease kernel_size.",
)
+ # A pixel counts as reached when -h*log(sum of its window's taps over reached pixels) > 0, i.e. when that sum is
+ # below 1; a source pixel fails the test through its own centre tap, and that is how sources stay at 0. If the
+ # off-centre taps can sum to 1 or more, an unreached pixel whose window is full of reached pixels fails it too and
+ # reads as foreground (0).
+ # The sum below is taken in float64, but the cascade forms it in the working precision: each tap is rounded when
+ # the kernel is built (exp of a rounded argument), and the window sum adds kernel_size**ndim roundings.
+ # 4 * kernel_size**ndim * eps bounds both with room. On CUDA a float32 convolution may also run in TF32
+ # (PyTorch's default for cuDNN), which rounds each tap to 10 mantissa bits: a relative 2**-11 on a sum below 1.
+ margin = 4 * kernel_size**ndim * torch.finfo(dtype).eps + (2.0**-11 if dtype == torch.float32 else 0.0)
+ off_centre = _off_centre_tap_sum(kernel_size, h, ndim)
+ KORNIA_CHECK(
+ off_centre < 1.0 - margin,
+ f"h={h} is too large for kernel_size={kernel_size} in {ndim}-D: the kernel's off-centre taps sum to "
+ f"{off_centre:.7f}, not below 1 by the rounding margin {margin:.1e} of the {dtype} working precision, so a "
+ "pixel surrounded by reached pixels could read as foreground (distance 0). Decrease h.",
+ )
+
+
+def _off_centre_tap_sum(kernel_size: int, h: float, ndim: int) -> float:
+ # Sum of exp(-|q|/h) over the kernel offsets q != 0, one octant at a time: every nonzero coordinate has a mirror
+ # twin, so it counts twice. Plain Python on constants, so the check stays out of the traced graph (no tensor, no
+ # .item()); nested loops, because generator expressions in this inner loop made the check take seconds at large
+ # kernels.
+ k_half = kernel_size // 2
+ weight = [1.0] + [2.0] * k_half
+ square = [c * c for c in range(k_half + 1)]
+ total = 0.0
+ for a in range(k_half + 1):
+ for b in range(k_half + 1):
+ if ndim == 2:
+ total += weight[a] * weight[b] * math.exp(-math.sqrt(square[a] + square[b]) / h)
+ continue
+ for c in range(k_half + 1):
+ total += weight[a] * weight[b] * weight[c] * math.exp(-math.sqrt(square[a] + square[b] + square[c]) / h)
+ return total - 1.0 # drop the centre tap
def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:
@@ -137,11 +167,15 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3
image: Image or volume with shape :math:`(B,C,H,W)` or :math:`(B,C,D,H,W)`.
kernel_size: size of the convolution kernel. Must be an odd number.
h: value that influences the approximation of the min function. The cascade's kernel taps are
- ``exp(-dist/h)``; too small an ``h`` for the given ``kernel_size`` underflows the
- axis-aligned tap (distance ``kernel_size // 2``) to exactly zero, which used to return a
- silently wrong or all-zero result. That combination now raises instead. ``float16`` and
- ``bfloat16`` inputs run the cascade in ``float32`` and cast the result back, which widens
- the safe ``h`` range for those dtypes to match ``float32``.
+ ``exp(-dist/h)``. Accepted: ``h`` large enough that the corner tap (distance
+ ``sqrt(ndim) * (kernel_size // 2)``) stays at or above the smallest normal number of the working
+ precision, and small enough that the off-centre taps sum to less than 1 by a margin for the working
+ precision's rounding (2-D: below 0.5624 at ``kernel_size`` 3, 0.5626 in ``float64``, about 0.50 at
+ larger kernels; 3-D: below 0.4070 at 3, 0.4071 in ``float64``, about 0.38 at larger kernels).
+ Any other ``h`` raises:
+ a smaller one would give wrong distances, a larger one would give 0 at background pixels whose window
+ is full of reached pixels. ``float16`` and ``bfloat16`` inputs run the cascade in ``float32`` and cast the
+ result back, which widens the safe ``h`` range for those dtypes to match ``float32``.
Returns:
tensor with the same shape as input.
@@ -174,7 +208,7 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3
KORNIA_CHECK(h > 0, f"h must be a positive float, got {h}")
compute_dtype = _compute_dtype(image.dtype)
- _check_h_range(kernel_size, h, compute_dtype)
+ _check_h_range(kernel_size, h, compute_dtype, image.ndim - 2)
if image.ndim == 4:
return _distance_transform_2d_impl(image, kernel_size, h)
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index dcfea4cca..afeb9e69b 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -51,6 +51,12 @@ class KMeans:
seed: int | None = None,
) -> None:
KORNIA_CHECK(num_clusters != 0, "num_clusters can't be 0")
+ KORNIA_CHECK(max_iterations >= 0, f"max_iterations must be >= 0, got {max_iterations}")
+ KORNIA_CHECK(tolerance is None or tolerance >= 0, f"tolerance must be None or >= 0, got {tolerance}")
+ KORNIA_CHECK(
+ tolerance is not None or max_iterations > 0,
+ "tolerance=None needs max_iterations > 0: with max_iterations=0 the fit would never stop.",
+ )
# cluster_centers should have only 2 dimensions
if cluster_centers is not None:
@@ -61,6 +67,7 @@ class KMeans:
)
self.num_clusters = num_clusters
+ self._initial_cluster_centers = cluster_centers # user-given start; None means sample from each fit's X
self._cluster_centers = cluster_centers
self.tolerance = tolerance
self.max_iterations = max_iterations
@@ -110,6 +117,23 @@ class KMeans:
return self._final_cluster_assignments
raise TypeError("Model has not been fit to a dataset")
+ @staticmethod
+ def _work_dtype(*tensors: torch.Tensor) -> torch.dtype:
+ """Dtype for distances and sums: the promoted dtype.
+
+ Half types lift to float32. When every tensor is integer the work dtype is int64, which is exact (float32
+ would merge integers above 2**24, and uint8 arithmetic wraps) while the squared distance stays below 2**63
+ (a distance of about 3.0e9).
+ """
+ dtype = tensors[0].dtype
+ for t in tensors[1:]:
+ dtype = torch.promote_types(dtype, t.dtype)
+ if dtype in (torch.float16, torch.bfloat16):
+ return torch.float32
+ if not dtype.is_floating_point:
+ return torch.int64
+ return dtype
+
def _initialise_cluster_centers(self, X: torch.Tensor, num_clusters: int) -> torch.Tensor:
"""Chooses num_cluster points from X as the initial cluster centers.
@@ -127,7 +151,10 @@ class KMeans:
return X[idx]
def _pairwise_euclidean_distance(self, data1: torch.Tensor, data2: torch.Tensor) -> torch.Tensor:
- """Compute pairwise squared distance between 2 sets of vectors.
+ """Compute pairwise distance between 2 sets of vectors.
+
+ Floating-point vectors give the Euclidean distance; integer vectors give the exact squared distance in int64
+ (same argmin).
Args:
data1: 2D torch.Tensor of shape N, D
@@ -141,6 +168,10 @@ class KMeans:
A = data1[:, None, ...]
# 1*C*D
B = data2[None, ...]
+ if not A.dtype.is_floating_point and not B.dtype.is_floating_point:
+ # Integer vectors: the squared distance is exact in int64, whereas its square root would round to float32.
+ # The caller only takes an argmin, which the square root does not change.
+ return (A - B).pow(2).sum(dim=-1)
return euclidean_distance(A, B)
def fit(self, X: torch.Tensor) -> None:
@@ -154,25 +185,28 @@ class KMeans:
# X should have only 2 dimensions
KORNIA_CHECK_SHAPE(X, ["N", "D"])
- if self._cluster_centers is None:
- self._cluster_centers = self._initialise_cluster_centers(X, self.num_clusters)
+ if self._initial_cluster_centers is None:
+ current_centers = self._initialise_cluster_centers(X, self.num_clusters)
else:
# X and cluster_centers should have same number of columns
KORNIA_CHECK(
- X.shape[1] == self._cluster_centers.shape[1],
+ X.shape[1] == self._initial_cluster_centers.shape[1],
f"Dimensions at position 1 of X and cluster_centers do not match. \
- {X.shape[1]} != {self._cluster_centers.shape[1]}",
+ {X.shape[1]} != {self._initial_cluster_centers.shape[1]}",
)
+ current_centers = self._initial_cluster_centers
- # X = X.to(self.device)
- current_centers = self._cluster_centers
+ # Distances and sums run in the promoted dtype, at least float32 for floating data (squared float16 distances
+ # overflow past 255) and int64 for integer data.
+ work_dtype = self._work_dtype(X, current_centers)
+ X_work = X.to(work_dtype)
previous_centers: torch.Tensor | None = None
iteration: int = 0
while True:
# find distance between X and current_centers
- distance: torch.Tensor = self._pairwise_euclidean_distance(X, current_centers)
+ distance: torch.Tensor = self._pairwise_euclidean_distance(X_work, current_centers.to(work_dtype))
cluster_assignment = distance.argmin(-1)
@@ -184,30 +218,40 @@ class KMeans:
# scatter_add_ into the small (num_clusters, D) destination measured ~10x slower on
# MPS for this shape (many threads racing to accumulate into few destination rows).
#
- # Counts stay int64 (exact) and the sum accumulates in at least float32: X.dtype
- # itself overflows to inf in float16 past 65504, and loses precision in bfloat16,
- # for perfectly ordinary inputs (e.g. float16 image color quantization).
+ # Counts stay int64 (exact) and the sum accumulates in the work dtype (at least float32 for floating data,
+ # int64 for integer data): X.dtype itself overflows to inf in float16 past 65504, and loses precision in
+ # bfloat16, for perfectly ordinary inputs (e.g. float16 image color quantization).
one_hot = torch.nn.functional.one_hot(cluster_assignment, num_classes=self.num_clusters)
cluster_counts = one_hot.sum(0)
- work_dtype = torch.float32 if X.dtype in (torch.float16, torch.bfloat16) else X.dtype
- X_work = X.to(work_dtype)
- cluster_sums = one_hot.to(work_dtype).t() @ X_work
+ if work_dtype.is_floating_point:
+ cluster_sums = one_hot.to(work_dtype).t() @ X_work
+ else:
+ # integer sums are exact with scatter_add_; MPS lacks integer matmul and index_add_ on torch 2.5
+ index = cluster_assignment[:, None].expand(-1, X_work.shape[1])
+ cluster_sums = X_work.new_zeros(self.num_clusters, X_work.shape[1]).scatter_add_(0, index, X_work)
# edge case when a certain cluster centre has no points assigned to it:
# just choose a random point as its update. A random index is drawn for every
# cluster unconditionally and masked with torch.where, so the branch never depends
# on a data-dependent Python bool (no host sync either way).
empty_mask = (cluster_counts == 0).unsqueeze(1)
- means = cluster_sums / cluster_counts.clamp(min=1).unsqueeze(1).to(work_dtype)
+ safe_counts = cluster_counts.clamp(min=1).unsqueeze(1).to(work_dtype)
+ if work_dtype.is_floating_point:
+ means = cluster_sums / safe_counts
+ else:
+ # exact integer mean, rounded toward zero like the cast back to an integer X.dtype
+ means = torch.div(cluster_sums, safe_counts, rounding_mode="trunc")
random_points = X_work[torch.randint(len(X), (self.num_clusters,), device=X.device)]
current_centers = torch.where(empty_mask, random_points, means).to(X.dtype)
# sum of distance of how much the newly computed clusters have moved from their previous positions
- center_shift = torch.sum(torch.sqrt(torch.sum((current_centers - previous_centers) ** 2, dim=1)))
+ # (in the work dtype: subtracting and squaring in a narrow integer dtype wraps)
+ shift = current_centers.to(work_dtype) - previous_centers.to(work_dtype)
+ center_shift = torch.sum(torch.sqrt(torch.sum(shift**2, dim=1)))
iteration = iteration + 1
- if self.tolerance is not None and center_shift**2 < self.tolerance:
+ if self.tolerance is not None and center_shift**2 <= self.tolerance:
break
if self.max_iterations != 0 and iteration >= self.max_iterations:
@@ -227,6 +271,7 @@ class KMeans:
1D torch.Tensor containing cluster id assigned to each data point in x
"""
+ KORNIA_CHECK_SHAPE(x, ["N", "D"])
# x and cluster_centers should have same number of columns
KORNIA_CHECK(
x.shape[1] == self.cluster_centers.shape[1],
@@ -234,5 +279,6 @@ class KMeans:
{x.shape[1]} != {self.cluster_centers.shape[1]}",
)
- distance = self._pairwise_euclidean_distance(x, self.cluster_centers)
+ work_dtype = self._work_dtype(x, self.cluster_centers)
+ distance = self._pairwise_euclidean_distance(x.to(work_dtype), self.cluster_centers.to(work_dtype))
return distance.argmin(-1)
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index ab09458cc..e714913bf 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -42,7 +42,7 @@ class Lambda(nn.Module):
def __init__(self, func: Callable[..., torch.Tensor]) -> None:
super().__init__()
if not callable(func):
- raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}")
+ raise TypeError(f"Argument func should be callable, got {type(func).__name__!r}")
self.func = func
diff --git a/tests/contrib/test_connected_component.py b/tests/contrib/test_connected_component.py
index c829d9340..eda0537c3 100644
--- a/tests/contrib/test_connected_component.py
+++ b/tests/contrib/test_connected_component.py
@@ -87,7 +87,7 @@ class TestConnectedComponents(BaseTester):
]
],
device=device,
- dtype=dtype,
+ dtype=torch.int64,
)
out = kornia.contrib.connected_components(img, num_iterations=10)
@@ -109,12 +109,85 @@ class TestConnectedComponents(BaseTester):
label_a = out[0, 0, 2051, 0]
label_b = out[0, 0, 2053, 0]
+ assert out.dtype == torch.int64
assert label_a != label_b, "two disconnected components must not share a label"
- def test_gradcheck(self, device):
- B, C, H, W = 2, 1, 4, 4
- img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- self.gradcheck(kornia.contrib.connected_components, (img,))
+ def test_labels_carry_no_gradient(self, device):
+ img = torch.ones(2, 1, 4, 5, device=device, dtype=torch.float32, requires_grad=True)
+ out = kornia.contrib.connected_components(img)
+ assert out.requires_grad is False
+ assert out.dtype == torch.int64
+
+ @pytest.mark.parametrize("in_dtype", [torch.float32, torch.float16, torch.bfloat16, torch.bool, torch.uint8])
+ def test_int64_labels_keep_distinct_components_apart(self, in_dtype, device):
+ # R3 / B-4 / B-5: float16 gave both pixels 2604.0, bool collapsed every label to True.
+ m = torch.zeros(1, 1, 3, 1400, device=device)
+ m[0, 0, 1, 1202] = 1
+ m[0, 0, 1, 1204] = 1
+ out = kornia.contrib.connected_components(m.to(in_dtype), num_iterations=5)
+ assert out.dtype == torch.int64
+ assert out[0, 0, 1, [1202, 1204]].tolist() == [1 * 1400 + 1202 + 1, 1 * 1400 + 1204 + 1]
+
+ def test_uint8_pixel_at_raster_index_255_stays_foreground(self, device):
+ # B-5: uint8 labels wrapped mod 256, so this pixel got label 0 (background).
+ m = torch.zeros(1, 1, 9, 31, dtype=torch.uint8, device=device)
+ m[0, 0, 8, 7] = 1
+ assert kornia.contrib.connected_components(m, num_iterations=3)[0, 0, 8, 7].item() == 8 * 31 + 7 + 1
+
+ def test_ids_stay_exact_past_2_pow_24_pixels(self, device):
+ # B-6: float32 ids merged indices 2**24 - 1 and 2**24 + 1 into 16777216.
+ if device.type == "mps":
+ pytest.skip("MPS has no float64; covered by test_mps_raises_past_2_pow_24_pixels")
+ m = torch.zeros(1, 1, 1, 2**24 + 8, device=device)
+ m[..., 2**24 - 1] = 1
+ m[..., 2**24 + 1] = 1
+ out = kornia.contrib.connected_components(m, num_iterations=2)
+ assert out[0, 0, 0, [2**24 - 1, 2**24 + 1]].tolist() == [2**24, 2**24 + 2]
+
+ def test_batch_labels_are_unique_and_follow_the_flat_raster_index(self, device):
+ # Per-image ids plus an int64 plane offset: label = flattened raster index over the batch + 1.
+ g = torch.Generator().manual_seed(0)
+ img = (torch.rand(4, 1, 5, 7, generator=g) > 0.5).float().to(device)
+ out = kornia.contrib.connected_components(img, num_iterations=3)
+ for b in range(4):
+ single = kornia.contrib.connected_components(img[b : b + 1], num_iterations=3)
+ expected = torch.where(single > 0, single + b * 5 * 7, single)
+ assert torch.equal(out[b : b + 1], expected)
+ full = kornia.contrib.connected_components(torch.ones(3, 1, 5, 7, device=device), num_iterations=10)
+ assert full[:, 0, 0, 0].tolist() == [35, 70, 105]
+
+ def test_batch_past_2_pow_24_pixels_in_total_runs(self, device):
+ # The 2**24 bound is per image: pooling never mixes batch planes. 17 * 1024 * 1000 > 2**24 pixels in total.
+ m = torch.zeros(17, 1, 1024, 1000, device=device)
+ m[16, 0, 5, 3] = 1
+ m[0, 0, 7, 9] = 1
+ out = kornia.contrib.connected_components(m, num_iterations=1)
+ assert out.dtype == torch.int64
+ assert out[16, 0, 5, 3].item() == 16 * 1024 * 1000 + 5 * 1000 + 3 + 1
+ assert out[0, 0, 7, 9].item() == 7 * 1000 + 9 + 1
+ assert int((out > 0).sum()) == 2
+
+ def test_mps_raises_past_2_pow_24_pixels(self, device):
+ if device.type != "mps":
+ pytest.skip("MPS-only bound")
+ with pytest.raises(ValueError, match="2\\*\\*24"):
+ kornia.contrib.connected_components(torch.zeros(1, 1, 1, 2**24 + 8, device=device))
+
+ def test_permuted_batch(self, device, dtype):
+ # B-8: a batch whose leading dims cannot be viewed together crashed on .view.
+ g = torch.Generator().manual_seed(0)
+ img = (torch.rand(3, 2, 1, 5, 7, generator=g) > 0.5).to(device, dtype).permute(1, 0, 2, 3, 4)
+ out = kornia.contrib.connected_components(img)
+ assert out.shape == (2, 3, 1, 5, 7)
+ assert torch.equal(out, kornia.contrib.connected_components(img.contiguous()))
+
+ @pytest.mark.parametrize("shape", [(1, 1, 0, 5), (2, 1, 5, 0), (0, 1, 5, 7), (3, 0, 1, 5, 7)])
+ def test_empty_input(self, shape, device, dtype):
+ # B-9: H = 0 crashed in reshape. Plan review P1: reshape(-1, 1, 0, 5) is itself ambiguous, so the empty
+ # check has to come first.
+ out = kornia.contrib.connected_components(torch.zeros(shape, device=device, dtype=dtype))
+ assert out.shape == shape
+ assert out.dtype == torch.int64
def test_jit(self, device, dtype):
B, C, H, W = 2, 1, 4, 4
diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.py
index b5509a11e..71bbbf91e 100644
--- a/tests/contrib/test_conv_distance_transformer.py
+++ b/tests/contrib/test_conv_distance_transformer.py
@@ -296,6 +296,76 @@ class TestConvDistanceTransform(BaseTester):
with pytest.raises(BaseError, match="too small for kernel_size"):
kornia.contrib.distance_transform(img, kernel_size=3, h=0.01)
+ @pytest.mark.parametrize(
+ ("shape", "kernel_size", "h"),
+ [((1, 1, 40, 50), 31, 0.18), ((1, 1, 40, 50), 31, 0.22), ((1, 1, 12, 40, 50), 21, 0.125)],
+ )
+ def test_h_too_small_for_the_corner_tap_raises(self, shape, kernel_size, h, device):
+ # B-19: the guard checked only the axis tap exp(-k/h); these h passed it while the corner tap
+ # exp(-sqrt(ndim) k/h) underflowed (float32 17.78 vs exact 21.21 at ks 31, h 0.18; MPS vs CPU 4.1 at h 0.22).
+ with pytest.raises(BaseError, match="corner kernel tap"):
+ kornia.contrib.distance_transform(torch.zeros(shape, device=device), kernel_size=kernel_size, h=h)
+
+ @pytest.mark.parametrize(
+ ("shape", "kernel_size", "h"),
+ [
+ ((1, 1, 23, 37), 3, 0.6),
+ ((1, 1, 23, 37), 7, 0.53),
+ ((1, 1, 9, 11, 13), 3, 0.42),
+ ((1, 1, 9, 11, 13), 5, 0.39),
+ ],
+ )
+ def test_h_too_large_raises(self, shape, kernel_size, h, device):
+ # Plan review P3: a pixel counts as reached when -h*log(sum of its window's taps over reached pixels) > 0.
+ # Once the off-centre taps can sum to >= 1, a pixel whose window is full of reached pixels reads as
+ # foreground (0). Random 60 % masks, ks 3: 140 of 2805 background pixels were 0 at h 0.591, 2726 at h 2.0.
+ # Bounds, float32 working precision (float64): 2-D 0.5624 (0.5626) at ks 3, 0.5084 (0.5085) at ks 5, ~0.501 at
+ # ks >= 7; 3-D 0.4070 (0.4071) at ks 3, 0.3843 (0.3844) at ks 5.
+ with pytest.raises(BaseError, match="too large for kernel_size"):
+ kornia.contrib.distance_transform(torch.zeros(shape, device=device), kernel_size=kernel_size, h=h)
+
+ def test_h_below_the_upper_bound_leaves_no_background_pixel_at_zero(self, device):
+ g = torch.Generator().manual_seed(0)
+ m = (torch.rand(8, 1, 23, 37, generator=g) < 0.6).float().to(device)
+ out = kornia.contrib.distance_transform(m, kernel_size=3, h=0.55)
+ assert not ((m == 0) & (out <= 0)).any()
+
+ @pytest.mark.parametrize(
+ ("shape", "accepted", "rejected"), [((1, 1, 7, 7), 0.5, 0.6), ((1, 1, 7, 7, 7), 0.35, 0.42)]
+ )
+ def test_largest_accepted_h_leaves_a_surrounded_background_pixel_nonzero(
+ self, shape, accepted, rejected, device, dtype
+ ):
+ # A background pixel whose whole window is reached sums every off-centre tap. The guard checks that sum in
+ # float64, but the cascade sums it in the working precision: at h=0.56256205 (2-D) the float64 sum is
+ # 0.99999991, float32 rounds it to 1, and the pixel read as foreground (0). Bisect for the largest h the guard
+ # accepts and check the pixel there, so the test pins the guarantee rather than the margin formula.
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip("This device does not support replicate padding for the regression dtype")
+ if not supports_conv2d(device, dtype):
+ pytest.skip("This device does not support convolution for the regression dtype")
+
+ img = torch.ones(shape, device=device, dtype=dtype)
+ img[(0, 0) + (3,) * (len(shape) - 2)] = 0.0
+ largest_out = None
+ for _ in range(50):
+ h = (accepted + rejected) / 2
+ try:
+ out = kornia.contrib.distance_transform(img, kernel_size=3, h=h)
+ except BaseError:
+ rejected = h
+ else:
+ accepted, largest_out = h, out
+ assert largest_out is not None
+ assert largest_out[(0, 0) + (3,) * (len(shape) - 2)] > 0
+
+ @pytest.mark.parametrize(("shape", "h"), [((1, 1, 7, 7), 0.56256205), ((1, 1, 7, 7, 7), 0.40709874)])
+ def test_h_whose_tap_sum_rounds_to_one_raises(self, shape, h, device):
+ # The off-centre taps sum to 0.99999991 (2-D) and 0.99999994 (3-D) in float64 at these h, and to 1 in the
+ # float32 cascade, which float16 and bfloat16 inputs also use.
+ with pytest.raises(BaseError, match="too large for kernel_size"):
+ kornia.contrib.distance_transform(torch.zeros(shape, device=device), kernel_size=3, h=h)
+
def test_dynamo(self, device, dtype, torch_optimizer):
input2d = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)
op = kornia.contrib.distance_transform
diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.py
index a9b792222..9779e0c49 100644
--- a/tests/contrib/test_kmeans.py
+++ b/tests/contrib/test_kmeans.py
@@ -19,6 +19,7 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import BaseError, ShapeError
from testing.base import BaseTester
@@ -109,8 +110,6 @@ class TestKMeans(BaseTester):
assert out2.shape == (num_clusters, D)
def test_exception(self, device, dtype):
- from kornia.core.exceptions import BaseError, ShapeError
-
# case: cluster_center = 0:
with pytest.raises(BaseError) as errinfo:
kornia.contrib.KMeans(0, None, 1e-3, 10, 0)
@@ -247,3 +246,141 @@ class TestKMeans(BaseTester):
self.assert_close(centers, centers_op)
self.assert_close(prediction, prediction_op)
+
+ def _blobs(self, device, dtype):
+ g = torch.Generator().manual_seed(0)
+ return torch.cat(
+ [torch.randn(60, 2, generator=g) + torch.tensor(c) for c in ([0.0, 0.0], [6.0, 0.0], [0.0, 6.0])]
+ ).to(device, dtype)
+
+ def test_zero_tolerance_stops_at_the_fixed_point(self, device, dtype):
+ # B-25: tolerance=0.0 with the default max_iterations=0 never returned.
+ X = self._blobs(device, dtype)
+ km = kornia.contrib.KMeans(3, X[[0, 60, 120]].clone(), tolerance=0.0)
+ calls = {"n": 0}
+ original = km._pairwise_euclidean_distance
+
+ def counting(a, b):
+ calls["n"] += 1
+ if calls["n"] > 200:
+ raise RuntimeError("fit did not stop")
+ return original(a, b)
+
+ km._pairwise_euclidean_distance = counting
+ km.fit(X)
+ assert calls["n"] < 50
+
+ def test_unbounded_configuration_raises(self):
+ with pytest.raises(BaseError, match="max_iterations"):
+ kornia.contrib.KMeans(3, None, tolerance=None, max_iterations=0)
+ with pytest.raises(BaseError, match="tolerance"):
+ kornia.contrib.KMeans(3, None, tolerance=-1.0)
+
+ def test_refit_samples_fresh_initial_centres(self, device, dtype):
+ # B-26: the second fit reused the first fit's sampled centres (and raised for another dimension).
+ km = kornia.contrib.KMeans(3, None, max_iterations=5, seed=0)
+ km.fit(torch.rand(180, 2, device=device, dtype=dtype))
+ X5 = torch.rand(100, 5, device=device, dtype=dtype) + 100
+ km.fit(X5)
+ assert km.cluster_centers.shape == (3, 5)
+ assert (km.cluster_centers >= 100).all()
+
+ def test_float16_distances_do_not_overflow(self, device):
+ # B-29: float16 squared distances overflowed to inf, so argmin returned [0, 0]; float64 gives [1, 0].
+ c = torch.tensor([[0.0, 0.0, 0.0], [100.0, 0.0, 0.0]], device=device, dtype=torch.float16)
+ p = torch.tensor([[255.0, 255.0, 255.0], [10.0, 200.0, 190.0]], device=device, dtype=torch.float16)
+ assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(p).tolist() == [1, 0]
+
+ def test_float16_fit_distances_do_not_overflow(self, device):
+ # B-29 in fit: the same overflow sent both points to cluster 0 and reseeded cluster 1 at random.
+ c = torch.tensor([[0.0, 0.0, 0.0], [100.0, 0.0, 0.0]], device=device, dtype=torch.float16)
+ p = torch.tensor([[255.0, 255.0, 255.0], [10.0, 200.0, 190.0]], device=device, dtype=torch.float16)
+ km = kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1)
+ km.fit(p)
+ self.assert_close(km.cluster_centers, p[[1, 0]], rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize("pixel_dtype", [torch.uint8, torch.int64])
+ def test_predict_integer_input_with_float_centres(self, device, pixel_dtype):
+ # Colour quantisation: fit on float pixels, predict integer pixels. The float centres must not be cast to the
+ # integer dtype (uint8 wraps, int64 truncates). Reference: torch.cdist in float64 on the CPU.
+ g = torch.Generator().manual_seed(0)
+ Xf = (torch.rand(500, 3, generator=g) * 255).round()
+ centres = Xf[:8].clone()
+ km = kornia.contrib.KMeans(8, centres.to(device), tolerance=1e-4, max_iterations=50)
+ km.fit(Xf.to(device))
+ expected = torch.cdist(Xf.double(), km.cluster_centers.cpu().double()).argmin(-1)
+ got = km.predict(Xf.to(pixel_dtype).to(device)).cpu()
+ assert torch.equal(got, expected)
+
+ @pytest.mark.parametrize("pixel_dtype", [torch.uint8, torch.int64])
+ def test_predict_does_not_truncate_the_float_centres(self, device, pixel_dtype):
+ # Casting the centres to the pixel dtype truncates 0.9 to 0 and ties the two centres (argmin keeps index 0).
+ c = torch.tensor([[0.0, 0.0], [0.9, 0.9]], device=device)
+ p = torch.tensor([[1, 1]], dtype=pixel_dtype, device=device)
+ assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(p).tolist() == [1]
+
+ def test_uint8_centres_and_points_are_compared_without_wrapping(self, device):
+ # uint8 differences and squares wrap: in uint8 the pixel (40, 40) looks nearest to (200, 200), but (0, 0) is.
+ c = torch.tensor([[0, 0], [200, 200]], dtype=torch.uint8, device=device)
+ p = torch.tensor([[40, 40]], dtype=torch.uint8, device=device)
+ assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(p).tolist() == [0]
+
+ def test_fit_uint8_points_with_float_centres_does_not_wrap_the_centres(self, device):
+ c = torch.tensor([[300.0, 300.0], [100.0, 100.0]], device=device)
+ p = torch.tensor([[250, 250], [90, 90]], dtype=torch.uint8, device=device)
+ km = kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1)
+ km.fit(p)
+ assert km.cluster_centers.tolist() == [[250, 250], [90, 90]]
+
+ def test_fit_sums_uint8_points_without_wrapping(self, device):
+ # uint8 sums wrap: the mean of 200 and 210 came out as 77. Two empty-cluster-free clusters, one update.
+ c = torch.tensor([[205.0, 205.0], [5.0, 5.0]], device=device)
+ p = torch.tensor([[200, 200], [210, 210], [4, 4]], dtype=torch.uint8, device=device)
+ km = kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1)
+ km.fit(p)
+ assert km.cluster_centers.tolist() == [[205, 205], [4, 4]]
+
+ def test_predict_int64_values_above_2_pow_24_stay_exact(self, device):
+ # Integer data against integer centres is compared in int64: float32 maps both centres to 16777216.
+ c = torch.tensor([[16777216], [16777217]], dtype=torch.int64, device=device)
+ x = torch.tensor([[16777217]], dtype=torch.int64, device=device)
+ assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(x).tolist() == [1]
+
+ def test_predict_integer_squared_distances_are_not_rounded_through_float32_sqrt(self, device):
+ # Squared distances 10**8 and 10**8 + 1 have the same float32 square root; the nearest centre is index 1.
+ c = torch.tensor([[10000, 1], [10000, 0]], dtype=torch.int64, device=device)
+ x = torch.tensor([[0, 0]], dtype=torch.int64, device=device)
+ assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(x).tolist() == [1]
+
+ def test_fit_int64_mean_above_2_pow_24_stays_exact(self, device):
+ # The sum 33554434 is not a float32 value (it rounds to 33554432), so a float mean would give 16777216.
+ probe = torch.div(
+ torch.tensor([33554434], device=device), torch.tensor([2], device=device), rounding_mode="trunc"
+ )
+ if probe.item() != 16777217:
+ pytest.skip("this torch/device computes int64 trunc division through float32 (MPS, torch 2.5)")
+ x = torch.tensor([[16777217], [16777217], [5]], dtype=torch.int64, device=device)
+ c = torch.tensor([[16777217], [5]], dtype=torch.int64, device=device)
+ km = kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1)
+ km.fit(x)
+ assert km.cluster_centers.tolist() == [[16777217], [5]]
+
+ def test_integer_zero_tolerance_shift_does_not_wrap(self, device):
+ # The first update gives [[16], [208]]; its squared shifts (16**2, 80**2) are 0 mod 256, so a uint8 shift
+ # stopped the fit there, although the next update gives [[37], [240]].
+ x = torch.tensor([[0], [32], [80], [240], [240], [240], [240]], dtype=torch.uint8, device=device)
+ c = torch.tensor([[0], [128]], dtype=torch.uint8, device=device)
+ km = kornia.contrib.KMeans(2, c, tolerance=0.0)
+ km.fit(x)
+ assert km.cluster_centers.tolist() == [[37], [240]]
+
+ def test_negative_max_iterations_raises(self):
+ with pytest.raises(BaseError, match="max_iterations must be >= 0"):
+ kornia.contrib.KMeans(3, None, tolerance=None, max_iterations=-1)
+ with pytest.raises(BaseError, match="max_iterations must be >= 0"):
+ kornia.contrib.KMeans(3, None, tolerance=1e-3, max_iterations=-2)
+
+ def test_predict_checks_its_input_rank(self, device, dtype):
+ km = kornia.contrib.KMeans(2, torch.rand(2, 2, device=device, dtype=dtype), max_iterations=1)
+ with pytest.raises(ShapeError):
+ km.predict(torch.rand(4, 2, 1, device=device, dtype=dtype))
diff --git a/tests/contrib/test_lambda_module.py b/tests/contrib/test_lambda_module.py
index 4b66f1063..04ee8aae8 100644
--- a/tests/contrib/test_lambda_module.py
+++ b/tests/contrib/test_lambda_module.py
@@ -61,3 +61,7 @@ class TestLambdaModule(BaseTester):
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
func = kornia.color.bgr_to_grayscale
self.gradcheck(kornia.contrib.Lambda(func), (img,))
+
+ def test_non_callable_message_names_the_parameter(self):
+ with pytest.raises(TypeError, match="func should be callable"):
+ kornia.contrib.Lambda(3)