regionprops: fix bugs in `cucim.skimage.measure.regionprops_table` #1196
[P1-1] Negative labels can write outside the GPU bounding-box buffer
AI-assisted review comment · Round 1 · New finding P1-1.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Normalize negative labels before narrowing the dtype or indexing the bounding-box array. The new nesting check turns −1 into ID 255 on the public batch path and indexes a box array sized for one label.
CUDA Compute Sanitizer reproduced an invalid four-byte global atomic on the reviewed head. The same 2 × 2 input completed with zero memcheck errors on the base.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
Request area_filled for the signed image [[1, -1], [0, 0]]. The batch dispatcher derives a maximum of 1 and casts −1 to uint8, producing 255. The new fill sees touching labels and requests one four-element bounding box. The CUDA kernel uses (lab - 1) * 4, so label 255 addresses element 1016. The direct fill helper retains −1 and addresses element −8. The base filled and relabeled a binary mask before counting this example. CUDA Compute Sanitizer reported an invalid four-byte global atomic in cucim__bbox2d_batch16 followed by a launch failure on the reviewed head. The same public API call on the base completed with zero memcheck errors. The direct helper’s index follows from source inspection. python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py:398-405 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:114-121 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:559-574 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:962-982
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1013-1017
touching = (~background) & ((nb_max != padded) | (nb_min != padded))
touching &= padded != 0
if bool(touching.any()):
if bbox is None:
bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)
Recommended change
Treat negative values as background before narrowing the batch image and before computing the direct helper’s maximum. Test both entry points with mixed-sign and all-negative inputs under Compute Sanitizer. The mixed example should leave label 1 with filled area 1.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py
@@ -398,2 +398,4 @@
out = {}
+ if label_image.dtype.kind == "i":
+ label_image = cp.maximum(label_image, 0)
if max_label is None:
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
@@ -1089,2 +1089,4 @@
"""
+ if labels.dtype.kind == "i":
+ labels = cp.maximum(labels, 0)
if max_label is None:
The proposed diff passed an application check against the reviewed head.
</details>
[P2-1] Host conversion loses the channel axis of weighted centroids
AI-assisted review comment · Round 1 · New finding P2-1.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Infer the complete shape of a multichannel weighted centroid before allocating host columns. The nested tuple holds one channel vector per coordinate, but the converter currently allocates storage for a single axis.
Both split and unsplit host outputs raised ValueError on the RTX A6000 with a two-channel input and two labels.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
With two labels and a two-channel 2D intensity image, each per-label centroid_weighted is a tuple of two channel vectors. The converter records shape (2,). Its new recursive host copy then assigns a matrix to a vector in unsplit mode, or a vector to a scalar in split mode. Both calls raised ValueError on the GPU with batch_processing=False, copy_output_to_host=True. python/cucim/src/cucim/skimage/measure/_regionprops.py:722-732 · python/cucim/src/cucim/skimage/measure/_regionprops.py:1055-1071
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops.py:1035-1045
else:
if isinstance(rp, cp.ndarray):
shape = rp.shape
else:
shape = (len(rp),)
if not to_table:
if copy_to_host:
column_data = np.empty((n,) + shape, dtype=dtype)
for k in range(n):
column_data[k] = _to_host(regions[k][prop])
Recommended change
Derive the complete shape of a host-bound tuple. Check four coordinate-by-channel columns in split mode and a (2, 2, 2) NumPy array in unsplit mode against the same reference centroids.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops.py
@@ -1037,2 +1037,4 @@
shape = rp.shape
+ elif copy_to_host:
+ shape = np.shape(_to_host(rp))
else:
The proposed diff passed an application check against the reviewed head.
</details>
[P2-2] Two touching pixels can require a 16 GiB temporary bounding-box array
AI-assisted review comment · Round 1 · New finding P2-2.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Bound fill scratch storage by the number of present labels. The connected-component nesting check allocates one box per ID up to the maximum, even when the caller only needs the filled image. Compact sparse labels for the fill and restore the original IDs afterward.
A two-pixel input with IDs 1 and 2³⁰ attempted a 16 GiB allocation on the reviewed head. A 256 MiB memory-pool limit stopped the allocation. The base completed under the same limit.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
For regionprops_label_filled([[1, 230]]) with uint32 input, the new nesting check asks for one 2D box per integer through the maximum. Its shape is (230, 4) with four bytes per entry. The helper discards the nesting result, and its image output has just two pixels. The same allocation occurs for a regionprops_dict request for label_filled alone. The base used image-sized component labels. Sparse IDs above 2⁵³ can also round in the grey filters’ double intermediates. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:548-564 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1090-1095 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py:757-765 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1462-1468
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1015-1017
if bool(touching.any()):
if bbox is None:
bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)
Recommended change
For the sparse case, assign compact integer IDs for the fill and map its two outputs back to the original IDs. The recursive call below runs once on a maximum bounded by the pixel count. Apply P1-1 first. Check the two-pixel example and a ring labeled 2**53 + 1 for exact labels and image-sized scratch storage. Per-label table rows still follow the existing dense-row convention.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
@@ -965,2 +965,12 @@
"""
+ if labels.size and max_label > labels.size:
+ values, codes = cp.unique(labels, return_inverse=True)
+ if int(values[0]) != 0:
+ values = cp.pad(values, (1, 0))
+ codes += 1
+ n = values.size - 1
+ dense = codes.reshape(labels.shape).astype(_get_min_integer_dtype(n))
+ filled, inexact = _fill_holes_by_label(dense, n)
+ return values[filled], cp.asnumpy(values[cp.asarray(inexact)])
+
ndim = labels.ndim
@@ -1136,2 +1146,3 @@
for lab in labels_inexact:
+ lab = int(lab)
image = label_image[slices[lab - 1]] == lab
The proposed diff passed an application check against the reviewed head.
</details>
[P2-3] An overflowing squared sum gives a varying region zero standard deviation
AI-assisted review comment · Round 1 · New finding P2-3.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Accumulate squared intensities in a type that can hold their sum. For a uint32 region containing 0 and two UINT32_MAX pixels, the uint64 sum of squares wraps, and the new variance clamp converts the negative result to zero.
The RTX A6000 returned 0 for that region. NumPy returned 2,024,666,999.51.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
For one uint32 region with values [0, 232 - 1, 232 - 1], two squared maxima overflow the uint64 accumulator. The existing one-pass formula then produces a large negative variance. The new clamp turns the baseline NaN into 0, hiding variation in the measurements. The GPU returned 0 and NumPy returned 2,024,666,999.51. The sample and population branches both clip. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:77-87 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:196-204 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:470-492
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:489-492
}} else {{
m = static_cast<double>(sum) / count;
double v = (static_cast<double>(sumsq) - m * m * count) / count;
var = sqrt(v < 0.0 ? 0.0 : v);
Recommended change
Use double accumulation before squaring and match the reduction’s output buffers to that type whenever squared sums are requested. Check both population and sample standard deviation against NumPy. This correction addresses integer overflow. The one-pass formula retains its existing sensitivity to cancellation for nearly equal large values.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
@@ -259,2 +259,5 @@
) = _get_intensity_img_kernel_dtypes(image_dtype)
+ if compute_sum_sq:
+ sum_dtype = cp.dtype(cp.float64)
+ c_sum_type = "double"
@@ -527,3 +530,3 @@
image_dtype = intensity_image.dtype
- sum_dtype, _, _, _ = _get_intensity_img_kernel_dtypes(image_dtype)
+ sum_dtype = cp.dtype(cp.float64)
The proposed diff passed an application check against the reviewed head.
</details>
Round 1 review, reviewed source 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Recommendation: Request changes. CUDA Compute Sanitizer confirmed an out-of-bounds GPU atomic write in the new fill path for a signed 2 × 2 input.
11 active findings · 11 new · 0 previously reported (1 P1, 6 P2, 4 P3).
P1-1: Negative labels can write outside the GPU bounding-box bufferP2-1: Host conversion loses the channel axis of weighted centroidsP2-2: Two touching pixels can require a 16 GiB temporary bounding-box arrayP2-3: An overflowing squared sum gives a varying region zero standard deviationP2-4: Float64 minima and maxima can return a finite value absent from the regionP2-5: Default 1D filling scans a long background vector quadraticallyP2-6: Varying the maximum label generates new GPU erosion kernelsP3-1: Changing the footprint can make an in-place fill return NoneP3-2: Per-label measurement copies the same device spacing to the host for each regionP3-3: A host footprint can raise TypeError only when it selects iterative fillingP3-4: The iterative-fill regression test passes when its footprint is ignoredValidation: All 39 reported GitHub checks and 11 focused RTX A6000 tests passed, including both large-image cases. Targeted GPU probes reproduced the signed-label, sparse-allocation, weighted-centroid, and intensity findings.
<!-- code-review: round=1 sha=0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8 findings=P1:1,P2:6,P3:4 -->
[P2-4] Float64 minima and maxima can return a finite value absent from the region
AI-assisted review comment · Round 1 · New finding P2-4.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Initialize float64 extrema with positive and negative infinity at both reduction stages. Finite initializers cause an all-positive-infinity region to return a finite minimum and an all-negative-infinity region to return a finite maximum.
Both errors reproduced on the RTX A6000. The base returned the expected infinities.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
An all-+inf region returned float64.max for its minimum. An all--inf region returned -float64.max for its maximum. Both the per-thread and the global reductions start at finite values. The new double-precision atomic now preserves those initializers even when every observation is more extreme. The finite-random regression test passes on this head. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:222-236 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:624-634 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_utils.py:32-57
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:275-286
any_min_max = compute_min or compute_max
if any_min_max:
if min_max_dtype is None:
raise ValueError("min_max_dtype must be specified")
range_min, range_max = _get_intensity_range(min_max_dtype)
min_max_pre, min_max_op, min_max_post = _get_intensity_min_max_code(
min_max_dtype=min_max_dtype,
c_min_max_type=c_min_max_type,
array_size=array_size,
num_channels=num_channels,
initial_max_val=range_min,
initial_min_val=range_max,
Recommended change
Use ±infinity at both reduction stages for float64. The diff covers present labels. For missing labels it also changes the exposed initial values to infinities. If callers rely on finite sentinels for gaps, restore those rows with a presence mask. Exercise both signs, a finite/infinite mixture, and an absent label.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
@@ -279,2 +279,4 @@
range_min, range_max = _get_intensity_range(min_max_dtype)
+ if min_max_dtype == cp.float64:
+ range_min, range_max = "-CUDART_INF", "CUDART_INF"
min_max_pre, min_max_op, min_max_post = _get_intensity_min_max_code(
@@ -627,2 +629,4 @@
range_min, range_max = _get_intensity_range(image_dtype)
+ if min_max_dtype == cp.float64:
+ range_min, range_max = -math.inf, math.inf
out_shape = (
The proposed diff passed an application check against the reviewed head.
</details>
[P2-5] Default 1D filling scans a long background vector quadratically
AI-assisted review comment · Round 1 · New finding P2-5.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Keep the default 1D fill linear by finding the first and last foreground positions and filling the interval. Sending a long all-zero vector through brute-force dilation takes one full scan and a convergence check per propagation step.
Source inspection and a SciPy propagation probe confirmed the mechanism and 513 steps for a 1,024-element vector. GPU timing was outside this check.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
The rank check sends even the default 1D footprint through brute-force dilation. On an all-zero vector the exterior advances one pixel from each end per full scan, followed by a device-wide equality check observed by the host. A length of 1,024 requires 513 passes including convergence, as confirmed with the same propagation in SciPy. The base labeling algorithm already gave the correct result for this input. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:307-328 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:953-982
Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:871-876
def _can_use_label_for_fill_holes(structure, ndim):
# In 1D the padding at opposite ends is not connected.
if ndim < 2:
return False
if structure is None:
return True
Recommended change
Allow labeling for the compatible 1D footprint and remove the background components at both padded ends. Keep the existing separated-ends test. Add a long all-zero vector and check that it takes the labeling path. Custom footprints still pass through the connectivity checks.
--- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
+++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
@@ -850,2 +850,4 @@
inverse_binary_mask[inverse_labels == background_index] = 0
+ if ndim == 1:
+ inverse_binary_mask[inverse_labels == inverse_labels[-1]] = 0
@@ -871,4 +873,3 @@
def _can_use_label_for_fill_holes(structure, ndim):
- # In 1D the padding at opposite ends is not connected.
- if ndim < 2:
+ if ndim == 0:
return False
@@ -902,3 +903,3 @@
one, as in SciPy. With the default origin and axes, inputs with
- at least two dimensions use a faster non-iterative algorithm
+ at least one dimension use a faster non-iterative algorithm
when the structure is centrosymmetric, has size 3 on every axis,
The proposed diff passed an application check against the reviewed head.
</details>
[P2-6] Varying the maximum label generates new GPU erosion kernels
AI-assisted review comment · Round 1 · New finding P2-6.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Use a border mode that lets erosion reuse its compiled kernel across label counts. The current sentinel becomes both a kernel cache key and a CUDA literal. For a size-3 neighborhood, the existing one-pixel sentinel border is enough for the pixels of interest.
Verified the memoization key and generated source path statically.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
Two tiles of the same shape and dtype with different maximum IDs pass different cval arguments to grey erosion. The separable filter includes that value in its per-device memoization key and embeds it as a literal in CUDA source. Streams of tiles with new object counts therefore accumulate distinct kernel variants and incur cold compilation on cache misses. Repeating one tile in a timing loop reuses its variant. python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1318-1330 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1436-1456 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters_core.py:348-353
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:980-987
no_label = max_label + 1
nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
nb_min = ndi.grey_erosion(
cp.where(background, no_label, padded).astype(work_dtype, copy=False),
size=3,
mode="constant",
cval=no_label,
)
Recommended change
Use a fixed boundary mode. The existing one-pixel border supplies the entire size-three neighborhood for every interior output the algorithm uses. Vary the maximum across same-shape tiles and check that the erosion kernel is reused and the filled pixels agree with the reference. Compile latency was not timed.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
@@ -984,4 +984,3 @@
size=3,
- mode="constant",
- cval=no_label,
+ mode="nearest",
)
The proposed diff passed an application check against the reviewed head.
</details>
[P3-1] Changing the footprint can make an in-place fill return None
AI-assisted review comment · Round 1 · New finding P3-1.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Preserve the existing return value when the caller supplies an output array. A footprint that selects iterative filling updates that array but now returns None, while a footprint that selects labeling returns the array.
Verified the two return paths in the pinned source.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
With default origin and axes, the base returned the supplied output array. On this head a compatible footprint still returns it. A horizontal device footprint selects the iterative branch, which writes the buffer and falls through with None. Code using the documented array result can fail on its next array operation. The new in-place test examines the buffer only. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:855-868 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:919-921 · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:183-188
Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:966-971
brute_force=True,
axes=axes,
)
cupy.logical_not(output, output)
else:
output = binary_dilation(
Recommended change
Return the output array on both branches to preserve cuCIM’s default-origin behavior. For a full and a horizontal footprint, check result is out and compare the updated pixels with SciPy.
--- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
+++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
@@ -982,3 +982,3 @@
cupy.logical_not(output, output)
- return output
+ return output
The proposed diff passed an application check against the reviewed head.
</details>
[P3-2] Per-label measurement copies the same device spacing to the host for each region
AI-assisted review comment · Round 1 · New finding P3-2.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Normalize a device spacing vector once per regionprops call. Each RegionProperties constructor now copies the same vector to the host, so a call with 1,024 labels can incur 1,024 synchronized transfers even when the caller only requests labels.
Verified the construction loop and device-to-host transfer in the pinned source.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
A regionprops call with a CuPy spacing vector constructs a RegionProperties object for every present label. Each constructor now calls cp.asnumpy on the same vector. A label-only request with 1,024 regions thus performs 1,024 synchronous transfers. The base kept device spacing on the device. python/cucim/src/cucim/skimage/measure/_regionprops.py:349-357 · python/cucim/src/cucim/skimage/measure/_regionprops.py:1634-1652
Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_utils.py:385-387
if isinstance(spacing, cp.ndarray):
spacing = cp.asnumpy(spacing)
spacing = np.array(spacing)
Recommended change
Download the spacing once before the loop. Count transfers for a many-label request and verify that spacing (2, 3) still gives each single-pixel region area 6. Constructor validation continues to cover direct callers.
--- a/python/cucim/src/cucim/skimage/measure/_regionprops.py
+++ b/python/cucim/src/cucim/skimage/measure/_regionprops.py
@@ -1633,2 +1633,5 @@
+ if isinstance(spacing, cp.ndarray):
+ spacing = cp.asnumpy(spacing)
+
regions = []
The proposed diff passed an application check against the reviewed head.
</details>
[P3-3] A host footprint can raise TypeError only when it selects iterative filling
AI-assisted review comment · Round 1 · New finding P3-3.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Convert host footprints before passing them to the iterative GPU path. A compatible NumPy footprint can take the labeling path, while a horizontal NumPy footprint falls through to dilation and raises TypeError.
GPU comparison reproduced the TypeError. The vendored morphology suite passed with the proposed conversion and revised fixture, with 430 passes and 13 skips.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
With default origin and axes a full 3 × 3 NumPy footprint reaches the host-compatible labeling route. Change its values to a horizontal line and the dispatcher forwards a NumPy array into device dilation, raising TypeError. Nested lists encounter the dilation helper’s shape shorthand. The base accepted both by ignoring them. This is a low-priority compatibility issue in the vendored helper. Its docstring specifies a CuPy footprint and the region-measurement fallback supplies one. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:898-908 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:953-968 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:341-356 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1135-1139
Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:941-947
structure_cpu = structure
if isinstance(structure, cupy.ndarray):
structure_cpu = cupy.asnumpy(structure)
if _can_use_label_for_fill_holes(structure_cpu, input.ndim):
return _binary_fill_holes_non_iterative(
input, structure=structure_cpu, output=output
)
Recommended change
Convert a host footprint when the default-origin dispatcher selects iteration. Preserve the shape shorthand for lower-rank lists. Compare a horizontal NumPy footprint, its nested-list equivalent and a CuPy copy with the same SciPy result.
--- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
+++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
@@ -947,2 +947,6 @@
)
+ if isinstance(structure, numpy.ndarray) or (
+ isinstance(structure, list) and numpy.ndim(structure) == input.ndim
+ ):
+ structure = cupy.asarray(structure, dtype=bool)
elif filter_all_axes:
The proposed diff passed an application check against the reviewed head.
</details>
[P3-4] The iterative-fill regression test passes when its footprint is ignored
AI-assisted review comment · Round 1 · New finding P3-4.
Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.
Use a non-empty fixture whose expected result changes with the footprint. The padded hollow box gets the same result with each selected footprint and the default, so the test passes even when the implementation ignores structure.
All 32 combinations passed against the original implementation. The revised non-empty fixture distinguished the requested footprints from the default in SciPy.
<details>
<summary>Evidence, proposed patch, and regression coverage</summary>
The hollow box has thick walls. For all four footprints in both dimensions, SciPy produces the same mask with the supplied footprint and with the default. The empty controls also agree. All 32 combinations can therefore pass the old dispatch that ignored the footprint. The adjacent fast-path test already uses a fixture that distinguishes connectivity. python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:144-153 · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:156-188
Original hunk · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:176-182
data = np.zeros((9,) * ndim, dtype=bool)
if not empty:
data[(slice(1, -1),) * ndim] = True
data[(slice(3, -3),) * ndim] = False
expected = ndi_cpu.binary_fill_holes(data, struct)
data = cp.asarray(data)
struct = cp.asarray(struct)
Recommended change
Keep the empty case and use a seeded non-empty input where the selected footprint changes the reference pixels. A SciPy comparison confirmed differing outputs for all eight rank/footprint pairs with the seed below.
--- a/python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py
+++ b/python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py
@@ -175,7 +175,9 @@
- data = np.zeros((9,) * ndim, dtype=bool)
+ if empty:
+ data = np.zeros((9,) * ndim, dtype=bool)
+ else:
+ data = np.random.default_rng(5).random((24,) * ndim) > 0.35
+ expected = ndi_cpu.binary_fill_holes(data, struct)
if not empty:
- data[(slice(1, -1),) * ndim] = True
- data[(slice(3, -3),) * ndim] = False
- expected = ndi_cpu.binary_fill_holes(data, struct)
+ assert not np.array_equal(expected, ndi_cpu.binary_fill_holes(data))
data = cp.asarray(data)
The proposed diff passed an application check against the reviewed head.
</details>
Thank you @grlee77 for fixing bug on this. It looks good to me overall.
Please find the ai review comments, before merge (at least P1 (+ P2)).
Thank you!
This is addressed among other improvements in #1228, but can push a more minimal fix in this branch.
Fixed in 96c68a5c; cleanup in 58415fce. Negative labels become background before narrowing or indexing. Mixed-sign and all-negative regressions pass Compute Sanitizer.
Fixed in 2e707fbb, aeba5e6b, and bb74afb1. Multichannel weighted centroids preserve both axes in split and unsplit host and device output. Device conversion stacks tuples of per-channel arrays, while scalar tuples such as bbox and centroid use their previous conversion
Fixed in 374513e6. Sparse labels are compacted before filling, then original IDs are restored. Tests cover IDs above 2**53 under a 256 MiB pool limit.
Fixed in 586a58d9, narrowed in 6e165c3e. Wide integers use double accumulation; bool and 8/16-bit integers retain integer accumulation below 2**32 pixels. Population/sample extreme-value tests match NumPy. Cancellation is handled separately in #1228.
Fixed in 2b44e73b and 40672323. Both reduction stages use infinite identities for all floating dtypes. Tests cover infinite regions, finite/infinite mixtures, and absent labels.
Fixed in 8ae9bb0e. Compatible 1D inputs use connected-component filling, with both exterior components excluded. A long-vector regression verifies dilation is bypassed.
Fixed in 374513e6. Erosion uses nearest, allowing kernel reuse across label counts. The regression checks kernel identities; 1f9d8c5a removes its positional-argument assumption.
Fixed in 8ae9bb0e. Both filling paths return the supplied output array. Tests verify return identity.
Fixed in 0a41163f. Device spacing is downloaded once before constructing regions. A 1,024-label regression verifies one transfer and correct scaled areas.
Fixed in 8ae9bb0e and 4cbce3eb. Host footprints are converted before iterative filling, including nondefault origins. NumPy/list/device and in-place cases are covered.
Fixed in 8ae9bb0e. Nonempty fixtures explicitly produce different results with the requested footprint versus the default, so ignoring the footprint fails the test.
Thanks, @gigony. Pushed several new commits addressing the remaining issues identified during review.
/merge
gigony
grlee77
Summary
This PR fixes bugs in cuCIM's batch region properties
(
regionprops_table(..., batch_processing=True), which callsregionprops_dict). This includes wrong coordinates and pixel counts on labelimages of 2³² or more pixels. It also fixes two closely related bugs: one in
the per-label path (
batch_processing=False) and one in cuCIM's vendoredbinary_fill_holes. The bugs were found while writing a technical explainerof the batch implementation and while optimizing it.
Each bug has its own commit with its own tests, so the commits can be reviewed
one at a time (22 commits, listed at the end). The branch is based on
main(a0e27d1e) and does not depend on the
intensity_medianPR.Is the bug also in scikit-image?
None of the bugs fixed here is present in scikit-image 0.26. Every fix
either makes cuCIM return what scikit-image returns, or fixes a cuCIM-only
property, parameter, option or vendored function that has no scikit-image
counterpart. In every case where a scikit-image counterpart exists, the fixed
cuCIM result now matches it, apart from the rounding of
intensity_std(see"Not addressed here").
The one bug with an upstream history is the sign of
orientationfor ±45°regions. scikit-image fixed it in 0.21 (scikit-image PR #6836, "Sign error fix
in measure.regionprops for orientations of 45 degrees"), but both cuCIM paths
still had the old sign.
Fixes that restore agreement with scikit-image
Examples are from the commit messages and tests; "spacing (2, 2)" values are
for a test image with two ellipses.
| Commit | Properties | cuCIM path | Before → after (= scikit-image) |
|---|---|---|---|
| 1 |
orientation| batch and per-label |cp.eye(10): −π/4 → π/4 || 2 |
eccentricity| batch | single-pixel region: NaN → 0 || 3 |
intensity_std| batch | constant float32 region of 0.1 or 1000.3: NaN → 0 || 6 |
centroid,centroid_weighted| batch | spacing (2, 2):centroid-028 → 40 || 7 |
centroid_weighted| per-label | region starting at row 3, spacing 2: 7.95 → 10.95 || 8 |
area_bbox,extent| batch | spacing (2, 2):area_bbox493 → 1972 || 9 |
moments_normalized,moments_weighted_normalized| batch | spacing (2, 2):moments_normalized-2-00.179 → 0.045 || 9 |
moments_hu,moments_weighted_hu| batch | non-unit spacing: values →NotImplementedError|| 10 |
area_convex,solidity| batch | spacing (2, 2):area_convex373 → 1492 || 11 |
perimeter,perimeter_crofton| batch | spacing (2, 2): 73.9 → 147.9; anisotropic spacing: values →NotImplementedError|| 14 |
area_filled| batch | filled pixel count → filled area (× pixel area) || 16 |
area_filled,image_filled| batch | labels not in raster order: [36, 4, 36] → [36, 36, 4]; touching regions: [128, 0] → [64, 64] || 18 |
bbox,centroid,centroid_local, moments and properties derived from them | batch | (65537, 65536) image, region on the last row:bboxrows [0, 1) → [65536, 65537) || 22 |
intensity_min,intensity_max| batch | float64 image of uniform values in [0.1, 1): off by up to 1.7e-9 (minimum) and 2e-8 (maximum), rounded to float32 → the exact pixel values |Notes:
regionprops_dictdid not passspacingto these functions (or, for the perimeters, did not scale the result),
although scikit-image applies it. The
NotImplementedErrors are the onesscikit-image and cuCIM's per-label path already raise.
centroid_weighted(commit 7). This is the only spacing bugthat was also in cuCIM's per-label path.
RegionProperties.centroid_weightedadded the bounding-box start without multiplying it by the spacing;
scikit-image uses
slc.start spc.intensity_std(commit 3). The one-pass variance(sumsq − mean²·count) / countcan round to a small negative number for aconstant region, and
sqrtthen returns NaN. It is now clipped at 0, using acomparison rather than CUDA's
max(which isfmax). That way, regions thatcontain NaN or ±inf still return NaN, as
numpy.stddoes.pixels" below.
threads' partial minima and maxima with
atomicMinandatomicMax. Fordouble, these are CuPy's overloads (cupy/_core/include/cupy/atomics.cuh),whose compare-and-swap loops compare with
fminfandfmaxf, thesingle-precision functions, so every stored value was rounded to float32
and could even lie outside the region's range. CuPy's development version
(October 2026) still has them. CUDA has no native atomic minimum or maximum
for
double, so the shared kernel preamble now definescucim_atomic_minandcucim_atomic_max: CUDA'satomicMinandatomicMaxfor every other type, and fordoublea compare-and-swap loopthat compares in double precision. The fix in CuPy itself would be to use
fminandfmaxthere.its own crop. The batch path filled the union of all labels and relabeled it
with
measure.label, so values came back in the wrong order and touchingregions were merged. See "Filled-region properties" below.
Fixes without a scikit-image counterpart
| Commit | What | Before → after |
|---|---|---|
| 4 |
pixels_per_threadkernel parameter (batch only) | 128–255 overflowed theint8_tper-thread counters:num_pixelsof a 64 × 64 region was 4294963200 (128) or 0 (255) → 4096 || 5 |
axis_lengths(cuCIM-only property) |properties=["axis_lengths"]alone:KeyError→ works || 12 |
copy_output_to_host=True(cuCIM-only option) withbatch_processing=False|TypeErrorforcentroid_weightedwith more than one region → works || 13 | docstrings of
regionprops_perimeter,regionprops_perimeter_crofton(batch module) | saidperimeterskips the boundary along the image edge; both perimeters count it || 15, 17 | vendored
ndimage.binary_fill_holes|structurewas ignored with the defaultoriginandaxes→ it is used || 16 |
label_filled,num_pixels_filled(cuCIM-only properties) | relabeled values and a one-pixel padding (22 × 22 output for a 20 × 20 input);num_pixels_filledrequested alone was the unfilled count → input label values and shape, filled count || 19 |
feret_diameter_maxof a label value that does not occur (batch only) |RuntimeError: No coordinates to process→ 0 || 20 |
regionprops_centroid(batch module) withnum_pixelsalready inprops_dict|TypeError: Wrong number of arguments→ works || 21 |
regionprops_centroid,regionprops_centroid_local(batch module) | region of 2³² or more pixels: wrappeduint32count, centroid row 2.1e9 → 32768 || 23 |
inertia_tensor_eigenvectors(cuCIM-only property) | the returned vectors were not eigenvectors ofinertia_tensor(each eigenvector's components were reversed) → the columns are the eigenvectors, in the order ofinertia_tensor_eigvals|Commit 15 is a bug in cuCIM's vendored copy only. SciPy and
cupyx.scipy.ndimage.binary_fill_holes(CuPy 14.2) use the structuringelement. No cuCIM function passed a
structureto the vendored versionbefore commit 16, whose per-label fallback does. Commit 17 completes commit
15: the fast non-iterative algorithm labels the background with the
structuring element, which is only valid for centrosymmetric 3 × 3 (× 3)
structures that contain the center and all face neighbors. Other structures
now use SciPy's iterative algorithm.
The batch path returns a row for every label value 1 …
max_label, also forvalues that do not occur (scikit-image returns only the labels present). Such
rows have an area of 0, so commit 19 returns 0 for their
feret_diameter_max, as for theirarea_convex,perimeterand axislengths. Before, any label image with a gap in its label values made
regionprops_tablefail whenferet_diameter_maxwas requested.regionprops_dictcomputes centroids from the raw moments, so commits 20 and21 only affect direct calls of the two helper functions.
cupy.linalg.eighreturns each batch of eigenvectors as the columns of a(K, ndim, ndim) array. To put them in the descending order of
inertia_tensor_eigvals,regionprops_inertia_tensor_eigvalsreversed axis 1(the components of every eigenvector) instead of axis 2 (the eigenvectors).
For an ellipse rotated by 30°,
T @ vgave (−10.8, 25.2) instead of56.9 · (0.511, 0.860). The eigenvalues were correct. Commit 23 reverses the
columns; the first eigenvector is then along the region's shortest axis (the
largest eigenvalue of the inertia tensor).
Behavior changes users may notice
orientation. Regions whose inertia tensor has equal diagonal entries(±45°) change sign, in both paths. The values now match scikit-image ≥ 0.21.
-
moments_huandmoments_weighted_huraiseNotImplementedErrorwithnon-unit spacing;
-
perimeterandperimeter_croftonraise it with anisotropic spacing.whenever the spacing is not 1.
label_filled. It now has the shape and the label values of the input,with no padding and no relabeling.
feret_diameter_maxof absent label values is 0 instead of an error.inertia_tensor_eigenvectorsreturns actual eigenvectors (as columns).bboxdtype for images of 2³² or more pixels isuint64(it wasuint32with wrapped values).section), because the old implementation did not compute per-region fills.
Filled-region properties (commit 16)
How the batch computation works:
1. The label image is padded and its background labeled with full
connectivity, as
binary_fill_holesdoes with the3ndimstructuringelement that scikit-image uses. Every background component except the one
touching the padding is a hole.
2. For each hole, the largest and smallest neighboring labels are found with a
grey dilation and erosion. A hole with a single neighboring label is filled
with that label. For that region, this is exactly what scikit-image's
binary_fill_holeson the region's crop gives.3. scikit-image treats other labels as background. A label's result can
therefore differ from step 2 only if:
- (a) it borders a hole that also borders other labels, or
- (b) a connected component of another label sits in one of its holes with
no background in between. Such a component touches the label, and its
bounding box lies strictly inside the label's bounding box.
Labels matching (a) or (b) are recomputed one at a time with
binary_fill_holeson their crop, asrobust_perimeterdoes for closelabels. The test is conservative: a flagged label may not need the
recomputation, but every label that needs it is flagged. Test (b) uses the
bounding box of the component, not of the whole label, because the other
components of a nested label can lie anywhere.
num_pixels_filled,area_filledandimage_filledare all computed fromthis one result.
area_filledtimings, with the number of labels each version gets wrongcompared with scikit-image 0.26:
| Input | Labels | Recomputed per label |
main(ms) | this PR (ms) | Wrong onmain| Wrong here ||---|---:|---:|---:|---:|---:|---:|
| tiles 2160 × 3840, 32 × 32 | 1024 | 0 | 5.8 | 16.0 | 1024 | 0 |
| tiles 2160 × 3840, 127 × 128 | 16256 | 0 | 5.7 | 15.8 | 16256 | 0 |
|
binary_blobs4096² | 240 | 0 | 9.6 | 20.4 | 0 | 0 || 4 intensity levels 2048² | 1864 | 121 | 4.0 | 109.9 | 1864 | 0 |
Setup:
regionprops_dict(labels, properties=["area_filled"]).cupyx.profiler.benchmark.- Tiles: rectangular regions that all touch each other.
-
binary_blobs:blob_size_fraction=0.02,volume_fraction=0.5,labeled.
- 4 intensity levels: Gaussian-smoothed (σ = 8) uniform noise, split
into 4 levels at its 10th, 50th and 90th percentiles. The connected
components of each level are labeled, giving many regions nested inside
others with no gap.
Most of the added cost on images that need no recomputation comes from the
extra full-image passes: the background labeling, the grey dilation and
erosion, and the connected-component labeling for test (b). Test (b) alone
adds about 3 ms on the tilings. On the intensity-levels image, the call takes
11.2 ms when the recomputation is skipped, against 110.3 ms with it. Each of
the 121 recomputed labels therefore costs about 0.8 ms, because the fallback
loops over labels on the host. Batching that fallback would be a separate
performance change.
Images of 2³² or more pixels (commits 18 and 21)
The batch bounding-box, centroid and moments kernels unravel each pixel's
raveled index into coordinates in their coordinate type. That type was
uint32whenever every axis is shorter than 2³², so on larger images theraveled index wrapped. Commit 18 chooses
uint64coordinates when the imagehas 2³² or more pixels, in one helper (
_get_coord_dtype) used by all fourcall sites. Commit 21 does the same for the pixel counts of the two centroid
helpers, which were always
uint32; the other count kernels already chosetheir type from the image size.
Smaller images keep 32-bit coordinates and counts, whose integer divisions
are much faster. Their generated kernels are unchanged: the sources of all
57 kernels that
regionprops_dictbuilds for 2D and 3D inputs withuint8,int32andint64labels (all non-convex properties) are identical beforeand after the commits.
Checked on a (65537, 65536)
uint8label image (4.3 GB) with auint8intensity image, outside the test suite:
hole) were compared with the same regions in a crop of a few rows around
them, with the crop offset added back to
bboxand the centroids.bbox,centroid,centroid_weighted,centroid_local,moments_central,moments_weighted_central,inertia_tensor,intensity_meanandintensity_max.2³². There are none after it.
bboxand centroid, witheither the moments or the coordinate sums.
Two properties still cannot be computed on such an image with 48 GB of GPU
memory (see "Not addressed here").
Tests
New tests:
Kernels:test_eccentricity_single_pixel_batch,test_intensity_std_constant_regions,test_intensity_std_nonfinite,test_num_pixels_large_pixels_per_thread,test_intensity_min_and_max_float64_exact(float64 minima and maximaequal to scikit-image's exactly; the existing min/max tests used
assert_allclose),test_inertia_tensor_eigenvectors(T·v = λ·v,orthonormality and descending order, 2D and 3D, with and without
spacing)..
Batch
regionprops_dictvs. scikit-image:-
test_regionprops_dict_spacing(2D and 3D, isotropic and anisotropicspacing, 10 properties);
-
test_regionprops_dict_perimeter_spacing,test_regionprops_dict_hu_spacing_not_implemented,test_regionprops_dict_area_filled_spacing,test_regionprops_dict_axis_lengths.Filled regions:
test_regionprops_dict_filled, with 8 cases: labels notin raster order, touching, nested with a gap, nested and touching, nested
with another component elsewhere, a ring open through a diagonal gap, a hole
between two labels, and 3D. Also
test_regionprops_dict_filled_random,test_label_filledandtest_fill_holes_by_label_tiling_is_exact.Both paths:
test_orientation_continuity(ported from scikit-image),test_orientation_diagonal_batch_matches_regionprops,test_centroid_weighted_offset_spacing,test_centroid_weighted_copy_to_host.Vendored ndimage:
test_binary_fill_holes_structure,test_binary_fill_holes_iterative_structure.Absent labels and helpers:
test_feret_diameter_max_absent_label,test_centroid_reuses_num_pixels.Images of 2³² or more pixels:*
test_regionprops_dict_coordinates_beyond_2_32_pixelsandtest_centroid_region_of_2_32_pixels. Each uses a 4.3 GB label image andis skipped when less than 8.6 GB of GPU memory is free. They take about 2 s
each on an RTX A6000.
The expected values in the existing
test_orientationwere updated toscikit-image 0.26's.
Every commit except the docstring one adds at least one test that fails
without its fix. For the filled-region commit, this was checked against
main's implementation: all 8test_regionprops_dict_filledcases failthere. A few tests guard against regressions that
maindid not have.For example,
test_intensity_std_nonfinitechecks that clipping the variancekeeps NaN for regions with NaN or inf values.