Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/algorithms.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ This introduces the following limitations on its usage:
approach.
- To use multiple GPUs over clusters, one must manually set up one process per GPU. See
the multi-GPU tutorial for more details.
- For a `DynamicalODEProblem` or `SecondOrderODEProblem`, every trajectory needs the
same lengths of `v` and `u`, and the mass matrix must be the identity. Other batches
throw an `ArgumentError`.

!!! warn

Expand Down
5 changes: 5 additions & 0 deletions src/ensemblegpuarray/kernels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ end
@views @inbounds f(du[:, i], u[:, i], ensemble_param(p, i), t)
end

@muladd @kernel function dynamical_kernel(f, du, u, @Const(p), @Const(t))
i = @index(Global, Linear)
@views @inbounds f(du[:, i], u[:, i], ensemble_param(p, i), t)
end

@muladd @kernel function gpu_kernel_oop(f, du, @Const(u), @Const(p), @Const(t))
i = @index(Global, Linear)
@views @inbounds x = f(u[:, i], ensemble_param(p, i), t)
Expand Down
1 change: 1 addition & 0 deletions src/ensemblegpuarray/lowerlevel_solve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ function vectorized_map_solve(
kwargs...
)

check_array_batch(probs)
# Keep an n×1 matrix for singleton state batches (lower-level API contract).
u0 = hcat([Array(probs[i].u0) for i in 1:length(I)]...)
p = pack_ordinary_parameters([probs[i] for i in 1:length(I)])
Expand Down
68 changes: 67 additions & 1 deletion src/ensemblegpuarray/problem_generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,80 @@ function pack_ordinary_parameters(probs)
end
end

# A `DynamicalODEFunction` (also used by `SecondOrderODEProblem`) has no single `f`: `f1`
# gives the derivative of `v` and `f2` the derivative of `u`. Each column of the batched
# state holds one trajectory's `ArrayPartition(v, u)` flattened to `[v; u]`, so split it
# and call both halves, writing each derivative into its slice of `du`. Out-of-place
# halves are copied element by element: concatenating them (e.g. with `vcat`) is generic
# array code that doesn't compile for GPUs when a half returns a view of the state.
struct DynamicalColumnRHS{iip, F1, F2}
f1::F1
f2::F2
n::Int # length of `v`
end
DynamicalColumnRHS{iip}(f1::F1, f2::F2, n) where {iip, F1, F2} =
DynamicalColumnRHS{iip, F1, F2}(f1, f2, n)

@inline function (f::DynamicalColumnRHS{true})(du, u, p, t)
n = f.n
@views begin
v, x = u[1:n], u[(n + 1):end]
f.f1(du[1:n], v, x, p, t)
f.f2(du[(n + 1):end], v, x, p, t)
end
return nothing
end

@inline function (f::DynamicalColumnRHS{false})(du, u, p, t)
n = f.n
@views v, x = u[1:n], u[(n + 1):end]
dv = f.f1(v, x, p, t)
@inbounds for j in 1:n
du[j] = dv[j]
end
dx = f.f2(v, x, p, t)
@inbounds for j in 1:(length(du) - n)
du[n + j] = dx[j]
end
return nothing
end

column_rhs(f, u0) = f.f
function column_rhs(f::SciMLBase.DynamicalODEFunction, u0)
return DynamicalColumnRHS{SciMLBase.isinplace(f)}(f.f1, f.f2, length(u0.x[1]))
end

# Every column is split where the first trajectory's state is, and the batched
# `ODEFunction` has no mass matrix, so reject batches that would be solved wrongly.
function check_array_batch(probs)
first(probs).f isa SciMLBase.DynamicalODEFunction || return nothing
n = length(first(probs).u0.x[1])
for prob in probs
if length(prob.u0.x[1]) != n
throw(ArgumentError("array ensembles need the same length of `v` in every trajectory of a dynamical problem, got $n and $(length(prob.u0.x[1]))"))
end
if prob.f.mass_matrix != I
throw(ArgumentError("array ensembles don't support mass matrices for dynamical problems, only the identity"))
end
end
return nothing
end

