Skip to content

Speed up cubic interp2d and interp3d - #214

Open
nstarman wants to merge 15 commits into
f0uriest:mainfrom
nstarman:perf/interp2d-3d-hermite-basis
Open

nstarman wants to merge 15 commits into
f0uriest:mainfrom
nstarman:perf/interp2d-3d-hermite-basis

Conversation

@nstarman

@nstarman nstarman commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Speeds up cubic interp2d and interp3d (and so Interpolator2D and Interpolator3D), using the same idea as #213 for 1D.

Bicubic and tricubic interpolation from f and its mixed first derivatives at the cell corners is the tensor product of the 1D cubic Hermite basis. So each query now needs 2ⁿ corner weights per field, built from the 1D basis along each axis. Before, every coefficient of the cell's polynomial was formed with a 16×16 (2D) or 64×64 (3D) matmul per query and per trailing element. _cell_coefficients, _get_t_der and the A_BICUBIC/A_TRICUBIC matrices in _coefs.py are no longer used and are removed.

As in #213:

  • the weights are computed in at least float32 and at least the precision of f and its derivatives;
  • the corners are differenced along each axis first, so the value terms cancel exactly, and each axis's dxi**derivative factor is applied to the sum in turn at the end, since in float32 their product alone can overflow on small cells where the result does not. With float32 and extreme cell sizes, or extreme ratios of cell sizes between axes, derivatives can still overflow or underflow, as they can on main; the interp2d and interp3d docstrings now say to use float64 there;
  • the result has the dtype of f and its derivatives promoted with the knots and queries, as before, so a complex fx with real f stays complex.

On the new bfloat16 test's data (seed 0), the largest error is 0.2% of the largest value, where main reaches about 5%.

This builds on #213, which adds the 1D basis helper _hermite_basis. Until that merges, the diff here includes its commits, so only the commits after #213's are new. One of them changes _hermite_basis to return the weight of f0 after f1 - f0 is taken (1 for the value, 0 for derivatives), which both the 1D and the 2D and 3D code use in place of their own where. Results before and after that commit are bit-identical in 1800 random cases (1D, 2D and 3D; float32, float64 and complex; all five cubic methods; derivative orders −1 to 4).

Results match the previous implementation to round-off (within 4e-13 of the largest value in 220 of 221 random cases; the other, a second derivative on a 0.005-wide cell, is closer to an exact rational evaluation than main) for the cubic, cubic2, catmull-rom, monotonic and akima methods, derivative orders up to 4, real and complex f, trailing axes, periodic axes and extrapolation. A new test checks separable data against products of 1D CubicHermiteSplines, which is independent of either implementation and also passes on main. Another checks bfloat16 results against the same rounded inputs, derivatives included, interpolated in float64. A third checks complex fx with real f, and float32 knots with float64 values in both interp2d and interp3d. A fourth checks float32 gradients with respect to the knots against float64, a fifth checks float32 high-order derivatives on small cells against float64, and a sixth checks that a large constant part of float32 f cancels exactly in derivatives.

Timings on CPU, single-threaded XLA, jax 0.8.0, float64, Interpolator2D on a 64×48 grid and Interpolator3D on 32³, method "cubic". "Scalar" is one query per step inside a lax.scan. The batched numbers are the best of two runs.

0.3.16 this PR
2D, scalar query 530 ns 97 ns
2D, scalar query, 10 trailing 2.7 µs 0.49 µs
2D, 4096 queries 420 µs 213 µs
2D, 4096 queries, 10 trailing 1.5 ms 0.48 ms
3D, scalar query 2.1 µs 0.64 µs
3D, scalar query, 10 trailing 56 µs 1.5 µs
3D, 4096 queries 1.3 ms 0.5–0.6 ms
3D, 4096 queries, 10 trailing 12 ms 2.4 ms

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.33%. Comparing base (98a3fee) to head (2b5b557).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #214      +/-   ##
==========================================
- Coverage   98.35%   98.33%   -0.02%     
==========================================
  Files           8        8              
  Lines        1699     1679      -20     
==========================================
- Hits         1671     1651      -20     
  Misses         28       28              
Files with missing lines Coverage Δ
interpax/_coefs.py 100.00% <ø> (ø)
interpax/_spline.py 98.62% <100.00%> (-0.05%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nstarman
nstarman force-pushed the perf/interp2d-3d-hermite-basis branch from f12dc87 to c3870c9 Compare November 23, 2026 21:35
nstarman and others added 13 commits November 24, 2026 09:00
Compute the Hermite basis weights once per query and broadcast them over the
trailing axes of f, instead of forming every cubic's coefficients with a 4x4
matmul per query and trailing element. Index f with scalars for a scalar
query, so XLA slices rather than gathers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Scaling the zero weights of derivatives above the third by dxi**4 gave
0 * inf = nan where that factor overflows. Scale each derivative branch by
its own power of dxi, and clamp a negative derivative to 0 as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summing the Hermite terms elementwise in half precision rounded every term,
where the old matmul ran at full precision. Cast the result back to the dtype
of f.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cast the result to the dtype of f and fx rather than of f alone, compute the
weights in at least the precision of f and fx, and take f1 - f0 first so the
value weights cancel exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Hermite basis now returns the weights as polynomials in t together
with a single scale (1, dxi, dxi**2 or 6*dxi**3), applied once after the
weighted sum. This keeps the rounding of f32 and bf16 derivatives close
to the 4x4 matmul it replaces, and the zero branch uses scale 1 so tiny
cells never form 0*inf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Evaluate the bicubic and tricubic interpolants as the tensor product of the
1D cubic Hermite basis: 2**n corner weights per field and query, rather than
forming every cell coefficient with a 16x16 or 64x64 matmul per query and
trailing element. Remove the now unused _cell_coefficients and _get_t_der.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The result of the cubic branch is cast to the data dtype promoted with the
knots and queries, as on main, so float32 data queried in float64 gives
float64 from the interpolators as it does from interp2d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The product of the per-axis scales alone overflows float32 on small cells
where the result does not, which gave inf, or nan for zero data, at high
derivative orders. Applying each axis's scale to the sum in turn keeps
those results finite, as on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Applying the per-axis scales in turn could still overflow or underflow in
float32 when cells are small along one axis and large along another. With
float32 weights the sum is now multiplied by the product of the scales'
mantissas and then by 2**(their summed exponent) in a few same-sign
factors, each representable. float64 keeps the single product of the
scales, which is as fast as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The frexp split of the scales handled float32 cells of very different
sizes across axes, which are now out of scope, and its mantissa has no
derivative in jax 0.5 and 0.6, which broke float32 knot gradients
there. Go back to applying each axis's scale to the sum in turn, note
in the interp2d and interp3d docstrings that float64 is needed for
extreme cell sizes, and test float32 knot gradients.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nstarman
nstarman force-pushed the perf/interp2d-3d-hermite-basis branch from fb28624 to b334f40 Compare November 24, 2026 14:35
nstarman and others added 2 commits November 25, 2026 11:36
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ices

_hermite_basis now returns the weight of f0 once f1 - f0 is taken, 1 for
the value and 0 for derivatives, in place of the weight every caller
discarded, so interp1d and _hermite_cell no longer special-case it.
_hermite_cell takes the knots, queries and cell indices and does the
per-axis setup that interp2d and interp3d each repeated. A_BICUBIC and
A_TRICUBIC have no users left and are removed. Results are bit-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant