π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(contrib): exact block-based connected components in pure PyTorch (#4666)
trueoneplusone92b340547d5c
diff --git a/benchmarks/contrib/connected_components.md b/benchmarks/contrib/connected_components.mdnew file mode 100644index 000000000..ed4182aa1--- /dev/null+++ b/benchmarks/contrib/connected_components.md@@ -0,0 +1,173 @@+# Exact block-based connected components++`kornia.contrib.connected_components_union_find` is an opt-in pure PyTorch+alternative to fixed-count max-pool label propagation. It addresses the+pure-PyTorch direction discussed in [#3657](https://github.com/kornia/kornia/issues/3657).+The block contraction is based on Allegretti, Bolelli and Grana,+[Optimized Block-Based Algorithms to Label Connected Components on GPUs](https://doi.org/10.1109/TPDS.2019.2934683),+TPDS 31(2), 423β438. This is a tensor adaptation, not a reproduction of the+paper's CUDA BUF/BKE kernels or their published performance.++## Why this algorithm++Max pooling moves a label by at most one edge per iteration. The required budget+depends on the foreground graph, not just the image dimensions. A 33Γ65 snake+in this benchmark needs 1,088 iterations; the default 100 produces several+labels for a single component. Choosing a large constant wastes work on other+masks and still cannot guarantee correctness for arbitrary inputs.++The new API runs to convergence and returns `int64`, avoiding float label+collisions for half-precision masks. The old API, iteration behavior and output+dtype are unchanged. Component IDs differ between the APIs; compare partitions.++## Correctness invariants++1. All foreground pixels in a 2Γ2 block are 8-connected, including diagonals.+ Contracting them to one graph vertex preserves the component partition.+2. The four predecessor directions cover every possible undirected edge between+ blocks exactly once: left, above, above-left and above-right. Horizontal and+ vertical edges require foreground on both touching sides; diagonal edges+ require both touching corner pixels. A nonempty neighboring block alone is+ insufficient. Odd dimensions are padded with background, and batches have+ disjoint index ranges and no cross-image edges.+3. Parents initially equal their own indices. A reduction hooks only roots,+ always toward a smaller index. This cannot create a cycle or split a tree.+ If several edges compete for a root, the smallest proposal wins and the+ remaining edges are reconsidered in the next round.+4. Pointer jumping compresses every path before the next root-hooking round.+ Each nonterminal round strictly decreases at least one nonnegative parent.+ At termination every original edge joins equal roots, so precisely the+ connected components share a root. Their root is their minimum block index.++The implementation keeps fixed-size edge arrays, representing missing edges as+self-loops. This avoids dynamic `nonzero` output allocation during edge+construction, but uses more memory than sparse edge storage. Working memory is+O(BHW). The scalar convergence checks synchronize CPU and accelerator: this API+does not support CUDA graph capture or fullgraph compilation. It is discrete+and has no gradients. No new runtime dependency or compiled extension is needed.++## Validation++The dependency-free pytest suite uses an independent stack-based flood fill and+exhausts every 3Γ3, 2Γ4 and 4Γ2 binary mask. It also checks random masks, snakes,+diagonal paths, distinct IDs across batch axes, odd sizes, noncontiguous input,+empty shapes, singleton blocks, boolean/integer inputs, exact foreground+selection and half-precision ID collisions. CPU/CUDA and all four floating+dtypes are exercised; CUDA half tests run in isolated subprocesses.++An additional SciPy check exhausts all 65,536 4Γ4 binary masks (103,696 foreground+components). Reproduce from the repository root with SciPy installed:++```python+import numpy as np+import torch+from scipy.ndimage import label+from kornia.contrib import connected_components_union_find++values = torch.arange(65536)+mask = ((values[:, None] >> torch.arange(16)) & 1).reshape(-1, 1, 4, 4)+actual = connected_components_union_find(mask).numpy()[:, 0]+structure = np.zeros((3, 3, 3), dtype=int)+structure[1] = 1 # No connections across the batch axis.+expected, count = label(mask[:, 0].numpy(), structure=structure)+pairs = np.unique(np.stack((actual.ravel(), expected.ravel()), axis=1), axis=0)+assert len(pairs) == len(np.unique(actual)) == count + 1+assert np.array_equal(actual != 0, expected != 0)+```++## Benchmark method++Run `python -m benchmarks.contrib.connected_components` from each checkout root.+The harness prints the interpreter and imported Kornia paths so an editable+install cannot silently invalidate the A/B comparison. On the base checkout,+copy the unchanged benchmark script into the same untracked relative path;+it detects the missing new API and benchmarks pooling only.++Both APIs receive the same resident float32 tensors. Seeds are pinned. Timing+uses `benchmarks/common.py` (`blocked_autorange`, warmup, synchronized device+execution, median and IQR). Correctness is checked against SciPy outside timing+by establishing a bijection between label IDs. Transfers and reference labeling+are excluded. The optional `--calibrate` search finds the minimum correct pooling+budget outside timing. This favors pooling with an oracle unavailable in normal+use, rather than inflating speedups with an arbitrary overlarge budget.++The `pool100` rows show the existing default, including its incorrect partitions.+Only correct `pool_calibrated` rows are used for equivalent-result comparisons.+CUDA peak allocation includes the output and temporary tensors above the+resident input, excluding allocator cache. CPU performance is measured with one+thread. These synthetic cases characterize algorithmic regimes, not downstream+segmentation accuracy or end-to-end application performance.++Commands (append `--json PATH` to save metadata and raw rows):++```text+python -m benchmarks.contrib.connected_components --device cpu --sizes 256 --calibrate --min-run-time 2+python -m benchmarks.contrib.connected_components --device cuda --sizes 256 1024 --calibrate+python -m benchmarks.contrib.connected_components --device cuda --sizes 256 --batch 4 --calibrate+```++## Results++Measured 2026-09-19 on Windows 11, AMD EPYC 9654 (one PyTorch CPU thread),+NVIDIA RTX 5090, Python 3.13.5, PyTorch 2.10.0+cu130, NumPy 2.1.3 and+SciPy 1.15.3. Base: `e1b79c2`; implementation and benchmark: `8041e8e`.+CPU autorange used at least 2 seconds; CUDA at least 1 second.+Raw A/B results: [connected_components_results](connected_components_results/).++All union-find rows match SciPy. The default 100-step pool fails on both dense+sizes, the snake and the 1024 random mask. Ratios below compare the two correct+methods within the implementation run. Values are median / IQR milliseconds;+a speedup below 1 means union-find loses.+++### CUDA, batch 1++| Mask | Minimum pool steps | Pool ms / IQR | Union-find ms / IQR | Speedup |+| --- | ---: | ---: | ---: | ---: |+| dense 256x256 | 255 | 9.352 / 0.077 | 2.101 / 0.023 | 4.45x |+| random 256x256 | 95 | 3.555 / 0.079 | 3.573 / 0.073 | 1.00x |+| isolated 256x256 | 1 | 0.154 / 0.001 | 1.089 / 0.009 | 0.14x |+| snake 33x65 | 1088 | 38.439 / 1.356 | 2.744 / 0.018 | 14.01x |+| dense 1024x1024 | 1023 | 35.136 / 0.602 | 2.913 / 0.019 | 12.06x |+| random 1024x1024 | 197 | 6.918 / 0.065 | 4.480 / 0.078 | 1.54x |+| isolated 1024x1024 | 1 | 0.152 / 0.002 | 1.123 / 0.008 | 0.14x |++### CPU, batch 1++| Mask | Minimum pool steps | Pool ms / IQR | Union-find ms / IQR | Speedup |+| --- | ---: | ---: | ---: | ---: |+| dense 256x256 | 255 | 515.523 / 9.786 | 2.518 / 0.041 | 204.76x |+| random 256x256 | 95 | 340.587 / 2.054 | 5.308 / 0.042 | 64.16x |+| isolated 256x256 | 1 | 2.300 / 0.014 | 1.621 / 0.019 | 1.42x |+| snake 33x65 | 1088 | 90.508 / 2.612 | 0.518 / 0.005 | 174.64x |++### CUDA, batch 4++| Mask | Minimum pool steps | Pool ms / IQR | Union-find ms / IQR | Speedup |+| --- | ---: | ---: | ---: | ---: |+| dense 256x256 | 255 | 8.993 / 0.198 | 2.122 / 0.005 | 4.24x |+| random 256x256 | 152 | 5.437 / 0.090 | 3.736 / 0.085 | 1.46x |+| isolated 256x256 | 1 | 0.154 / 0.002 | 1.123 / 0.013 | 0.14x |+| snake 33x65 | 1088 | 38.797 / 0.930 | 2.735 / 0.023 | 14.19x |++### Interpretation and limits++The 1024x1024 dense case is about 12x faster and the small snake about 14x+faster on this GPU than an oracle-tuned correct pooling run. The random 256 mask+is effectively a tie; isolated pixels are about 7x slower than a known one-step+pooling budget. This is why the new API is opt-in rather than a default replacement.+CPU results reflect PyTorch's pooling/reduction implementations on this machine;+they are not a comparison against optimized native CPU CCL implementations.++Peak extra allocated CUDA memory at 1024x1024 is 17.0 MiB for pooling and+57.0-59.0 MiB for union-find (output included), roughly 3.5x higher. Block contraction+reduces the graph size but the tensor edge arrays, root proposals and integer+output still add memory. This matters for high-resolution batches.++Unchanged pooling code varies between separate base and branch measurements:+the 1024 dense calibrated pool is 48.491 ms on base and 35.136 ms in the branch+run. The raw base results disclose this run-to-run variation; headline ratios use+the paired branch measurements. Re-run on the intended hardware before using+these numbers for a deployment decision. MPS/TPU, minimum-supported PyTorch,+natural-image datasets and end-to-end segmentation pipelines have not been+benchmarked here.diff --git a/benchmarks/contrib/connected_components.py b/benchmarks/contrib/connected_components.pynew file mode 100644index 000000000..389f85957--- /dev/null+++ b/benchmarks/contrib/connected_components.py@@ -0,0 +1,172 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Compare exact block CCL and pooling, validating partitions with optional SciPy.++Run from the repository root: python -m benchmarks.contrib.connected_components+--device cuda --sizes 256 1024 --calibrate --json results.json++Both backends receive identical resident float32 masks. Reference validation and+transfers to CPU are outside timing. --calibrate finds the minimum *correct*+pooling budget by doubling then binary search against SciPy, outside timing.+This oracle-tuned baseline favors pooling: users normally do not know this+budget. The default 100-iteration baseline is also measured, but incorrect+partitions must never be treated as equivalent-work speedups. SciPy itself is+not timed because it labels host arrays, whereas these APIs label device tensors.+CUDA rows include peak allocated bytes above the resident input, including the+output and temporary tensors but excluding the allocator's reserved cache.+"""++from __future__ import annotations++import argparse+import sys+from functools import partial+from pathlib import Path++import torch++import kornia++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from common import run_metadata, save_json, time_us+++def reference_labels(image):+ try:+ import numpy as np+ from scipy.ndimage import label+ except ImportError:+ return None+ return [label(mask, structure=np.ones((3, 3)))[0] for mask in image[:, 0].cpu().numpy()]+++def same_partition(labels, references):+ if references is None:+ return None+ import numpy as np++ for actual, expected in zip(labels[:, 0].cpu().numpy(), references):+ if not np.array_equal(actual != 0, expected != 0):+ return False+ # A bijection between actual and reference IDs establishes equality of+ # partitions, independent of their particular numerical label values.+ pairs = np.unique(np.stack((actual.ravel(), expected.ravel()), axis=1), axis=0)+ if len(pairs) != len(np.unique(actual)) or len(pairs) != len(np.unique(expected)):+ return False+ return True+++def minimum_iterations(image, reference):+ low, high = 0, 1+ maximum = image.shape[-2] * image.shape[-1]+ while not same_partition(kornia.contrib.connected_components(image, high), reference):+ low, high = high, min(high * 2, maximum)+ if low == high:+ raise RuntimeError("Pooling did not match the reference even at the pixel-count budget")+ while high - low > 1:+ middle = (high + low) // 2+ if same_partition(kornia.contrib.connected_components(image, middle), reference):+ high = middle+ else:+ low = middle+ return high+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--device", default="cpu")+ parser.add_argument("--sizes", type=int, nargs="+", default=[256, 1024])+ parser.add_argument("--batch", type=int, default=1)+ parser.add_argument("--calibrate", action="store_true")+ parser.add_argument("--min-run-time", type=float, default=1.0)+ parser.add_argument("--json", type=Path)+ args = parser.parse_args()+ device = torch.device(args.device)+ torch.set_num_threads(1)+ print(f"Python: {sys.executable}\nKornia: {kornia.__file__}", flush=True)+ metadata = run_metadata(device)+ print(metadata, flush=True)+ results = []+ for size in args.sizes:+ for case in ("dense", "random", "isolated", "snake"):+ generator = torch.Generator().manual_seed(0)+ height, width = (33, 65) if case == "snake" else (size, size)+ if case == "snake" and size != args.sizes[0]:+ continue+ image = torch.zeros(args.batch, 1, height, width)+ if case == "dense":+ image.fill_(1)+ elif case == "random":+ image = (torch.rand(image.shape, generator=generator) < 0.35).float()+ elif case == "isolated":+ image[..., ::2, ::2] = 1+ else:+ image[..., ::2, :] = 1+ image[..., 1::4, -1] = 1+ image[..., 3::4, 0] = 1+ image = image.to(device)+ reference = reference_labels(image)+ if reference is None:+ print("SciPy unavailable: skipping partition validation and calibration", flush=True)+ methods = [("pool100", 100)]+ if args.calibrate and reference is not None:+ methods.append(("pool_calibrated", minimum_iterations(image, reference)))+ if hasattr(kornia.contrib, "connected_components_union_find"):+ methods.append(("block_union_find", None))+ for backend, iterations in methods:+ if iterations is None:+ operation = partial(kornia.contrib.connected_components_union_find, image)+ else:+ operation = partial(kornia.contrib.connected_components, image, iterations)+ correct = same_partition(operation(), reference)+ if backend == "block_union_find" and correct is False:+ raise AssertionError(f"Incorrect partition: {case}, {size}")+ sync = torch.mps.synchronize if device.type == "mps" else None+ median, iqr = time_us(operation, min_run_time=args.min_run_time, sync=sync)+ peak_extra_bytes = None+ if device.type == "cuda":+ torch.cuda.synchronize(device)+ allocated = torch.cuda.memory_allocated(device)+ torch.cuda.reset_peak_memory_stats(device)+ output = operation()+ torch.cuda.synchronize(device)+ peak_extra_bytes = torch.cuda.max_memory_allocated(device) - allocated+ del output+ row = {+ "op": "connected_components",+ "backend": backend,+ "case": case,+ "batch": args.batch,+ "height": height,+ "width": width,+ "dtype": "float32",+ "iterations": iterations,+ "correct": correct,+ "median_us": median,+ "iqr_us": iqr,+ "peak_extra_bytes": peak_extra_bytes,+ "throughput_per_s": args.batch * 1e6 / median,+ }+ results.append(row)+ print(row, flush=True)+ if args.json:+ save_json(args.json, metadata, results)+++if __name__ == "__main__":+ main()diff --git a/benchmarks/contrib/connected_components_results/8041e8e_cpu.json b/benchmarks/contrib/connected_components_results/8041e8e_cpu.jsonnew file mode 100644index 000000000..4b9a5f64d--- /dev/null+++ b/benchmarks/contrib/connected_components_results/8041e8e_cpu.json@@ -0,0 +1,202 @@+{+ "metadata": {+ "albumentations": null,+ "device": "cpu",+ "git_commit": "8041e8e",+ "kornia": "0.9.0rc1",+ "kornia_rs": "0.1.14",+ "machine": "AMD64",+ "numpy": "2.1.3",+ "opencv": "4.12.0",+ "pillow": "11.1.0",+ "platform": "Windows-11-10.0.22631-SP0",+ "python": "3.13.5",+ "skimage": "0.25.0",+ "timestamp_utc": "2026-09-19T00:28:35+00:00",+ "torch": "2.10.0+cu130",+ "torch_num_threads": 1,+ "torchvision": "0.25.0+cu130"+ },+ "results": [+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 2194.40006185323,+ "iterations": 100,+ "median_us": 153279.69996724278,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 6.524021120955409,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 9786.025097128004,+ "iterations": 255,+ "median_us": 515523.4499834478,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 1.9397759695162413,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 40.637500933371655,+ "iterations": null,+ "median_us": 2517.7249975968152,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 397.18396606242004,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 1742.5250262022018,+ "iterations": 100,+ "median_us": 354663.3000369184,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 2.819575636655684,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 2054.1999547276646,+ "iterations": 95,+ "median_us": 340586.50000952184,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 2.936111677861697,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 41.55499627813645,+ "iterations": null,+ "median_us": 5308.089999016374,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 188.3916814118274,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 3069.0249986946583,+ "iterations": 100,+ "median_us": 202655.10003082454,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 4.934492148719161,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 13.84500064887089,+ "iterations": 1,+ "median_us": 2300.2360004466027,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 434.7380007120334,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 18.77299975603817,+ "iterations": null,+ "median_us": 1620.9290002007037,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 616.9301677471251,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "snake",+ "correct": false,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 92.71501330658863,+ "iterations": 100,+ "median_us": 7759.3049965798855,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 128.87752194826416,+ "width": 65+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 2611.699979752302,+ "iterations": 1088,+ "median_us": 90507.69999157637,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 11.048783695675294,+ "width": 65+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 4.5005010906606655,+ "iterations": null,+ "median_us": 518.2399996556342,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 1929.6079049561806,+ "width": 65+ }+ ]+}diff --git a/benchmarks/contrib/connected_components_results/8041e8e_cuda.json b/benchmarks/contrib/connected_components_results/8041e8e_cuda.jsonnew file mode 100644index 000000000..d63370533--- /dev/null+++ b/benchmarks/contrib/connected_components_results/8041e8e_cuda.json@@ -0,0 +1,339 @@+{+ "metadata": {+ "albumentations": null,+ "cuda_device": "NVIDIA GeForce RTX 5090",+ "cuda_version": "13.0",+ "device": "cuda",+ "git_commit": "8041e8e",+ "kornia": "0.9.0rc1",+ "kornia_rs": "0.1.14",+ "machine": "AMD64",+ "numpy": "2.1.3",+ "opencv": "4.12.0",+ "pillow": "11.1.0",+ "platform": "Windows-11-10.0.22631-SP0",+ "python": "3.13.5",+ "skimage": "0.25.0",+ "timestamp_utc": "2026-09-19T00:31:33+00:00",+ "torch": "2.10.0+cu130",+ "torch_num_threads": 1,+ "torchvision": "0.25.0+cu130"+ },+ "results": [+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 84.2650071717797,+ "iterations": 100,+ "median_us": 3813.1700013764203,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 262.24899483606424,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 76.70500199310516,+ "iterations": 255,+ "median_us": 9351.689997129142,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 106.93254377625735,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 22.672000341117382,+ "iterations": null,+ "median_us": 2101.45799908787,+ "op": "connected_components",+ "peak_extra_bytes": 3844096,+ "throughput_per_s": 475.86009353222676,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 61.24000065028641,+ "iterations": 100,+ "median_us": 3702.960000373423,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 270.05422686152576,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 79.1899976320563,+ "iterations": 95,+ "median_us": 3555.3100053220987,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 281.2694247486313,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 72.64500018209228,+ "iterations": null,+ "median_us": 3572.509996592999,+ "op": "connected_components",+ "peak_extra_bytes": 3844096,+ "throughput_per_s": 279.9152419317711,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 111.10999330412588,+ "iterations": 100,+ "median_us": 3691.239998443052,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 270.91167207274395,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 1.4880500384606357,+ "iterations": 1,+ "median_us": 154.09259998705238,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 6489.604303412525,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 8.979249687399767,+ "iterations": null,+ "median_us": 1088.7985001318157,+ "op": "connected_components",+ "peak_extra_bytes": 3713024,+ "throughput_per_s": 918.4435870171889,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "snake",+ "correct": false,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 101.46499844267998,+ "iterations": 100,+ "median_us": 3715.750004630536,+ "op": "connected_components",+ "peak_extra_bytes": 37376,+ "throughput_per_s": 269.12467166892515,+ "width": 65+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 1355.7250786107033,+ "iterations": 1088,+ "median_us": 38438.650022726506,+ "op": "connected_components",+ "peak_extra_bytes": 37376,+ "throughput_per_s": 26.01548179784563,+ "width": 65+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 17.826750408857748,+ "iterations": null,+ "median_us": 2744.2740002879873,+ "op": "connected_components",+ "peak_extra_bytes": 130048,+ "throughput_per_s": 364.39510045099684,+ "width": 65+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 46.39999242499454,+ "iterations": 100,+ "median_us": 3565.7400032505393,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 280.4466952409309,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 601.6000406816602,+ "iterations": 1023,+ "median_us": 35135.80001890659,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 28.46099987653332,+ "width": 1024+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 18.664000090211527,+ "iterations": null,+ "median_us": 2912.5259997090325,+ "op": "connected_components",+ "peak_extra_bytes": 61850624,+ "throughput_per_s": 343.3445744690012,+ "width": 1024+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": false,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 74.88500850740812,+ "iterations": 100,+ "median_us": 3617.349994601682,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 276.4454646335966,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 64.78500436060078,+ "iterations": 197,+ "median_us": 6917.789997532964,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 144.5548362058724,+ "width": 1024+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 77.94999983161671,+ "iterations": null,+ "median_us": 4480.330005753785,+ "op": "connected_components",+ "peak_extra_bytes": 61894656,+ "throughput_per_s": 223.19784451497267,+ "width": 1024+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 70.48001280054442,+ "iterations": 100,+ "median_us": 3560.6299992650747,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 280.84917562521326,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 1.566750055644674,+ "iterations": 1,+ "median_us": 152.20490004867315,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 6570.090711141448,+ "width": 1024+ },+ {+ "backend": "block_union_find",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 8.30500037409367,+ "iterations": null,+ "median_us": 1122.7750009857118,+ "op": "connected_components",+ "peak_extra_bytes": 59801600,+ "throughput_per_s": 890.650396670816,+ "width": 1024+ }+ ]+}diff --git a/benchmarks/contrib/connected_components_results/8041e8e_cuda_batch4.json b/benchmarks/contrib/connected_components_results/8041e8e_cuda_batch4.jsonnew file mode 100644index 000000000..67a3a3597--- /dev/null+++ b/benchmarks/contrib/connected_components_results/8041e8e_cuda_batch4.json@@ -0,0 +1,204 @@+{+ "metadata": {+ "albumentations": null,+ "cuda_device": "NVIDIA GeForce RTX 5090",+ "cuda_version": "13.0",+ "device": "cuda",+ "git_commit": "8041e8e",+ "kornia": "0.9.0rc1",+ "kornia_rs": "0.1.14",+ "machine": "AMD64",+ "numpy": "2.1.3",+ "opencv": "4.12.0",+ "pillow": "11.1.0",+ "platform": "Windows-11-10.0.22631-SP0",+ "python": "3.13.5",+ "skimage": "0.25.0",+ "timestamp_utc": "2026-09-19T00:33:03+00:00",+ "torch": "2.10.0+cu130",+ "torch_num_threads": 1,+ "torchvision": "0.25.0+cu130"+ },+ "results": [+ {+ "backend": "pool100",+ "batch": 4,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 90.48999636434002,+ "iterations": 100,+ "median_us": 3667.035000398755,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 1090.7995150210015,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 4,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 197.58250273298367,+ "iterations": 255,+ "median_us": 8993.23000921868,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 444.7790166491599,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 4,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 4.505999386310386,+ "iterations": null,+ "median_us": 2122.2410001792014,+ "op": "connected_components",+ "peak_extra_bytes": 15368192,+ "throughput_per_s": 1884.800076740691,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 4,+ "case": "random",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 85.62999428249948,+ "iterations": 100,+ "median_us": 3613.414999563247,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 1106.9860507258313,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 4,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 90.24500031955523,+ "iterations": 152,+ "median_us": 5436.740000732243,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 735.7350175769419,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 4,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 84.60000390186906,+ "iterations": null,+ "median_us": 3735.8899950049818,+ "op": "connected_components",+ "peak_extra_bytes": 15368192,+ "throughput_per_s": 1070.6953377503467,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 4,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 56.44001066684723,+ "iterations": 100,+ "median_us": 3608.0600053537637,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 1108.6290122849016,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 4,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 1.6345000476576643,+ "iterations": 1,+ "median_us": 153.73439993709326,+ "op": "connected_components",+ "peak_extra_bytes": 4456448,+ "throughput_per_s": 26018.900139700447,+ "width": 256+ },+ {+ "backend": "block_union_find",+ "batch": 4,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 12.629000702872768,+ "iterations": null,+ "median_us": 1122.8740005753934,+ "op": "connected_components",+ "peak_extra_bytes": 14843904,+ "throughput_per_s": 3562.287485461666,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 4,+ "case": "snake",+ "correct": false,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 59.77500113658624,+ "iterations": 100,+ "median_us": 3672.4899953696877,+ "op": "connected_components",+ "peak_extra_bytes": 147456,+ "throughput_per_s": 1089.1792775591603,+ "width": 65+ },+ {+ "backend": "pool_calibrated",+ "batch": 4,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 930.2750113420188,+ "iterations": 1088,+ "median_us": 38796.900073066354,+ "op": "connected_components",+ "peak_extra_bytes": 147456,+ "throughput_per_s": 103.10102076368948,+ "width": 65+ },+ {+ "backend": "block_union_find",+ "batch": 4,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 23.06800044607352,+ "iterations": null,+ "median_us": 2734.7249997546896,+ "op": "connected_components",+ "peak_extra_bytes": 510464,+ "throughput_per_s": 1462.6699212384456,+ "width": 65+ }+ ]+}diff --git a/benchmarks/contrib/connected_components_results/e1b79c2_cpu.json b/benchmarks/contrib/connected_components_results/e1b79c2_cpu.jsonnew file mode 100644index 000000000..7c3b7e6b9--- /dev/null+++ b/benchmarks/contrib/connected_components_results/e1b79c2_cpu.json@@ -0,0 +1,142 @@+{+ "metadata": {+ "albumentations": null,+ "device": "cpu",+ "git_commit": "e1b79c2",+ "kornia": "0.9.0rc1",+ "kornia_rs": "0.1.14",+ "machine": "AMD64",+ "numpy": "2.1.3",+ "opencv": "4.12.0",+ "pillow": "11.1.0",+ "platform": "Windows-11-10.0.22631-SP0",+ "python": "3.13.5",+ "skimage": "0.25.0",+ "timestamp_utc": "2026-09-19T00:27:04+00:00",+ "torch": "2.10.0+cu130",+ "torch_num_threads": 1,+ "torchvision": "0.25.0+cu130"+ },+ "results": [+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 2685.6748736463487,+ "iterations": 100,+ "median_us": 144242.90001625195,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 6.932750242038459,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 2735.3499899618328,+ "iterations": 255,+ "median_us": 546458.8000904769,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 1.8299641250802998,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 4434.424918144941,+ "iterations": 100,+ "median_us": 387206.20004460216,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 2.5826032741335503,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 16362.325026420876,+ "iterations": 95,+ "median_us": 350660.9000614844,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 2.8517579228954846,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 15005.400055088103,+ "iterations": 100,+ "median_us": 230221.80004045367,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 4.343637308996298,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 18.05200125090797,+ "iterations": 1,+ "median_us": 2308.0390004906803,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 433.26824190899885,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "snake",+ "correct": false,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 79.15750320535223,+ "iterations": 100,+ "median_us": 7874.234998598694,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 126.99646380606636,+ "width": 65+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 2458.7499792687595,+ "iterations": 1088,+ "median_us": 89927.49999742955,+ "op": "connected_components",+ "peak_extra_bytes": null,+ "throughput_per_s": 11.120068944745308,+ "width": 65+ }+ ]+}diff --git a/benchmarks/contrib/connected_components_results/e1b79c2_cuda.json b/benchmarks/contrib/connected_components_results/e1b79c2_cuda.jsonnew file mode 100644index 000000000..8b7dee0d0--- /dev/null+++ b/benchmarks/contrib/connected_components_results/e1b79c2_cuda.json@@ -0,0 +1,234 @@+{+ "metadata": {+ "albumentations": null,+ "cuda_device": "NVIDIA GeForce RTX 5090",+ "cuda_version": "13.0",+ "device": "cuda",+ "git_commit": "e1b79c2",+ "kornia": "0.9.0rc1",+ "kornia_rs": "0.1.14",+ "machine": "AMD64",+ "numpy": "2.1.3",+ "opencv": "4.12.0",+ "pillow": "11.1.0",+ "platform": "Windows-11-10.0.22631-SP0",+ "python": "3.13.5",+ "skimage": "0.25.0",+ "timestamp_utc": "2026-09-19T00:29:26+00:00",+ "torch": "2.10.0+cu130",+ "torch_num_threads": 1,+ "torchvision": "0.25.0+cu130"+ },+ "results": [+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 93.8900018809365,+ "iterations": 100,+ "median_us": 5831.674998626113,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 171.47732002136445,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 220.5049968324619,+ "iterations": 255,+ "median_us": 14457.599993329495,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 69.16777338295319,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 119.55000227317248,+ "iterations": 100,+ "median_us": 5903.120001312345,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 169.40194334143405,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 67.70249747205509,+ "iterations": 95,+ "median_us": 5644.369998481125,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 177.16769103887515,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 131.28499558661116,+ "iterations": 100,+ "median_us": 5767.899996135384,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 173.37332489641315,+ "width": 256+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 256,+ "iqr_us": 2.3520999820902952,+ "iterations": 1,+ "median_us": 230.8443000074476,+ "op": "connected_components",+ "peak_extra_bytes": 1114112,+ "throughput_per_s": 4331.924158264846,+ "width": 256+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "snake",+ "correct": false,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 185.49999804236012,+ "iterations": 100,+ "median_us": 5855.815001996234,+ "op": "connected_components",+ "peak_extra_bytes": 37376,+ "throughput_per_s": 170.77042216311517,+ "width": 65+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "snake",+ "correct": true,+ "dtype": "float32",+ "height": 33,+ "iqr_us": 1399.6000634506345,+ "iterations": 1088,+ "median_us": 61034.50001683086,+ "op": "connected_components",+ "peak_extra_bytes": 37376,+ "throughput_per_s": 16.384176158144005,+ "width": 65+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "dense",+ "correct": false,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 113.06499072816136,+ "iterations": 100,+ "median_us": 5052.135000005364,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 197.9361200757577,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "dense",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 1614.2999520525336,+ "iterations": 1023,+ "median_us": 48490.700079128146,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 20.622511087036873,+ "width": 1024+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "random",+ "correct": false,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 213.02999521140026,+ "iterations": 100,+ "median_us": 5097.045004367828,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 196.1921072195883,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "random",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 195.76000049710206,+ "iterations": 197,+ "median_us": 9674.159996211529,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 103.368147765967,+ "width": 1024+ },+ {+ "backend": "pool100",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 185.72999397292733,+ "iterations": 100,+ "median_us": 5165.184999350458,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 193.60390772561948,+ "width": 1024+ },+ {+ "backend": "pool_calibrated",+ "batch": 1,+ "case": "isolated",+ "correct": true,+ "dtype": "float32",+ "height": 1024,+ "iqr_us": 1.5658999327570067,+ "iterations": 1,+ "median_us": 227.88979997858405,+ "op": "connected_components",+ "peak_extra_bytes": 17825792,+ "throughput_per_s": 4388.085820839612,+ "width": 1024+ }+ ]+}diff --git a/changelog.d/4666.added.md b/changelog.d/4666.added.mdnew file mode 100644index 000000000..f95c5776f--- /dev/null+++ b/changelog.d/4666.added.md@@ -0,0 +1 @@+Added `kornia.contrib.connected_components_union_find`, an exact, pure PyTorch 8-connected component labeling alternative using 2x2 block union-find. It converges without a user-selected iteration budget and returns integer labels for boolean, integer and floating-point masks, including half precision.diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex e13414d86..91ac3798d 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -243,6 +243,26 @@ Image Segmentation------------------.. autofunction:: connected_components+.. autofunction:: connected_components_union_find++Choosing a labeling method+^^^^^^^^^^^^^^^^^^^^^^^^^^++``connected_components_union_find`` computes the exact 8-connected partition+without an iteration budget. It accepts boolean masks and returns ``int64``+labels, so half-precision inputs do not cause distinct component IDs to collide.+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;+compare their foreground partitions instead of comparing label values directly.+Segment Anything (SAM)^^^^^^^^^^^^^^^^^^^^^^diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 1cd4eecab..70f2c3d50 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -23,7 +23,7 @@ This subpackage provides community-contributed and experimental features.from kornia.models.tiny_vit import TinyViTfrom .augmentation_audit import AugmentationAuditReport, AugmentationAuditStep, SpatialAudit, audit-from .connected_components import connected_components+from .connected_components import connected_components, connected_components_union_findfrom .diamond_square import diamond_squarefrom .distance_transform import DistanceTransform, distance_transformfrom .edge_detection import EdgeDetector, EdgeDetectorBuilder@@ -65,6 +65,7 @@ __all__ = ["combine_tensor_patches","compute_padding","connected_components",+ "connected_components_union_find","diamond_square","distance_transform","extract_tensor_patches",diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.pyindex 956f01d28..f34bc0fc1 100644--- a/kornia/contrib/connected_components.py+++ b/kornia/contrib/connected_components.py@@ -72,3 +72,115 @@ def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torcout = torch.mul(out, mask) # mask using element-wise multiplicationreturn out.to(image.dtype).view_as(image)+++def connected_components_union_find(image: torch.Tensor) -> torch.Tensor:+ r"""Label 8-connected foreground components exactly using block union-find.++ This pure PyTorch implementation contracts each 2x2 block, following the+ block-based approach of Allegretti, Bolelli and Grana, *Optimized Block-Based+ Algorithms to Label Connected Components on GPUs*, TPDS 2020,+ https://doi.org/10.1109/TPDS.2019.2934683. Root hooking with ``scatter_reduce_``+ and pointer jumping replace the paper's custom CUDA union kernels.++ Unlike :func:`connected_components`, this function runs until convergence+ and returns integer labels, including for half-precision inputs. There is+ no iteration budget to choose based on component diameter.++ Args:+ image: Binary image of shape :math:`(*, 1, H, W)`. Boolean, integer and+ floating-point tensors are accepted. Only values equal to 1 are+ foreground, as in :func:`connected_components`.++ Returns:+ A ``torch.int64`` tensor on the input device with the same shape.+ Background is zero. Foreground labels are the minimum 1-based block+ index in each component, in raster order over flattened batches and+ the :math:`\lceil H/2\rceil \times \lceil W/2\rceil` block grid.+ Labels are deterministic and distinct across images, but not contiguous+ and not equal to the labels of the pooling implementation.++ Note:+ This discrete operation is not differentiable. Working memory is linear+ in the number of pixels. Convergence checks synchronize the device with+ the host; CUDA graph capture and ``torch.compile(fullgraph=True)`` are+ not supported. All mask, edge and label computation stays on the input+ device. The existing pooling API remains useful for fixed-work graphs.++ Example:+ >>> mask = torch.tensor([[[1, 0, 0], [0, 0, 1]]], dtype=torch.bool)+ >>> connected_components_union_find(mask)+ tensor([[[1, 0, 0],+ [0, 0, 2]]])++ """+ if not isinstance(image, torch.Tensor):+ raise TypeError(f"Input image is not a torch.Tensor. Got: {type(image)}")+ if image.ndim < 3 or image.shape[-3] != 1:+ raise ValueError(f"Input image shape must be (*,1,H,W). Got: {image.shape}")+ if image.numel() == 0:+ return torch.zeros_like(image, dtype=torch.int64)++ height, width = image.shape[-2:]+ mask = (image == 1).reshape(-1, height, width)+ # MPSGraph's boolean padding can abort the process; allocate the border explicitly.+ padded = mask.new_zeros((mask.shape[0], height + height % 2, width + width % 2))+ padded[:, :height, :width] = mask+ top_left, top_right = padded[:, ::2, ::2], padded[:, ::2, 1::2]+ bottom_left, bottom_right = padded[:, 1::2, ::2], padded[:, 1::2, 1::2]+ # Every pair of foreground pixels inside a 2x2 block is 8-connected.+ # A block may connect to four already-visited neighbors, but only if an+ # actual pair of foreground pixels touches across the shared boundary.+ blocks = torch.arange(top_left.numel(), device=image.device).reshape(top_left.shape)+ left = (top_left[:, :, 1:] | bottom_left[:, :, 1:]) & (top_right[:, :, :-1] | bottom_right[:, :, :-1])+ above = (top_left[:, 1:, :] | top_right[:, 1:, :]) & (bottom_left[:, :-1, :] | bottom_right[:, :-1, :])+ above_left = top_left[:, 1:, 1:] & bottom_right[:, :-1, :-1]+ above_right = top_right[:, 1:, :-1] & bottom_left[:, :-1, 1:]++ sources = torch.cat(+ [+ blocks[:, :, 1:].flatten(),+ blocks[:, 1:, :].flatten(),+ blocks[:, 1:, 1:].flatten(),+ blocks[:, 1:, :-1].flatten(),+ ]+ )+ # Absent edges become self-loops. Fixed-size arrays avoid nonzero/boolean+ # indexing, which would add device synchronizations during edge creation.+ targets = torch.cat(+ [+ torch.where(left, blocks[:, :, :-1], blocks[:, :, 1:]).flatten(),+ torch.where(above, blocks[:, :-1, :], blocks[:, 1:, :]).flatten(),+ torch.where(above_left, blocks[:, :-1, :-1], blocks[:, 1:, 1:]).flatten(),+ torch.where(above_right, blocks[:, :-1, 1:], blocks[:, 1:, :-1]).flatten(),+ ]+ )+ parents = blocks.flatten()+ # Some MPS devices cannot compile int64 atomic min. Keep the forest in+ # int32 when every zero-based block index fits, without narrowing edge indices.+ if image.device.type == "mps" and parents.numel() <= torch.iinfo(torch.int32).max + 1:+ parents = parents.to(torch.int32)+ while True:+ source_roots, target_roots = parents[sources], parents[targets]+ merged = parents.clone()+ merged.scatter_reduce_(+ 0,+ torch.maximum(source_roots, target_roots).long(),+ torch.minimum(source_roots, target_roots),+ reduce="amin",+ )+ # Only roots are hooked and every parent decreases, so cycles cannot+ # form. Fully compress before hooking again: hooking non-roots could+ # detach an already-merged subtree.+ while True:+ compressed = merged[merged.long()]+ if torch.equal(compressed, merged):+ break+ merged = compressed+ if torch.equal(merged, parents):+ break+ parents = merged++ # Widen before reserving zero for background, including the largest int32 root.+ labels = (parents.long().reshape(blocks.shape) + 1).repeat_interleave(2, -2).repeat_interleave(2, -1)+ return (labels[:, :height, :width] * mask).reshape(image.shape)diff --git a/tests/contrib/test_connected_components_union_find.py b/tests/contrib/test_connected_components_union_find.pynew file mode 100644index 000000000..b31f31b33--- /dev/null+++ b/tests/contrib/test_connected_components_union_find.py@@ -0,0 +1,140 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++import kornia++from testing.base import BaseTester+++def _flood_fill(mask):+ """Independent 8-neighbor CPU oracle with canonical (first pixel) labels."""+ height, width = len(mask), len(mask[0])+ labels = [[0] * width for _ in range(height)]+ for y in range(height):+ for x in range(width):+ if not mask[y][x] or labels[y][x]:+ continue+ label = y * width + x + 1+ labels[y][x] = label+ queue = [(y, x)]+ while queue:+ row, col = queue.pop()+ for dy in (-1, 0, 1):+ for dx in (-1, 0, 1):+ yy, xx = row + dy, col + dx+ if 0 <= yy < height and 0 <= xx < width and mask[yy][xx] and not labels[yy][xx]:+ labels[yy][xx] = label+ queue.append((yy, xx))+ return labels+++def _canonical(labels):+ mapping = {0: 0}+ return [mapping.setdefault(value, index + 1) for index, value in enumerate(labels)]+++class TestConnectedComponentsUnionFind(BaseTester):+ @pytest.mark.parametrize("shape", [(1, 1, 513), (2, 1, 513, 1), (2, 3, 1, 17, 19)])+ def test_long_connected_regions(self, device, dtype, shape):+ image = torch.ones(shape, device=device, dtype=dtype)+ labels = kornia.contrib.connected_components_union_find(image)+ assert labels.shape == image.shape+ assert labels.dtype == torch.int64+ batches = labels.reshape(-1, shape[-2] * shape[-1])+ assert all(row.unique().numel() == 1 for row in batches)+ assert batches[:, 0].unique().numel() == batches.shape[0]++ @pytest.mark.parametrize("height,width", [(3, 3), (2, 4), (4, 2)])+ def test_exhaustive_small_masks(self, device, dtype, height, width):+ # Exhaust every occupancy pattern across horizontal/vertical block edges+ # as well as diagonals, empty blocks and odd-sized borders.+ pixels = height * width+ values = torch.arange(2**pixels, device=device)+ image = (values[:, None] >> torch.arange(pixels, device=device)) & 1+ image = image.reshape(-1, 1, height, width).to(dtype)+ labels = kornia.contrib.connected_components_union_find(image)+ for mask, result in zip(+ image.cpu().reshape(-1, height, width).tolist(), labels.cpu().reshape(-1, pixels).tolist()+ ):+ expected = [value for row in _flood_fill(mask) for value in row]+ assert _canonical(result) == expected++ def test_random_masks(self, device, dtype):+ generator = torch.Generator().manual_seed(19)+ image = (torch.rand(24, 1, 17, 23, generator=generator) < 0.35).to(device=device, dtype=dtype)+ labels = kornia.contrib.connected_components_union_find(image)+ for mask, result in zip(image.cpu().reshape(-1, 17, 23).tolist(), labels.cpu().reshape(-1, 391).tolist()):+ assert _canonical(result) == [value for row in _flood_fill(mask) for value in row]++ def test_serpentine(self, device, dtype):+ image = torch.zeros(1, 1, 33, 65, device=device, dtype=dtype)+ image[..., ::2, :] = 1+ image[..., 1::4, -1] = 1+ image[..., 3::4, 0] = 1+ labels = kornia.contrib.connected_components_union_find(image)+ assert labels[image == 1].unique().numel() == 1+ assert (labels[image == 0] == 0).all()++ def test_noncontiguous(self, device, dtype):+ image = torch.eye(31, device=device, dtype=dtype)[None].transpose(-1, -2)+ assert not image.is_contiguous()+ labels = kornia.contrib.connected_components_union_find(image)+ assert labels[image == 1].unique().numel() == 1+ assert (labels[image == 0] == 0).all()++ def test_half_labels_do_not_collide(self, device):+ image = torch.zeros(1, 1, 257, 257, device=device, dtype=torch.float16)+ image[..., ::2, ::2] = 1+ labels = kornia.contrib.connected_components_union_find(image)+ assert labels[image == 1].unique().numel() == 129**2+ assert labels.dtype == torch.int64++ def test_bool_and_determinism(self, device):+ image = torch.tensor([[[True, False, False], [False, False, True]]], device=device)+ expected = torch.tensor([[[1, 0, 0], [0, 0, 2]]], device=device)+ for _ in range(3):+ self.assert_close(kornia.contrib.connected_components_union_find(image), expected)++ @pytest.mark.parametrize("shape", [(0, 1, 3, 5), (1, 0, 5), (2, 1, 3, 0), (1, 3, 5)])+ def test_empty(self, device, dtype, shape):+ image = torch.zeros(shape, device=device, dtype=dtype)+ labels = kornia.contrib.connected_components_union_find(image)+ self.assert_close(labels, torch.zeros(shape, device=device, dtype=torch.int64))++ def test_exact_foreground(self, device, dtype):+ image = torch.tensor([[[0, 0.5, 1, -1, 2]]], device=device, dtype=dtype)+ labels = kornia.contrib.connected_components_union_find(image)+ self.assert_close(labels != 0, image == 1)++ @pytest.mark.parametrize("shape", [(1, 1, 1), (1, 1, 2), (1, 2, 1)])+ def test_single_block_integer(self, device, shape):+ image = torch.ones(shape, device=device, dtype=torch.int32)+ self.assert_close(kornia.contrib.connected_components_union_find(image), image.long())++ def test_no_grad(self, device, dtype):+ image = torch.ones(1, 3, 3, device=device, dtype=dtype, requires_grad=True)+ assert not kornia.contrib.connected_components_union_find(image).requires_grad++ def test_exception(self, device, dtype):+ with pytest.raises(TypeError, match=r"torch\.Tensor"):+ kornia.contrib.connected_components_union_find(None)+ for shape in [(3, 4), (2, 3, 4), (1, 2, 3, 4)]:+ with pytest.raises(ValueError, match="shape"):+ kornia.contrib.connected_components_union_find(torch.zeros(shape, device=device, dtype=dtype))