# `DynamicalColumnRHS` always writes into `du`, so it runs in an in-place kernel. That
# kernel leaves `u` writable: on the CPU, `@Const` wraps it in `Base.Experimental.Const`,
# and broadcasting from a view of that (like the `du .= v` of a `SecondOrderODEProblem`)
# throws a `MethodError` in Base's aliasing check.
column_kernel(f, prob) = DiffEqBase.isinplace(prob) ? gpu_kernel : gpu_kernel_oop
column_kernel(::DynamicalColumnRHS, prob) = dynamical_kernel

function generate_problem(
prob::SciMLBase.AbstractODEProblem,
u0,
p,
jac_prototype,
colorvec
)
_f = let f = prob.f.f, kernel = DiffEqBase.isinplace(prob) ? gpu_kernel : gpu_kernel_oop
_f = let f = column_rhs(prob.f, prob.u0), kernel = column_kernel(f, prob)
function (du, u, p, t)
version = get_backend(u)
wgs = workgroupsize(version, size(u, 2))
Expand Down
1 change: 1 addition & 0 deletions src/solve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ function batch_solve(
ensembleprob.prob_func(ensembleprob.prob, ctx)
end
end
check_array_batch(probs)
u0 = _hcat_batch([Array(probs[i].u0) for i in 1:length(I)])

if !all(
Expand Down
104 changes: 104 additions & 0 deletions test/ensemblegpuarray_dynamical.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using DiffEqGPU, StaticArrays
using OrdinaryDiffEq: Tsit5
using OrdinaryDiffEqRosenbrock: Rosenbrock23
using SciMLBase: DynamicalODEFunction, DynamicalODEProblem, SecondOrderODEProblem,
EnsembleProblem, EnsembleSerial, ReturnCode, remake, solve
using LinearAlgebra: Diagonal
using Test

include("utils.jl")
ensemble = GROUP == "CPU" ? EnsembleCPUArray() : EnsembleGPUArray(backend, 0.0)

# harmonic oscillators: dv/dt = -k x, dx/dt = v, with a different k per trajectory
dv(v, x, p, t) = -p[1] .* x
dx(v, x, p, t) = v # returns the state itself: a view of it in the GPU kernels
dv_static(v, x, p, t) = SVector(-p[1] * x[1], -p[1] * x[2])
function dv!(a, v, x, p, t)
for j in eachindex(a)
a[j] = -p[1] * x[j]
end
return nothing
end
function dx!(a, v, x, p, t)
for j in eachindex(a)
a[j] = v[j]
end
return nothing
end

v0 = Float32[0.5, 0]
x0 = Float32[1, -2]
tspan = (0.0f0, 2.0f0)
ks = Float32[1, 2, 3, 4]
prob_func = (prob, ctx) -> remake(prob, p = Float32[ks[ctx.sim_id]])

function exact(k, t)
w = sqrt(k)
return vcat(-w .* x0 .* sin(w * t) .+ v0 .* cos(w * t), x0 .* cos(w * t) .+ v0 ./ w .* sin(w * t))
end

v0_static, x0_static = SVector{2}(v0), SVector{2}(x0)

# `dv` allocates, so these out-of-place cases only run on the CPU
cpu_probs = [
"DynamicalODEProblem oop" => DynamicalODEProblem{false}(dv, dx, v0, x0, tspan, Float32[1]),
"SecondOrderODEProblem" => SecondOrderODEProblem{false}(dv, v0, x0, tspan, Float32[1]),
]
# allocation-free right-hand sides that also compile for GPUs
probs = [
"DynamicalODEProblem iip" => DynamicalODEProblem{true}(dv!, dx!, v0, x0, tspan, Float32[1]),
# the built-in `du .= v` for `u`
"SecondOrderODEProblem iip" => SecondOrderODEProblem{true}(dv!, v0, x0, tspan, Float32[1]),
"DynamicalODEProblem oop, static" =>
DynamicalODEProblem{false}(dv_static, dx, v0_static, x0_static, tspan, Float32[1]),
"SecondOrderODEProblem oop, static" =>
SecondOrderODEProblem{false}(dv_static, v0_static, x0_static, tspan, Float32[1]),
]
GROUP == "CPU" && append!(probs, cpu_probs)

@testset "$name" for (name, prob) in probs
ens = EnsembleProblem(prob; prob_func, safetycopy = false)
kw = (; trajectories = length(ks), abstol = 1.0f-7, reltol = 1.0f-7, save_everystep = false)
sol = solve(ens, Tsit5(), ensemble; kw...)
ref = solve(ens, Tsit5(), EnsembleSerial(); kw...)
for (i, k) in enumerate(ks)
@test collect(sol.u[i].u[end]) ≈ exact(k, tspan[2]) atol = 1.0f-3
@test collect(sol.u[i].u[end]) ≈ collect(ref.u[i].u[end]) atol = 1.0f-3
end
end

GROUP == "CPU" && @testset "SecondOrderODEProblem iip, Float64" begin
prob = SecondOrderODEProblem{true}(dv!, [0.0], [1.0], (0.0, 1.0), [1.0])
sol = solve(
EnsembleProblem(prob; safetycopy = false), Tsit5(), ensemble;
trajectories = 2, abstol = 1.0e-8, reltol = 1.0e-8, save_everystep = false
)
for s in sol.u
@test s.retcode == ReturnCode.Success
@test collect(s.u[end]) ≈ [-sin(1.0), cos(1.0)] atol = 1.0e-7 # [v; x]
end
end

# each column is split where the first trajectory's state is, and the batched problem
# has no mass matrix, so these batches must be rejected instead of solved wrongly
@testset "unsupported batches" begin
kw = (; abstol = 1.0f-7, reltol = 1.0f-7, save_everystep = false)
p = Float32[1]
widths = [
DynamicalODEProblem{true}(dx!, dx!, Float32[0], Float32[0, 0], tspan, p),
DynamicalODEProblem{true}(dx!, dx!, Float32[0, 0], Float32[0], tspan, p),
]
mf = DynamicalODEFunction{true}(dv!, dx!; mass_matrix = Diagonal(Float32[2, 1]))
mass = fill(DynamicalODEProblem(mf, Float32[0], Float32[0], tspan, p), 2) # 1 runs serially
@testset "$name" for (name, alg, probs) in [
("different widths", Tsit5(), widths), ("mass matrix", Rosenbrock23(), mass),
]
ens = EnsembleProblem(
probs[1]; prob_func = (prob, ctx) -> probs[ctx.sim_id], safetycopy = false
)
@test_throws ArgumentError solve(ens, alg, ensemble; trajectories = length(probs), kw...)
@test_throws ArgumentError DiffEqGPU.vectorized_map_solve(
probs, alg, ensemble, 1:length(probs), true; kw...
)
end
end
9 changes: 9 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ if GROUP in SUPPORTS_DOUBLE_PRECISION
=#
end

if GROUP in ("CUDA", "AMDGPU", "Metal")
@time @safetestset "EnsembleGPUArray DynamicalODEFunction" begin
include("ensemblegpuarray_dynamical.jl")
end
end

if GROUP == "CPU"
@time @safetestset "Public generic interfaces" begin
include("public_interface.jl")
Expand All @@ -142,6 +148,9 @@ if GROUP == "CPU"
@time @safetestset "EnsembleGPUArray scalar batch parameters" begin
include("ensemblegpuarray_scalar_batch.jl")
end
@time @safetestset "EnsembleGPUArray DynamicalODEFunction" begin
include("ensemblegpuarray_dynamical.jl")
end
@time @safetestset "Kernel ensemble host storage" begin
include("gpu_kernel_de/host_fastpath.jl")
end
Expand Down
Loading