Improve performance of spline prefiltering #1182
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 #1182"
general
weight: 0.35
gigony
Context
Higher-order interpolation (order >= 2) prepares spline coefficients with
causal and anti-causal IIR recurrences. This spline prefiltering step can
take substantially more time than the subsequent interpolation kernel. This MR
parallelizes eligible prefilter passes and removes redundant memory passes,
copies, and per-call metadata transfers. It also reduces repeated coordinate
arithmetic in batched interpolation, and replaces the 12-sample pre-padding of
mode="nearest"andmode="grid-constant"with exact boundary handling(Optimization 4). Public signatures are unchanged.
These changes complement other interpolation performance MRs from earlier this
year (#1055, #1060). With those improvements, the spline prefilter became the
dominant cost.
On
main, preparing spline coefficients consumed 88–95% of GPU kerneltime in representative order-3 rotations, motivating the focus of this
MR. The appendix compares that share with the final implementation.
Two new cooperative kernels accelerate real float32/float64 workspaces, while
the general per-line kernel handles complex-valued and remaining cases not
eligable for these faster cooperative kernels. All three kernels support spline
orders 2–5 and reuse the existing boundary formulas. Public signatures are
unchanged; regrouping recurrences can change floating-point rounding. The output
matches the prior implementation to within a small floating point tolerance.
Here a line varies along the filtered axis with all other indices fixed;
a sample is one value along that line. Consecutive samples follow axis
order and need not occupy adjacent memory addresses. For C-contiguous arrays,
their stride is 1 element along the last axis, 3 along the width of an RGB
image, and the image width along axis 0 of a 2D image.
Optimization 1: Shared-memory warp prefilter for contiguous and interleaved lines
Commits: a007518c (kernel), 7497fd92 (device-aware float64 dispatch),
and 930ca7ef (bank-access explanation). Shared kernel documentation:
d96e26aa (also covers Optimization 2).
This kernel increases within-line parallelism from one thread per line to
one warp (32 threads) per contiguous line. For interleaved data
(e.g. RGB or RGBA images), one warp handles a group of 2–4 channel lines
together. Each warp stages a contiguous line, or a contiguous
(samples, channels)block with 2-4 interleaved lines, using coalesced globalloads. A "lane" is a thread's position within a warp. Each lane handles a
run: a consecutive chunk of samples along the filtered line. Lanes
summarize their chunks, combine the summaries through warp shuffle scans, then
filter their chunks in shared memory and store results coalesced. The same
kernel handles scalar, RGB/RGBA, and other small trailing dimensions, and
accepts element-aligned output views.
For one sample, the forward recurrence is
y[i] = zy[i-1] + gx[i], wherex[i]is the current line's input value (an image sample or an intermediateresult from earlier filtering), and
y[i]is the intermediate coefficientafter this causal update. The reverse sweep and any remaining poles complete
the spline coefficients for this axis.
zis the spline pole, andgis thenormalization gain required for conversion to spline coefficients: 6 for
cubic (order 3), or 120 for quintic (order 5). The gain is fused into the
first pole's forward sweep on each axis; subsequent poles use
g = 1.Each chunk needs the filtered value immediately before it: its incoming
carry. Its final filtered value is the outgoing carry needed by the next
chunk.
A run map summarizes a whole chunk as
y_out = Ay_in + B, wherey_inandy_outare its incoming and outgoing carries. Formforwardupdates,
A = zm;Bcombines the contributions of that chunk's inputsamples, including the gain. Thus
(A, B)describes the chunk's effect onthe same filtered state
y.Carry propagation means determining these boundary values across chunks.
The reverse sweep uses the same idea with the traversal direction reversed.
To determine the carries in parallel, we use the prefix scan illustrated for
summation in GPU Gems 3, §39.2.1 and Figure 39-2.
Here addition is replaced by associative composition of the run maps:
for two consecutive chunks, let
y0be the incoming carry,y1the valueafter the first chunk, and
y2the value after the second:The combined chunk therefore has summary
(A2A1, A2B1 + B2).This reduction of first-order recurrences to scans is
derived in Blelloch, Prefix Sums and Their Applications, §1.4.1.
The five shuffle rounds use
__shfl_up_sync;__syncwarpseparates sharedmemory handoffs, as described in Using CUDA Warp-Level Primitives.
Staging separates coalesced global transfers from each lane's recurrence
accesses, analogous to Coalesced Transpose Via Shared Memory in
An Efficient Matrix Transpose in CUDA C/C++.
Its Shared Memory Bank Conflicts section explains the related layout principle
behind our odd run lengths; our kernel changes the run partition rather than
padding a transpose tile.
After this new kernel was implemented, a search for pre-existing
implementations identified that this same sort of linear recurrence pattern
also comes up in the Mamba neural network architecture. For more about these
patterns for the Mamba use case, please see Sarnthein's
Linear Recurrences Accessible to Everyone.
A concrete example of the same pair-composition rule in production is Mamba's
SSMScanOp<float>Kernel Dispatch Criteria
Dispatch to this kernel requires sufficient device shared memory as well as at
least 32 samples to provide sufficient work for the 32-lane warp and amortize
cooperation overhead. At an FP32:FP64 throughput ratio of 64:1, float64 uses
the staged path for lines of at least 512 samples, or at most 256
single-channel lines; otherwise serial boundary initialization can outweigh
the parallel recurrence. A cached per-device CUDA ratio scales these
restrictions on GPUs with stronger FP64, reaching the float32 shape rules at
4:1 or better. Missing or invalid ratios retain the 64:1 defaults. This
scaling is a heuristic; the measurements below use the unchanged RTX A6000
dispatch. Strided cases outside this dispatch use the segmented kernel;
remaining cases use the general fallback.
Performance
Against the retained general kernel, contiguous-axis calls improved
2.32–7.81x for float32 (orders 3 and 5) and
2.68x for float64 (order 3) in the 512²/2048² cases.
For interleaved lines, the staged warp path improved 2.48–3.46x
for float32 RGB/RGBA and 2.81x for float64 RGB, compared
with the retained segmented kernel. These one-axis calls also include their
workspace initialization copy.
Optimization 2: Block-parallel prefilter for strided axes
Commits: b26e94e5 (kernel) and d96e26aa (shared kernel documentation).
After introducing within-line parallelism for contiguous lines, Nsight
Systems identified the still-serial axis-0 prefilter as a major remaining
cost. The second cooperative kernel family extends within-line parallelism
to strided axes while preserving coalesced accesses across neighboring lines.
For a non-last axis of a C-contiguous workspace, a block handles 32 adjacent
lines and splits each line into runs. At a fixed position along the filtered
axis, adjacent lanes read neighboring values in dimensions after that axis
in the array's shape—for axis 0 of a 2D image, neighboring columns. This
preserves coalesced global accesses. Shared memory holds each run's affine
carry map; composing these maps supplies the
incoming state before each thread replays its run. This adds parallelism
within long lines without staging the entire strided axis.
This kernel reuses the first-order recurrence composition described above,
combining run summaries through shared memory and block barriers instead of
a warp shuffle scan. Mapping neighboring lanes to neighboring memory
locations follows the same coalescing principle described in the matrix
transpose reference; it does not stage or transpose the image data.
This local-summary, boundary-reconstruction, and replay pattern has direct
spline-specific prior art. Nehab et al. (2011), §§1, 4.3, and 8.
compute bicubic and biquintic B-spline coefficients using blocked recursive
filters. Chaurasia et al. (2015), §6.1 and §8
explain the local-filter, boundary-aggregation, and recomputation steps and
apply them to bicubic B-spline interpolation. Both share the recurrence
decomposition used by our two cooperative kernel families. Their image-wide
tiled pipelines differ from this kernel's processing of each line within
one thread block. These references were discovered by literature search
after this implementation was complete.
Against the retained general kernel, complete one-axis calls improved
2.70–6.71x for float32 at 512²/2048² (orders 3 and 5), and
3.49x for float64 at 2048² (order 3). These isolated dispatch
comparisons include the initial copy into a supplied output workspace.
Optimization 3: Reduce memory passes, metadata transfers, and transform setup
Commits: 1f1f730f (batch coordinates), 0d1e45e9 (gain fusion),
8d5384e1 (general-kernel launch sizing), 1edc3448 (workspace reuse),
3328d790 (scalar metadata), 87a98fd2 (host rotation setup),
8efca35a (host OpenCV zoom/shift setup), and 48d8533a (single-kernel
edge pre-padding).
Fuse spline gain into the first causal pass. Filter initialized workspaces
in place from the first axis, reuse private padded arrays, and skip self-copies.
Caller inputs retain their existing ownership and output/dtype behavior.
Pass counts and dimensions as runtime scalar kernel arguments instead of
allocating and uploading a metadata array for each filtered axis. Tune the
general fallback's block size for contiguous and low-stride lines.
Batched interpolation omits known-zero coordinate terms and reuses outer batch
offsets. Rotation keeps host matrices on the host through affine setup,
avoiding device uploads followed immediately by host readbacks.
With cooperative kernels absent, the gain/workspace/metadata/launch updates
improved complete prefilter GPU-event timings 1.08–2.63x and host-call
timings 2.67–2.84x across six selected cases. This isolates the
supporting changes; the net rotation results below also include coordinate
and host-matrix setup improvements.
Optimization 4: Exact boundaries for
nearestandgrid-constantCommit: a9502819.
SciPy has exact prefilter initializations only for
mirror,reflect(
grid-mirror) andgrid-wrap. Fornearestandgrid-constantit padsthe input by 12 samples per side, filters the padded array with the reflect or
mirror initialization, and clamps (or uses
cval) beyond the padding;cuCIM did the same. Briand and Monasse (IPOL 2018, §3.2) explain why: a
constant extension is not preserved by the exponential filters, so it cannot be
handled on the signal's own domain like the symmetric and periodic
extensions, and they extend the domain instead. The padding is accurate inside
the array (a few 1e-9 for order 5 in float64) but not exact, its error grows
outside the array (up to ~2e-4 for order 5), and it costs a padding kernel plus
24 extra samples per axis in every prefilter pass.
The constant extension does have a closed form, derived for this MR from
the recursions (no published version was found): outside the line, every
sequence the prefilter produces is an exponential polynomial
sum_r a_r rm, with roots 1 (the constant) and the poles applied so far.Each causal or anti-causal pass maps such tails to new tails in closed form,
so every initial value is a finite sum of at most three terms per side:
The interpolation kernel also needs coefficients outside the array. Those are
fixed linear combinations of the first (or last)
J + 1coefficients(
J= number of poles), obtained from the tail form and the interpolationcondition at the extended samples; for the cubic spline,
c[-m] = cval + zm (c[0] - cval)forgrid-constant. The kernel foldsthese weights into each axis's B-spline weights inside a branch taken only
near the edges, so each output still reads
(order + 1)ndimcoefficientsand no padded array exists. The formulas and their derivation are documented
in the code above
EXACT_CONSTANT_MODES(_ndimage_spline_prefilter_core.py)and in
exterior_coefficient_terms.Scope and compatibility:
interpolated axis has at least
order + 1samples and the input is real;other cases keep the padded path.
spline_filter/spline_filter1dkeep SciPy's behavior for thesemodes, as does interpolation with
prefilter=False, since callers may pairthem with coefficients computed the SciPy way.
~2e-4 outside the array for order 5 in float64 (smaller for lower orders).
Max absolute error against the infinite extension (float64
map_coordinates,23 × 31 standard-normal image,
cval=0.4, 400 points inside and 400 up to30 pixels outside the array; the reference is a 200-sample padded prefilter):
| Order | Mode | Padded, inside | Padded, outside | Exact, inside | Exact, outside |
| --- | --- | ---: | ---: | ---: | ---: |
| 3 |
nearest| 7.1e-14 | 1.6e-7 | 7.2e-14 | 5.1e-14 || 3 |
grid-constant| 1.3e-13 | 3.6e-7 | 7.2e-14 | 4.7e-14 || 5 |
nearest| 3.8e-10 | 1.1e-4 | 7.3e-14 | 5.3e-14 || 5 |
grid-constant| 3.6e-9 | 2.2e-4 | 7.9e-14 | 4.7e-14 |In float32 both paths are limited by float32 rounding: for a 2048²
standard-normal image the maximum error against a float64 call is
5.9e-4–1.1e-3 for
shift,rotateandzoomwith either path (4.9e-4instead of 1.0e-3 for
zoom, which no longer adds the 12-sample offset toits float32 coordinates).
Performance against the preceding commit (
48d8533a), float32, GPU-eventmeans (
bench_spline_constant_boundary.py ab, 36 cases): 1.01–1.36x fornearestand 1.16–1.91x forgrid-constant, which previously also paidfor a bounds test per coefficient in the interpolation kernel.
| Call | Order |
nearest: padded → exact (ms) |grid-constant: padded → exact (ms) || --- | ---: | --- | --- |
|
shift,(512, 512)| 3 | 0.139 → 0.132 (1.05x) | 0.192 → 0.136 (1.41x) ||
shift,(2048, 2048)| 5 | 0.659 → 0.516 (1.28x) | 0.761 → 0.517 (1.47x) ||
shift,(256, 256, 256)| 5 | 4.659 → 3.428 (1.36x) | 6.063 → 3.436 (1.76x) ||
zoom×2,(2048, 2048)| 5 | 1.080 → 0.852 (1.27x) | 1.335 → 0.847 (1.58x) ||
zoom×2,(128, 128, 128)| 5 | 2.894 → 2.210 (1.31x) | 4.262 → 2.226 (1.91x) ||
rotate15°,(512, 512)| 3 | 0.214 → 0.207 (1.03x) | 0.241 → 0.207 (1.16x) ||
rotate15°,(2048, 2048)| 3 | 0.482 → 0.411 (1.17x) | 0.552 → 0.411 (1.34x) |test_spline_exact_boundary.pycomparesmap_coordinates,shift,affine_transform,zoom(withgrid_mode), a looped RGB batch axis andinteger output against the infinite extension for orders 2–5, including
points far outside the array (1e-11 absolute tolerance in float64), and checks
the fallback and the unchanged public
spline_filter.Combined result summary
With all changes, complete prefilter calls improved 2.27–6.93x
against
main(12e69a22, whose sources differ fromrelease/26.12only in CI workflow files). Complete float32 rotations improved
5.26–5.78x for the two grayscale images and
3.42x* for the batched RGB case. These are direct
branch-versus-main measurements (branch
a9502819, re-measured 2026-11-11);the individual ranges above use separate controls and should not be
multiplied. These calls use
mode="reflect"; Optimization 4 adds thenearest/grid-constantgains on top.| Measured call | Input / dtype / order | Main (ms) | Branch (ms) | Net speedup |
| --- | --- | ---: | ---: | ---: |
| Complete
spline_filter|(64, 64), float32 / 3 | 0.196 | 0.056 | 3.47x || Complete
spline_filter|(512, 512), float32 / 3 | 0.263 | 0.057 | 4.59x || Complete
spline_filter|(2048, 2048), float32 / 3 | 1.856 | 0.268 | 6.93x || Complete
spline_filter|(512, 512), float32 / 5 | 0.333 | 0.065 | 5.11x || Complete
spline_filter|(512, 512), float64 / 3 | 0.318 | 0.140 | 2.27x || Batch-aware prefilter |
(2, 512, 512, 3), float32 / 3 | 0.490 | 0.093 | 5.26x || Complete
rotate|(1920, 1080), float32 / 3 | 1.696 | 0.293 | 5.78x || Complete
rotate|(1080, 1920), float32 / 3 | 1.464 | 0.278 | 5.26x || Complete
rotate|(2, 512, 512, 3), float32 / 3 | 0.816 | 0.239 | 3.42x |Complete prefilter calls include allocation and required copies. Complete
rotatecalls also include interpolation (angle 17°,reshape=False,mode="reflect", order 3).Measurements
RTX A6000, CuPy 14.2.0 and
cupyx.profiler.benchmark(max_duration=2.0)withten warmups.