You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
So far I am very pleased with the FastInterpolations.jl performance and feature support. Recently, I am experimenting about porting my test particle tracing to GPU. Currently, I have a customized field interpolation for GPU, trying to match the FastInterpolation support on CPU. This makes me wonder if we can directly support field interpolation here in this package. Do you have any plan to support a subset of the interpolation methods on GPU? Do you envision any obstacles/challenges? Thanks!
Thanks for bringing this up and for sharing your implementation!
GPU support has been on my roadmap, but it hasn’t been a high priority so far, mainly because I haven’t had a concrete use case or received specific requests for it. Now that you’ve brought this up, I think it’s worth taking a closer look.
I’ve also been considering using Adapt.jl or a similar approach to bring parts of the package, particularly interpolation evaluation, to the GPU, though I haven’t tried anything concrete yet. Ultimately, dedicated GPU kernels might be ideal for performance, but that’s probably a longer-term goal.
There are quite a few things we’d need to explore, including practical performance considerations (e.g., CPU–GPU memory transfers) and how much of the interpolation workflow should actually run on the GPU. For more complex interpolants like cubic splines, I suspect building on the CPU and transferring the interpolant for GPU evaluation might be a reasonable starting point.
If you have any specific use cases in mind (e.g., interpolation types, whether GPU evaluation alone would be sufficient), or any insights from your experience with GPU implementations, particularly regarding performance and problem sizes where GPU acceleration becomes worthwhile, that would be really helpful!
I probably won’t have the bandwidth to work on this over the next few weeks, but I’d like to revisit it when I get a chance.
Sorry about the late response! I was in a Hackathon this week. For me the use case is pretty simple right now: I want linear and cubic interpolation support for the EM field on GPU and evaluation alone would be sufficient. I am currently using KernelAbstractions.jl and provide a matrix as my test particle initial conditions. All the particles are traced in the same EM field on GPU. I've recently made some benchmarks about TestParticle.jl, and there's a subsection about GPU trilinear interpolation. Originally I thought Float32 and Float64 would make a large difference, but that only applies to consumer GPUs, not cluster GPUs.
I also have a demo for showing my current GPU interpolation implementation.
A first round of GPU support is implemented in PR #224 (now on master):
linear interpolation in 1D and ND, on any GPUArrays backend (tested on CUDA and Metal).
Interpolants can be built straight from device arrays or moved from the CPU with Adapt.adapt, and they also work as arguments of your own KernelAbstractions kernels, which is probably your use-case.
More detailed information is in the GPU Arrays guide.
It is still experimental and not fully optimized, but it should already be usable for basic interpolations.
Please give it a try when you have a moment; feedback is very welcome.
Cubic and the other methods need more substantial changes, which will come later.
Thanks!
I tried together with Claude the new GPU support in TestParticle.jl, where a KernelAbstractions Boris kernel evaluates gridded E/B fields per particle. FastInterpolations matches the CPU exactly, and its speed is close to our own kernels (cannot really tell which is faster). So we are replacing our hand-written GPU interpolators (~600 lines) with adapt(backend, itp), and will switch once a release includes #224.
Setup: RTX 5070 (consumer card, FP64 at 1/64 rate), Julia 1.13.2 on Windows, CUDA.jl 6.4.2, KA 0.9.45, FastInterpolations master (with #226), TestParticle 0.24.3. Both scripts are attached below.
1. Interpolation only (bench_interp.jl)
4M random points, 5% of them outside the grid. Each time is the best of 7 × 50 kernel launches (out[i] = itp(pts[i])).
Case
T
FastInterpolations
TestParticle (hand-written)
3D uniform 64³, SVector{3}
Float32
0.538 ms
0.534 ms
3D uniform 64³, scalar
Float32
0.382 ms
0.339 ms
2D uniform 512²
Float32
0.283 ms
0.296 ms
1D uniform 4096
Float32
0.159 ms
0.157 ms
3D spherical 64³ (periodic ϕ)
Float32
0.383 ms
0.339 ms
3D uniform 64³, SVector{3}
Float64
1.540 ms
1.783 ms
3D non-uniform 64³
Float64
2.007 ms
(wrong, see below)
On Cartesian grids, FastInterpolations is bitwise identical to the CPU interpolant. On the spherical grid, both implementations differ from the CPU by the same amount (2e-4 in Float32), which comes from the Cartesian↔spherical conversion done in TestParticle's wrapper. The script also checks edge points for each boundary option against the CPU: on the grid edge, one ulp outside, half a cell outside, far outside, NaN, ±Inf. All of them match, for FillExtrap, ClampExtrap, WrapExtrap, 1D PeriodicBC (inclusive and exclusive), and PeriodicBC on the last axis of a 3D grid, with check = true and false.
2. Particle tracing (bench_tracing.jl)
TestParticle's GPU Boris solver with 1e5 particles × 1e4 steps; only the field object passed to the kernel differs.
Grid
T
TestParticle GPU grids
FastInterpolations
3D uniform 64³
Float32
0.146 s
0.189 s
3D spherical 64³
Float32
0.186 s
0.234 s
3D uniform 64³
Float64
0.880 s
0.955 s
3D spherical 64³
Float64
2.508 s
2.489 s
Trajectories from FastInterpolations agree with our CPU solver to 1e-8 in Float32 and 1e-16 in Float64.
Observations for FastInterpolations
Slower inside a larger kernel in Float32. Interpolation alone is at parity with our kernels. Inside the Boris kernel, which evaluates two 3D interpolants per step, FastInterpolations is about 25–30% slower in Float32, and 0–8% in Float64. Our guess is register pressure or occupancy. bench_tracing.jl reproduces it (TO BE CONFIRMED).
Unsupported families pass through adapt without error. This happens for cubic_interp, constant_interp, and the ND interpolant from order-3 cardinal_interp. The result still refers to host memory, and the problem only appears at kernel compile time as a long KernelError/InvalidIRError pointing into the user's kernel. FastInterpolations is the natural place to catch this, since it knows which families have device support. Two options: an ArgumentError when adapting an unsupported family to a GPU array type (leaving adapt(Array, itp) unchanged), or a public query such as supports_device(itp). For now TestParticle checks for LinearInterpolant/LinearInterpolantND itself, which will go stale once cubic support lands.
We are looking forward to the planned cubic support on GPU~
Issues on our side, now fixed by switching
These were bugs in TestParticle's own GPU grids, not in FastInterpolations. The scripts show them, and they go away with the switch.
Non-uniform (rectilinear) grids were converted to uniform ones on the device, so values were wrong everywhere. Tracing error: 40%.
ClampExtrap and WrapExtrap grids failed to compile on the GPU.
FillExtrap grids returned values up to 4 ulp outside the domain instead of NaN, and 1D Float32 lookups lost accuracy (relative error 2e-3).
Float32 spherical grids ending at Float32(π) were rejected by our range check (fixed separately).
# Pure interpolation on the GPU: FastInterpolations.jl device interpolants vs the# hand-written GPU grids in TestParticle.jl v0.24.3 (`GPUGrid*`, `GPUSphericalGrid`).## Environment: TestParticle v0.24.3, FastInterpolations#master, CUDA, KernelAbstractions,# StaticArrays, Adapt.using TestParticle, FastInterpolations, Adapt, CUDA, KernelAbstractions, StaticArrays
using Random, Printf
import TestParticle as TP
const backend =CUDABackend()
println(CUDA.name(CUDA.device()), ", driver ", CUDA.driver_version(), ", Julia ", VERSION)
println("FastInterpolations ", pkgversion(FastInterpolations), " (master), TestParticle ",
pkgversion(TestParticle), "\n")
@kernelfunctioneval_k!(out, f, pts)
i =@index(Global)
@inbounds out[i] =f(pts[i])
endfunctiondevice_eval!(out, f, pts)
eval_k!(backend, 256)(out, f, pts; ndrange =length(pts))
KernelAbstractions.synchronize(backend)
return out
endfunctionbest_time(g; nrep =50, nbatch =7)
g()
returnminimum(_ -> CUDA.@elapsed(for _ in1:nrep; g(); end), 1:nbatch) / nrep
end_isnan(v) =any(isnan, v)
"Max relative error vs the reference, and the number of NaN/non-NaN disagreements."functioncompare(a, ref)
err, nan =0.0, 0for (u, v) inzip(a, ref)
if_isnan(u) ||_isnan(v)
nan +=_isnan(u) !=_isnan(v)
else
err =max(err, maximum(abs, u - v) /max(maximum(abs, v), floatmin(Float32)))
endendreturn err, nan
end## 1. Timing and accuracy on random points ####################################const N =2^22# query points, 5% of them outside the gridrandpts(rng, ::Type{T}, D, lo, hi) where {T} =
[SVector{D, T}(ntuple(_ -> lo + (hi - lo) *rand(rng, T), D)) for _ in1:N]
functionrun_case(name, itp, pts_cpu, fi_dev, tp_dev)
ref =itp.(pts_cpu)
pts =CuArray(pts_cpu)
out =CuArray(similar(ref))
cols =map((fi_dev, tp_dev)) do f
try
t =best_time(() ->device_eval!(out, f, pts))
err, nan =compare(Array(out), ref)
@sprintf("%7.3f ms err %.0e NaN-diff %-7d", 1.0e3* t, err, nan)
catch e
rpad(string(nameof(typeof(e))), 36)
endend@printf("%-30s %-7s | %s | %s\n", name, eltype(eltype(pts_cpu)), cols...)
endprintln("Random points: N = $N. Error and NaN-diff are relative to the CPU interpolant.")
@printf("%-30s %-7s | %-36s | %-36s\n", "case", "T", "FastInterpolations", "TestParticle GPUGrid")
for T in (Float32, Float64)
rng =Xoshiro(1)
n =64
g =range(T(-10), T(10), length = n)
gv =sort!([T(-10); T(-10) .+T(20) .*rand(rng, T, n -2); T(10)])
V3 =rand(rng, SVector{3, T}, n, n, n)
S3 =rand(rng, T, n, n, n)
fill3 =FillExtrap(SVector{3, T}(NaN, NaN, NaN))
p3 =randpts(rng, T, 3, T(-10.35), T(10.35))
for (name, itp, pts) in (
("3D uniform 64^3, SVector{3}", linear_interp((g, g, g), V3; extrap = fill3), p3),
("3D uniform 64^3, scalar",
linear_interp((g, g, g), S3; extrap =FillExtrap(T(NaN))), p3),
("3D non-uniform 64^3, SVector{3}",
linear_interp((gv, gv, gv), V3; extrap = fill3), p3),
("2D uniform 512^2, SVector{3}",
linear_interp(ntuple(_ ->range(T(-10), T(10), length =512), 2),
rand(rng, SVector{3, T}, 512, 512); extrap = fill3),
randpts(rng, T, 2, T(-10.35), T(10.35))),
("1D uniform 4096, SVector{3}",
linear_interp(range(T(-10), T(10), length =4096),
rand(rng, SVector{3, T}, 4096); extrap = fill3),
[T(-10.35) +T(20.7) *rand(rng, T) for _ in1:N]),
)
run_case(name, itp, pts, adapt(backend, itp), TP._to_gpu_grid(itp, backend))
end# Spherical grid as TestParticle builds it: r and θ fill with NaN, ϕ is periodic.# Queries are Cartesian; both sides convert to (r, θ, ϕ) and back.
r =range(T(1), T(10), length = n)
θ =range(T(0), prevfloat(T(π)), length = n) # TestParticle v0.24.3 rejects Float32(π)
ϕ =range(T(0), prevfloat(T(2π)), length = n)
fi = TP.build_interpolator(TP.StructuredGrid, rand(rng, T, 3, n, n, n), r, θ, ϕ)
run_case("3D spherical 64^3, SVector{3}", fi, randpts(rng, T, 3, T(-10.5), T(10.5)),
adapt(backend, fi), TP._to_gpu_spherical_grid(fi.itp, backend))
end## 2. Boundary handling at the edges ############################################ A uniform and a non-uniform 1D axis on [0, 4], and a 3D grid where one coordinate# takes the probe value and the others sit mid-grid. The device result is compared# with the CPU interpolant (isequal, NaN == NaN).const UNIFORM =0.0:1.0:4.0const NONUNIFORM = [0.0, 0.5, 1.5, 3.0, 4.0]
const PROBES = [0.0, 4.0, prevfloat(0.0), nextfloat(4.0), -0.5, 4.5, -12.0, 16.0,
2.25, NaN, Inf, -Inf]
functionedge_report(name, itp, pts, fi_dev, tp_dev)
ref =map(pts) do p
tryitp(p)
catchmissing# CPU throws, e.g. NoExtrap outside the domainendend
pts_d =CuArray(pts)
res =map((fi_dev, tp_dev)) do f
f ===nothing&&return"-"try
out =CuArray(fill(zero(typeof(first(skipmissing(ref)))), length(pts)))
got =Array(device_eval!(out, f, pts_d))
bad = [p for (p, a, b) inzip(pts, got, ref) if!ismissing(b) &&!isequal(a, b)]
isempty(bad) ?"ok":"mismatch at "*join(string.(bad), ", ")
catch e
string(nameof(typeof(e)))
endend@printf(" %-34s FI: %-40s TP: %s\n", name, res...)
endprintln("\nEdge points ", PROBES, "\n(on the grid edges, one ulp outside, half a cell ",
"outside, far outside, inside, NaN, ±Inf)")
let y1 = [SVector(x, 2x, -x) for x in UNIFORM]
for extrap in (FillExtrap(SVector(NaN, NaN, NaN)), ClampExtrap(), WrapExtrap())
println(nameof(typeof(extrap)))
for (gname, g) in (("1D uniform", UNIFORM), ("1D non-uniform", NONUNIFORM))
itp =linear_interp(g, y1; extrap)
tp = g isa AbstractRange ? TP._to_gpu_grid(itp, backend) :nothingedge_report(gname, itp, PROBES, adapt(backend, itp), tp)
endfor (gname, g) in (("3D uniform", UNIFORM), ("3D non-uniform", NONUNIFORM))
itp =linear_interp((g, g, g), [SVector(x, y, z) for x in g, y in g, z in g];
extrap)
pts =vcat(
[SVector(p, 2.25, 2.25) for p in PROBES],
[SVector(2.25, 2.25, p) for p in PROBES]
)
edge_report(gname, itp, pts, adapt(backend, itp), TP._to_gpu_grid(itp, backend))
endendendprintln("PeriodicBC (FastInterpolations only; TestParticle's GPU grids ignore it)")
let x =0.0:1.0:4.0, y = [1.0, 3.0, 2.0, 5.0, 1.0]
for (name, itp) in (
("1D inclusive", linear_interp(x, y; bc =PeriodicBC(endpoint =:inclusive))),
("1D exclusive, period 5",
linear_interp(x, y[1:5]; bc =PeriodicBC(endpoint =:exclusive, period =5.0))),
)
edge_report(name, itp, PROBES, adapt(backend, itp), nothing)
end# TestParticle's spherical setup: fill on two axes, periodic on the last one.
g =0.0:1.0:4.0
A = [x +10y +100sinpi(z /2) for x in g, y in g, z in g]
for check in (true, false)
itp =linear_interp((g, g, g), A;
bc = (NoBC(), NoBC(), PeriodicBC(; check)),
extrap = (FillExtrap(NaN), FillExtrap(NaN), NoExtrap()))
pts = [SVector(2.25, 2.25, p) for p in PROBES]
edge_report("3D periodic last axis, check=$check", itp, pts, adapt(backend, itp),
nothing)
endendprintln("NoExtrap inside a user kernel (the PR asks for a non-throwing extrapolation)")
let itp =linear_interp(UNIFORM, collect(1.0:5.0))
edge_report("1D, points inside", itp, [0.0, 1.5, 4.0], adapt(backend, itp), nothing)
edge_report("1D, one point outside", itp, [1.5, 4.5], adapt(backend, itp), nothing)
end
bench_tracing.jl
# Test particle tracing on the GPU: TestParticle.jl v0.24.3 with its own GPU grids# (default) vs the same Boris kernel evaluating FastInterpolations.jl device# interpolants. Only the field object handed to the kernel differs.## Environment: TestParticle v0.24.3, BorisPushers, FastInterpolations#master, CUDA,# KernelAbstractions, StaticArrays, Adapt.using TestParticle, FastInterpolations, Adapt, CUDA, KernelAbstractions, StaticArrays
using Random, Printf
import TestParticle as TP
import BorisPushers
const backend =CUDABackend()
println(CUDA.name(CUDA.device()), ", driver ", CUDA.driver_version(), ", Julia ", VERSION)
println("FastInterpolations ", pkgversion(FastInterpolations), " (master), TestParticle ",
pkgversion(TestParticle), "\n")
"Field that is moved to the device with FastInterpolations' own `adapt`."struct NativeField{F} <:Function
fi::Fend
(f::NativeField)(x) = f.fi(x)
Adapt.adapt_structure(to, f::NativeField) =NativeField(adapt(to, f.fi))
BorisPushers.adapt_field_to_gpu(f::NativeField, b::CUDABackend) =adapt(b, f)
"Replace the gridded E and B of a prepared parameter tuple by `NativeField`s."functionnative(param)
q, m, E, B, F = param
wrap(f) = TP.Field{false, NativeField{typeof(f.field_function)}}(
NativeField(f.field_function)
)
return (q, m, wrap(E), wrap(B), F)
endmaxrel(a, b) =maximum(norm_rel(u, v) for (u, v) inzip(a, b))
norm_rel(u, v) =maximum(abs, u - v) /maximum(abs, v)
functionrun_case(name, param, ::Type{T}; ntraj =100_000, nstep =10_000) where {T}
dt =T(1.0e-3) # a ~1 m/s proton in ~10 nT gyrates with r ≈ 1 m, period ≈ 6.5 s
tspan = (zero(T), nstep * dt)
rng =Xoshiro(1)
# Start near (5, 0, 0) with mostly perpendicular velocities, so every particle# (gyroradius ≲ 1.5 m, drift along B ≲ 1 m) stays inside all grids below.
states =map(1:ntraj) do _
x =SVector{3, T}(5, 0, 0) .+T(2) .* (rand(rng, SVector{3, T}) .-T(0.5))
v =SVector{3, T}(1, 1, T(0.1)) .*T(2) .* (rand(rng, SVector{3, T}) .-T(0.5))
vcat(x, v)
endprob_func(prob, ctx) = TP.remake(prob; u0 =collect(states[ctx.sim_id]))
cols =map((param, native(param))) do p
prob =TraceProblem(collect(states[1]), tspan, p; prob_func)
sol_cpu =solve(prob, Boris(); dt).u
try
sol_gpu =solve(prob, Boris(), backend; dt, trajectories =1).u[1].u
err =maxrel(sol_gpu, sol_cpu)
ens() =solve(prob, Boris(), backend; dt, trajectories = ntraj,
raw_output =true, save_everystep =false)
ens()
t =minimum(_ ->@elapsed(ens()), 1:3)
@sprintf("%7.3f s traj. err vs CPU %.0e", t, err)
catch e
rpad(string(nameof(typeof(e))), 32)
endend@printf("%-28s %-7s | %-32s | %s\n", name, T, cols...)
endprintln("1e5 particles x 1e4 Boris steps, final state only. 'traj. err' is the max ",
"relative deviation of one GPU trajectory from the CPU solver.")
@printf("%-28s %-7s | %-32s | %s\n", "grid", "T", "TestParticle GPUGrid (default)",
"FastInterpolations native")
for T in (Float32, Float64)
n =64
xu =range(T(-10), T(10), length = n)
rng =Xoshiro(2)
xn =sort!([T(-10); T(-10) .+T(20) .*rand(rng, T, n -2); T(10)])
Bfun(x, y, z) =T(1.0e-8) .* (T(0.1) *sin(y), T(0.1) *cos(z), 1+T(0.05) * x)
grid_B(x, y, z) = [Bfun(xi, yi, zi)[c] for c in1:3, xi in x, yi in y, zi in z]
E0 =zeros(T, 3, n, n, n)
run_case("3D uniform 64^3", prepare(xu, xu, xu, E0, grid_B(xu, xu, xu);
species = Proton), T)
run_case("3D non-uniform 64^3", prepare(xn, xn, xn, E0, grid_B(xn, xn, xn);
species = Proton, gridtype = TP.RectilinearGrid), T)
run_case("3D uniform 64^3, ClampExtrap", prepare(xu, xu, xu, E0, grid_B(xu, xu, xu);
species = Proton, bc =ClampExtrap()), T)
# Spherical grid: uniform B₀ ẑ in spherical components, r ∈ [1, 10] m.
r =range(T(1), T(10), length = n)
θ =range(T(0), prevfloat(T(π)), length = n) # TestParticle v0.24.3 rejects Float32(π)
ϕ =range(T(0), prevfloat(T(2π)), length = n)
Bs =zeros(T, 3, n, n, n)
for (j, θj) inenumerate(θ)
Bs[1, :, j, :] .=T(1.0e-8) *cos(θj)
Bs[2, :, j, :] .=-T(1.0e-8) *sin(θj)
end
sph =prepare(r, θ, ϕ, zeros(T, size(Bs)), Bs; species = Proton,
gridtype = TP.StructuredGrid)
run_case("3D spherical 64^3", sph, T)
end
Thanks a lot for the detailed tests and analysis, and for sharing scripts.
I'm glad this first version already works for you without errors or a big performance loss :)
Performance on GPUs seems to depend more on the hardware than I expected.
I develop on a Mac, so I mostly tested on Metal (M1 Pro).
There your bench_tracing.jl actually runs faster with FI: 1.40 s vs 1.76 s on the 3D uniform Float32 grid.
On a NVIDIA's V100S on a remote cluster, FI is comparable to your GPU grids in bench_interp.jl,
but slower inside the Boris kernel (about 1.7× on the 3D uniform Float32 grid).
So the slowdown seems to come from how the interpolation combines with the Boris kernel rather than from the interpolation itself.
I'll look into the cause and see whether it can be improved.
That may take a while, though: I don't have an NVIDIA GPU locally, so every iteration goes through the cluster.
I'll also keep testing the linear path for missing APIs and bugs.
Once linear interpolation on GPUs is reasonably stable, I'll make a release with it on its own.
Would that be enough for you for now?
Cubic and the other families will take longer
(they need more design work on the device side, and my bandwidth will be more limited for a couple of coming weeks)
Either way, I'll keep you updated as the linear part gets polished!
Hi, just FYI, I think I found one of the main causes: NativeField in bench_tracing.jl is not @inline. On CUDA the FI evaluation then stays a device function call in the Boris loop. Metal seems to inline it anyway, which is why I saw no slowdown there. With @inline (f::NativeField)(x) = f.fi(x), FI matches your hand-written grids on our V100S.
TestParticle's own Field and FieldInterpolator are already @inline, so the real integration should be fine regarding this inlining.
A stable performance on metal and cuda with linear interpolation fits our need for the GPU version of TestParticle for now. Once you release the new version I will switch to depend on that instead of housekeeping my own version. This is a much better separation of concerns 😃
Activity
mgyoo86 commentedon Oct 12, 2026
Hi @henry2004y,
Thanks for bringing this up and for sharing your implementation!
GPU support has been on my roadmap, but it hasn’t been a high priority so far, mainly because I haven’t had a concrete use case or received specific requests for it. Now that you’ve brought this up, I think it’s worth taking a closer look.
I’ve also been considering using
Adapt.jlor a similar approach to bring parts of the package, particularly interpolation evaluation, to the GPU, though I haven’t tried anything concrete yet. Ultimately, dedicated GPU kernels might be ideal for performance, but that’s probably a longer-term goal.There are quite a few things we’d need to explore, including practical performance considerations (e.g., CPU–GPU memory transfers) and how much of the interpolation workflow should actually run on the GPU. For more complex interpolants like cubic splines, I suspect building on the CPU and transferring the interpolant for GPU evaluation might be a reasonable starting point.
If you have any specific use cases in mind (e.g., interpolation types, whether GPU evaluation alone would be sufficient), or any insights from your experience with GPU implementations, particularly regarding performance and problem sizes where GPU acceleration becomes worthwhile, that would be really helpful!
I probably won’t have the bandwidth to work on this over the next few weeks, but I’d like to revisit it when I get a chance.
henry2004y commentedon Oct 16, 2026
Sorry about the late response! I was in a Hackathon this week. For me the use case is pretty simple right now: I want linear and cubic interpolation support for the EM field on GPU and evaluation alone would be sufficient. I am currently using KernelAbstractions.jl and provide a matrix as my test particle initial conditions. All the particles are traced in the same EM field on GPU. I've recently made some benchmarks about TestParticle.jl, and there's a subsection about GPU trilinear interpolation. Originally I thought Float32 and Float64 would make a large difference, but that only applies to consumer GPUs, not cluster GPUs.
I also have a demo for showing my current GPU interpolation implementation.
mgyoo86 commentedon Oct 22, 2026
Hi @henry2004y,
A first round of GPU support is implemented in PR #224 (now on master):
linear interpolation in 1D and ND, on any GPUArrays backend (tested on CUDA and Metal).
Interpolants can be built straight from device arrays or moved from the CPU with
Adapt.adapt, and they also work as arguments of your ownKernelAbstractionskernels, which is probably your use-case.More detailed information is in the GPU Arrays guide.
It is still experimental and not fully optimized, but it should already be usable for basic interpolations.
Please give it a try when you have a moment; feedback is very welcome.
Cubic and the other methods need more substantial changes, which will come later.
Thanks!
henry2004y commentedon Oct 22, 2026
Will do so! I'll let you know how it goes.
henry2004y commentedon Oct 23, 2026
I tried together with Claude the new GPU support in TestParticle.jl, where a KernelAbstractions Boris kernel evaluates gridded E/B fields per particle. FastInterpolations matches the CPU exactly, and its speed is close to our own kernels (cannot really tell which is faster). So we are replacing our hand-written GPU interpolators (~600 lines) with
adapt(backend, itp), and will switch once a release includes #224.Setup: RTX 5070 (consumer card, FP64 at 1/64 rate), Julia 1.13.2 on Windows, CUDA.jl 6.4.2, KA 0.9.45, FastInterpolations
master(with #226), TestParticle 0.24.3. Both scripts are attached below.1. Interpolation only (
bench_interp.jl)4M random points, 5% of them outside the grid. Each time is the best of 7 × 50 kernel launches (
out[i] = itp(pts[i])).SVector{3}SVector{3}On Cartesian grids, FastInterpolations is bitwise identical to the CPU interpolant. On the spherical grid, both implementations differ from the CPU by the same amount (2e-4 in Float32), which comes from the Cartesian↔spherical conversion done in TestParticle's wrapper. The script also checks edge points for each boundary option against the CPU: on the grid edge, one ulp outside, half a cell outside, far outside, NaN, ±Inf. All of them match, for
FillExtrap,ClampExtrap,WrapExtrap, 1DPeriodicBC(inclusive and exclusive), andPeriodicBCon the last axis of a 3D grid, withcheck = trueandfalse.2. Particle tracing (
bench_tracing.jl)TestParticle's GPU Boris solver with 1e5 particles × 1e4 steps; only the field object passed to the kernel differs.
Trajectories from FastInterpolations agree with our CPU solver to 1e-8 in Float32 and 1e-16 in Float64.
Observations for FastInterpolations
bench_tracing.jlreproduces it (TO BE CONFIRMED).adaptwithout error. This happens forcubic_interp,constant_interp, and the ND interpolant from order-3cardinal_interp. The result still refers to host memory, and the problem only appears at kernel compile time as a longKernelError/InvalidIRErrorpointing into the user's kernel. FastInterpolations is the natural place to catch this, since it knows which families have device support. Two options: anArgumentErrorwhen adapting an unsupported family to a GPU array type (leavingadapt(Array, itp)unchanged), or a public query such assupports_device(itp). For now TestParticle checks forLinearInterpolant/LinearInterpolantNDitself, which will go stale once cubic support lands.We are looking forward to the planned cubic support on GPU~
Issues on our side, now fixed by switching
These were bugs in TestParticle's own GPU grids, not in FastInterpolations. The scripts show them, and they go away with the switch.
ClampExtrapandWrapExtrapgrids failed to compile on the GPU.FillExtrapgrids returned values up to 4 ulp outside the domain instead of NaN, and 1D Float32 lookups lost accuracy (relative error 2e-3).Float32(π)were rejected by our range check (fixed separately).Environment
bench_interp.jl
bench_tracing.jl
mgyoo86 commentedon Oct 23, 2026
Thanks a lot for the detailed tests and analysis, and for sharing scripts.
I'm glad this first version already works for you without errors or a big performance loss :)
Performance on GPUs seems to depend more on the hardware than I expected.
I develop on a Mac, so I mostly tested on Metal (M1 Pro).
There your
bench_tracing.jlactually runs faster with FI: 1.40 s vs 1.76 s on the 3D uniform Float32 grid.On a NVIDIA's V100S on a remote cluster, FI is comparable to your GPU grids in
bench_interp.jl,but slower inside the Boris kernel (about 1.7× on the 3D uniform Float32 grid).
So the slowdown seems to come from how the interpolation combines with the Boris kernel rather than from the interpolation itself.
I'll look into the cause and see whether it can be improved.
That may take a while, though: I don't have an NVIDIA GPU locally, so every iteration goes through the cluster.
I'll also keep testing the linear path for missing APIs and bugs.
Once linear interpolation on GPUs is reasonably stable, I'll make a release with it on its own.
Would that be enough for you for now?
Cubic and the other families will take longer
(they need more design work on the device side, and my bandwidth will be more limited for a couple of coming weeks)
Either way, I'll keep you updated as the linear part gets polished!
henry2004y commentedon Oct 24, 2026
Take your time! I know tuning GPU performance is a rabbit hole. Hopefully with AI this becomes a much smoother experience.
mgyoo86 commentedon Oct 24, 2026
Hi, just FYI, I think I found one of the main causes:
NativeFieldinbench_tracing.jlis not@inline. On CUDA the FI evaluation then stays a device function call in the Boris loop. Metal seems to inline it anyway, which is why I saw no slowdown there. With@inline (f::NativeField)(x) = f.fi(x), FI matches your hand-written grids on our V100S.TestParticle's own Field and FieldInterpolator are already
@inline, so the real integration should be fine regarding this inlining.henry2004y commentedon Oct 24, 2026
A stable performance on metal and cuda with linear interpolation fits our need for the GPU version of TestParticle for now. Once you release the new version I will switch to depend on that instead of housekeeping my own version. This is a much better separation of concerns 😃