Image pyramid performance: reduce filtering, downsampling, and clipping overhead #1183
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #1183"
general
weight: 0.35
gigony
Summary
Stacked on top of #1182, so please review and merge that one first
This change reduces the overhead of repeated Gaussian filtering, especially for
image pyramids and batch-processing workloads that reuse the same filter
parameters. Several other sources of overhead were addressed in image pyramids to give overall large improvement in
Motivation
Caching
A multidimensional Gaussian filter is implemented as a sequence of 1D
convolutions. Previously, each call regenerated an identical host-side kernel
for every filtered axis and copied it to the GPU. This fixed setup cost is
significant for small and medium images, repeated calls, and
pyramid_gaussian, where the same sigma is used at each pyramid level.The new cache pays the coefficient-generation and host-to-device-copy cost on
the first use of a parameter combination. Later axes, pyramid levels, and
calls reuse the GPU kernel directly.
Similarly,
ndimage.zoompreviously copied its short sequence of zoom factorsto a new GPU array on every call. A pyramid performs one zoom per reduction,
so these tiny transfers contributed a fixed cost at every level. The bounded
factor cache now performs this transfer once per unique device/factor/dtype
combination.
The cache key includes the CUDA device ID so an array is never reused on the
wrong device. Both caches copy new entries on a private non-blocking stream
per device and wait only for that stream before publishing fully initialized
arrays. Cache misses therefore do not drain work already queued by the caller.
Cache hits need no CUDA event or GPU stream operation. Consumer streams are
tracked on the host, and evicted allocations remain alive until their queued
reads have completed.
In a later commit, the shared cache was extended to cover vendored Prewitt,
Sobel, and Laplace, plus public separable Sobel, Prewitt, Scharr, and Farid
filters.
Remove synchronization and improve efficiency of clipping
Higher-order interpolation previously synchronized to read the clipping range
and to decide whether constant padding expanded that range. Most clipping now
uses device-resident reductions and device-side decisions. Intermediate-sized
constant-mode inputs retain the old host-side short-circuit to avoid the
measured regression when
cvalis within the input range. A combined reductioncarries NaN-safe extrema and a NaN flag together, avoiding separate image scans
and the synchronization in CuPy's public
nanmin/nanmaxwarning checks.Float32 comparisons preserve subnormal extrema despite CuPy's flush-to-zero
compilation. All-NaN results retain their NaN behavior; this clipping path omits those
host-side warning checks. The constant-fill path retains the distinction
between NaN-propagating and NaN-ignoring output range checks based on the input.
A generic scalar CuPy reduction uses a single block. C-contiguous arrays of at
most 512 KiB use it directly to avoid staging overhead; strided inputs retain
the conservative 4096-element cutoff. Larger contiguous real inputs compute
partial ranges in parallel and merge them in the last finishing block of the
same kernel launch. Float16, complex, and strided inputs retain separate partial
and merge launches, including a separate incomplete-tail reduction when needed.
Both approaches read each image element once for the range computation; the
merge only reads the small arrays of partial results.
The terminal-level shape check also applies to finite layer limits, avoiding a
discarded reduction after the last useful layer.
More details on individual changes made
Caching-based improvements
radius, and dtype.
- Reuse the cached kernels in both
gaussian_filterandgaussian_filter1dinstead of rebuilding the NumPy coefficients and copying them to the GPU
for every call and every filtered axis.
- Store Gaussian coefficients in the filter's working dtype. Coefficients are
still generated and normalized in NumPy's existing precision, then cast
during the initial transfer. This avoids repeated
float64-to-float32conversion kernels on cache hits, including two conversions per 2D
float32pyramid reduction. The cache byte limit uses the stored dtype.- Initialize cacheable Gaussian kernels on a private non-blocking stream,
waiting only for that stream before publishing them. This preserves safe
cross-stream reuse without draining the caller's stream or adding per-hit
event waits. Oversized kernels retain asynchronous same-stream behavior.
- Keep cache memory bounded: the LRU holds at most 64 entries, and individual
kernels larger than 1 MiB bypass the cache. Cached kernel data is therefore
limited to approximately 64 MiB per process, plus evicted storage still
needed by queued consumers. Completion events protect this storage from
premature reuse; subsequent misses reclaim completed allocations.
and dtype instead of rebuilding and copying it for every pyramid level.
- Bound the zoom-factor cache to 128 tiny entries. Factor arrays use the
same private initialization stream and allocation-lifetime protection as
Gaussian coefficients, without per-hit CUDA operations.
and public separable Sobel, Prewitt, Scharr, and Farid filters. A shared
64-entry cache keys coefficients by device, dtype, and magnitude normalization,
using the same initialization and allocation-lifetime policy as the other caches.
Miscellaneous Other Improvements
ndimage.gaussian_filterdirectly from pyramid smoothing,using
axesto exclude the channel axis while avoiding redundant wrapperwork. Sigma sequences covering just the spatial axes now also work with
channel_axis.including when a finite
max_layerexceeds the available pyramid levels.- Keep resize/warp clipping bounds on the device for nonconstant modes and
small or large constant-mode inputs. Higher-order pyramid interpolation
benefits from this shared clipping path. Constant-fill range checks and
clipping are fused, preserving unused
cvaland NaN behavior.- For constant-mode inputs larger than 512 KiB and at most 16 MiB, retain the
host-side input range check so an in-range
cvalavoids output reductions.Inputs without NaNs use ordinary extrema and fused clipping when
cvalis outside the range; NaN-containing inputs fall back to combined ranges.
This deliberately restores one or two host readbacks in this size band.
- Compute NaN-safe minimum, maximum, and a NaN flag together in one scan of
each image. Small images use one combined reduction kernel; larger images
use parallel partial ranges followed by a merge. Strided arrays are reduced
through views without copying the full image to flatten it. This replaces
two separate reductions for nonconstant clipping and six for constant-mode
clipping with one combined range computation per participating image when
using the device-side path.
- Add keyword-only
assume_finite=Falsetoresizeand all four pyramid APIs.Opting in promises finite inputs and intermediates, selecting ordinary min/max
reductions without NaN detection or host range checks. Generators forward the
promise through every level without rescanning the initial image. Constant
mode rejects nonfinite
cvalvalues when opting in; defaults are unchanged.Each API's Notes identifies this as a cuCIM-only extension and warns that
violating the finite-value promise may skip output clipping.
- Use the direct single-block reduction for C-contiguous arrays up to 512 KiB,
independently of the 4096-element chunk size used for staged reductions.
Other layouts retain the 4096-element direct cutoff. This reduces staging
overhead for intermediate image sizes without assigning large images to a
single block.
Follow-up optimizations
The following measurements compare each update with its preceding implementation,
rather than measuring cumulative gains against
main.C-contiguous arrays into a 2D view for the existing shared-memory kernel.
At 4096² RGB, the axis-0 Gaussian pass improved 2.25x (1.54 to 0.68 ms),
and the complete two-axis Gaussian call improved 1.54x (3.12 to 2.02 ms).
Small cases were close to unchanged. A separate correctness fix also restores
copying computed filter results back to overlapping output buffers.
as independent leading rows, a filtered axis, and independent trailing values.
A shared-memory tile packs small trailing strides into full warps; larger
strides reuse the existing 3D kernel. Boundaries map only the filtered axis,
preserving trailing components. Short axes and unsupported layouts retain
the elementwise path. This extends the common
correlate1d/convolve1ddispatch used by Gaussian, uniform, and separable edge filters; zero-weight
taps retain the elementwise implementation's NaN/Inf behavior.
Relative to
48cc7f00, the 4096² RGB axis-1 Gaussian pass improved 2.34x(1.44 to 0.62 ms), and the complete two-axis call improved 1.60x
(2.05 to 1.28 ms). Complete 4096² RGB Laplacian pyramids (
max_layer=6) improved 1.33xfor order 1 and 1.07x for order 3; Gaussian pyramids improved 1.08x
for order 3, while the already-fused order-1 path was unchanged.
At 1024² RGB, complete public Sobel, Scharr, Prewitt, and Farid calls improved
1.07x–1.10x; vendored uniform filtering improved 1.10x and
Gaussian–Laplacian 1.22x, while vendored Sobel stayed close to unchanged.
On 64×256×256 volumes filtered over all three axes, complete Gaussian,
Gaussian–Laplacian, and public Sobel calls improved 1.50x, 1.56x,
and 1.14x, respectively.
preserve_range=Truefor already convertedpyramid images and let Gaussian filtering allocate its output. Complete
order-1 pyramids improved up to 1.14x; the largest GPU-bound cases were
close to unchanged.
inputs with even spatial dimensions,
downscale=2,order=1, and scalarsigma from 0 through 4, combine Gaussian smoothing with adjacent-sample
averaging in separable strided correlations. Each pass computes only retained
samples; other inputs use the existing path. Boundary mapping is retained,
but reassociation changes floating-point rounding. Complete Gaussian pyramids
improved 2.08x at 4096² grayscale, 3.34x at 4096² RGB, and 2.28x
at 8192² grayscale with the default sigma.
with the smoothed image, saving one allocation per reduced level. The input,
smoothed image, and previous yields remain intact. Complete-call timings were
near unchanged, within about 4% of the baseline.
so the last finishing block merges partial ranges without a second launch
or a spin wait. Float16, complex, and strided inputs retain the staged fallback.
Range-only GPU-event speedups were 1.15x–3.07x, with host-call
speedups of 2.43x–3.44x across the measured float32/float64 cases.
Benchmark Results
Refreshed on 2026-10-21. These tables compare
main(a3d57b6d) withPyramid, including the interpolation base's spline kernels. Order-3 timings
were recorded at 686cf926, whose runtime code matches the current Pyramid
tip 4f8f8736 on interpolation base 81db51e2. Order-1 and standalone
Gaussian results are retained from ebeecbe6; those paths do not use the
spline prefilter. All results report cumulative gains over
main, ratherthan isolating this MR's changes relative to its interpolation base.
All table timings are GPU-event milliseconds for complete calls, with pyramid
generators fully materialized. Unless specified otherwise, inputs are float32,
max_layer=6,downscale=2,preserve_range=True, andmode="reflect".pyramid_gaussian, order 1Grayscale inputs. Geometric-mean speedups across eight sizes are 6.31x for
GPU-event time and 7.35x for host-call time. This path includes fused
smoothing/downsampling for eligible inputs, cached coefficients, and reduced
per-level setup overhead.
| Input shape | Before (ms) | After (ms) | Speedup |
| --- | --- | --- | --- |
| 64 x 64 | 2.806 | 0.395 | 7.11x |
| 128 x 128 | 2.830 | 0.386 | 7.32x |
| 256 x 256 | 2.834 | 0.390 | 7.27x |
| 512 x 512 | 2.842 | 0.393 | 7.23x |
| 1024 x 1024 | 2.808 | 0.395 | 7.12x |
| 2048 x 2048 | 2.839 | 0.394 | 7.21x |
| 4096 x 4096 | 2.857 | 0.410 | 6.97x |
| 8192 x 8192 | 3.270 | 1.277 | 2.56x |
pyramid_gaussian, order 3Grayscale inputs. Geometric-mean speedups across eight sizes are 3.23x for
GPU-event time and 4.14x for host-call time. This path includes the
interpolation base's spline gain fusion, workspace copy removal, scalar
metadata arguments, and segmented-scan kernels for strided, contiguous, and
interleaved lines, plus Gaussian and clipping updates.
| Input shape | Before (ms) | After (ms) | Speedup |
| --- | --- | --- | --- |
| 64 x 64 | 5.630 | 2.119 | 2.66x |
| 128 x 128 | 5.650 | 2.074 | 2.72x |
| 256 x 256 | 5.651 | 2.023 | 2.79x |
| 512 x 512 | 5.725 | 1.989 | 2.88x |
| 1024 x 1024 | 5.846 | 1.881 | 3.11x |
| 2048 x 2048 | 7.528 | 1.896 | 3.97x |
| 4096 x 4096 | 13.239 | 2.581 | 5.13x |
| 8192 x 8192 | 32.429 | 10.054 | 3.23x |
At 8192 x 8192, host-call time falls from 32.421 to 1.921 ms, while GPU-event
time improves 3.23x. The remaining large-image spline and filtering work still
limits device throughput.
RGB and constant-padding coverage
RGB inputs use
channel_axis=-1. Reflect-mode gains:| Shape | Order-1 speedup | Order-3 before (ms) | Order-3 after (ms) | Order-3 speedup |
| --- | --- | --- | --- | --- |
| 128 x 128 x 3 | 7.78x | 5.859 | 2.111 | 2.78x |
| 512 x 512 x 3 | 7.78x | 5.917 | 2.093 | 2.83x |
| 2048 x 2048 x 3 | 7.48x | 10.681 | 2.147 | 4.98x |
| 4096 x 4096 x 3 | 5.05x | 23.805 | 7.932 | 3.00x |
Constant-mode order-3 cases cover spatial sizes 128, 512, 2048, and 4096. The
fills are the original input's min/max midpoint and
cval=2, outside thenormalized input range. Fill membership is still checked per level.
| Layout | Fill | Default-path speedup range |
| --- | --- | --- |
| Grayscale | midpoint | 2.15x–3.25x |
| Grayscale | outside | 2.45x–3.33x |
| RGB | midpoint | 1.79x–2.36x |
| RGB | outside | 1.96x–2.48x |
new
assume_finite=Truekeyword-only argumentThese ratios compare the full branch's default path with its finite-input path
on the same finite data. Values below one mean opting in was slower. The
promise is forwarded across levels; range computation remains per-level work.
The opt-in is not a uniform throughput gain.
| Cases | Extra GPU-event speedup range | Geometric mean |
| --- | --- | --- |
| Reflect, grayscale | 0.95x–1.01x | 0.98x |
| Reflect, RGB | 0.95x–0.98x | 0.96x |
| Constant, input-midpoint fill | 0.97x–1.53x | 1.11x |
| Constant, outside fill | 0.99x–1.57x | 1.15x |
Standalone
filters.gaussian, sigma=1, warm cacheComplete Gaussian calls with the default
mode="nearest", measured separatelyfrom pyramid construction:
| Input shape | Before (ms) | After (ms) | Speedup |
| --- | --- | --- | --- |
| 64 x 64 | 0.332 | 0.100 | 3.33x |
| 128 x 128 | 0.334 | 0.103 | 3.25x |
| 256 x 256 | 0.323 | 0.102 | 3.16x |
| 512 x 512 | 0.334 | 0.102 | 3.27x |
| 1024 x 1024 | 0.332 | 0.108 | 3.07x |
| 2048 x 2048 | 0.381 | 0.183 | 2.09x |
| 4096 x 4096 | 0.668 | 0.469 | 1.42x |
Across all 21 Gaussian configurations (seven sizes and sigmas 0.25, 1, and 4),
GPU-event speedups range from 1.14x–3.33x, with a median of 3.17x.
Host-call speedups range from 3.12x–3.55x.
Standalone edge filters, warm cache
Measured on 2026-10-22 for complete public
cucim.skimage.filtersmagnitudecalls on float32 grayscale images, with
axis=Noneandmode="reflect".These comparisons isolate coefficient caching: before is its parent
e9d80af1, and after isf3a6fcfa. Each cell reports before → after inmilliseconds (speedup).
| Input shape | Sobel | Prewitt | Scharr | Farid |
| --- | --- | --- | --- | --- |
| 64 x 64 | 0.285 → 0.177 (1.61x) | 0.275 → 0.180 (1.53x) | 0.272 → 0.182 (1.49x) | 0.268 → 0.184 (1.46x) |
| 128 x 128 | 0.280 → 0.181 (1.55x) | 0.278 → 0.180 (1.55x) | 0.276 → 0.178 (1.55x) | 0.272 → 0.185 (1.47x) |
| 256 x 256 | 0.277 → 0.181 (1.53x) | 0.278 → 0.180 (1.55x) | 0.280 → 0.176 (1.59x) | 0.276 → 0.184 (1.50x) |
| 512 x 512 | 0.282 → 0.181 (1.56x) | 0.278 → 0.179 (1.55x) | 0.280 → 0.179 (1.56x) | 0.274 → 0.181 (1.52x) |
| 1024 x 1024 | 0.283 → 0.186 (1.52x) | 0.277 → 0.183 (1.51x) | 0.277 → 0.183 (1.51x) | 0.276 → 0.186 (1.49x) |
| 2048 x 2048 | 0.570 → 0.479 (1.19x) | 0.566 → 0.480 (1.18x) | 0.569 → 0.478 (1.19x) | 0.568 → 0.482 (1.18x) |
| 4096 x 4096 | 1.799 → 1.722 (1.04x) | 1.797 → 1.723 (1.04x) | 1.800 → 1.723 (1.04x) | 1.796 → 1.728 (1.04x) |
GPU-event speedups are 1.46x–1.61x through 1024², 1.18x–1.19x at
2048², and about 1.04x at 4096². Host-call speedups across these cases
are 1.51x–1.65x.