Skip to content
Draft
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 Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ UnPack = "3a884ed6-31ef-47d7-9d2a-63182c4928ed"
ZygoteRules = "700de1a5-db45-46bc-99cf-38207098b444"

[weakdeps]
OrdinaryDiffEqCore = "bbf590c4-e513-4bbe-9b18-05decba2e5d8"
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
Expand All @@ -44,6 +45,7 @@ OpenCL = "08131aa3-fb12-5dee-8b74-c09406e224a2"
oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b"

[extensions]
OrdinaryDiffEqCoreExt = "OrdinaryDiffEqCore"
EnzymeExt = "Enzyme"
AMDGPUExt = ["AMDGPU"]
CUDAExt = ["CUDA"]
Expand All @@ -54,6 +56,7 @@ OpenCLExt = ["OpenCL"]
oneAPIExt = ["oneAPI"]

[compat]
OrdinaryDiffEqCore = "4"
AMDGPU = "2"
Adapt = "4"
CUDA = "6"
Expand Down
7 changes: 4 additions & 3 deletions docs/src/tutorials/gpu_ensemble_basic.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ information on the limitations of `EnsembleGPUKernel()`, see [its docstring](@re
DiffEqGPU also supports more advanced features than shown above. Other tutorials dive into
[handling events or callbacks](@ref events) and [multi-GPU parallelism](@ref multigpu).
But the simplest thing to show is that the generality of solvers allows for other types of
equations. For example, one can handle stiff ODEs with `EnsembleGPUArray` simply by using a
stiff ODE solver. Note that, as explained in the docstring, analytical derivatives
(Jacobian and time gradient) must be supplied. For the Lorenz equation, this looks like:
equations. Use `Rodas5P()` with `independent_adaptivity = true` to give each trajectory
its own adaptive time step and let ForwardDiff compute derivatives from a GPU-compatible
right-hand side. With a shared time step, supply the Jacobian and time gradient as in this
Lorenz example.

```@example lorenz
function lorenz_jac(J, u, p, t)
Expand Down
11 changes: 11 additions & 0 deletions ext/OrdinaryDiffEqCoreExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module OrdinaryDiffEqCoreExt

import DiffEqGPU
import OrdinaryDiffEqCore

if isdefined(OrdinaryDiffEqCore, :batch_stats)
import OrdinaryDiffEqCore: batch_stats
DiffEqGPU.vector_time_batch_stats() = batch_stats
end

end
2 changes: 2 additions & 0 deletions src/DiffEqGPU.jl
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ include("ensemblegpuarray/callbacks.jl")
include("ensemblegpuarray/kernels.jl")
include("ensemblegpuarray/problem_generation.jl")
include("ensemblegpuarray/lowerlevel_solve.jl")
include("ensemblegpuarray/vector_time_device.jl")
include("ensemblegpuarray/vector_time.jl")

include("ensemblegpukernel/callbacks.jl")
include("ensemblegpukernel/lowerlevel_solve.jl")
Expand Down
31 changes: 25 additions & 6 deletions src/algorithms.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@ right-hand side cannot be compiled into one fused `EnsembleGPUKernel` solve.
two-argument constructor stores this value as a `Float64`; the one-argument constructor
defaults to `0.2`.

# Independent adaptive ODE solves

Pass `independent_adaptivity = true` to `solve` with `Tsit5()` or `Rodas5P()`
from OrdinaryDiffEq. Each batch uses a single integrator with one physical clock,
step size, error estimate, and accept/reject decision per state column. All columns
use the selected backend, including the dense factorizations for `Rodas5P()`.

```julia
sol = solve(
ensemble_prob, Rodas5P(), EnsembleGPUArray(backend);
trajectories = 1000, batch_size = 128, independent_adaptivity = true, saveat = 0.1
)
```

Use plain ODEs with floating-point vector states of a common length, common
GPU-compatible functions, and read-only parameter data. `Rodas5P()` requires an
identity mass matrix. Its default ForwardDiff computes the Jacobian and time
gradient when `jac` or `tgrad` are omitted. Each trajectory may have its own time
span. The `dt` option accepts a scalar or one initial step size per trajectory.
Specify `callback = nothing` and `dense = false`. Requested `saveat` times are
step endpoints, and saved states are returned on the host.

# Returns

An `EnsembleGPUArray` algorithm selector.
Expand Down Expand Up @@ -73,12 +95,9 @@ This introduces the following limitations on its usage:
+ Implicit Runge-Kutta methods
+ Rosenbrock methods
+ DiscreteCallbacks and ContinuousCallbacks
- Stiff ODEs require the analytical solution of every derivative function it requires.
For example, Rosenbrock methods require the Jacobian and the gradient with respect to
time, and so these two functions are required to be given. Note that they can be
generated by the
[ModelingToolkit.jl](https://docs.sciml.ai/ModelingToolkit/stable/)
approach.
- For stiff solves with a shared step size, supply analytic derivatives such as the
Jacobian and time gradient for Rosenbrock methods. These derivatives can be generated
by [ModelingToolkit.jl](https://docs.sciml.ai/ModelingToolkit/stable/).
- To use multiple GPUs over clusters, one must manually set up one process per GPU. See
the multi-GPU tutorial for more details.

Expand Down
175 changes: 175 additions & 0 deletions src/ensemblegpuarray/vector_time.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
function vector_time_batch_stats end

function vector_time_batch_options(indices; unstable_check = nothing, dt = nothing, options...)
steps = dt isa AbstractVector ? Array(dt)[indices] : dt
return (; dt = steps, options)
end

vector_time_parameter_layout(p) = typeof(p)
vector_time_parameter_layout(p::AbstractVector{T}) where {T <: Number} = (T, length(p))
function vector_time_parameter_layout(p::AbstractArray)
throw(ArgumentError("Use numeric vectors or GPU-compatible scalar or structured parameters."))
end

function check_vector_time_problems(probs)
prob = first(probs)
prob isa ODEProblem && prob.f isa ODEFunction && prob.u0 isa AbstractVector ||
throw(ArgumentError("Independent adaptivity requires ODEProblem trajectories with vector states."))
f = prob.f
layout = vector_time_parameter_layout(prob.p)
for candidate in probs
candidate isa ODEProblem && candidate.f isa ODEFunction &&
candidate.u0 isa AbstractVector && length(candidate.u0) == length(prob.u0) ||
throw(ArgumentError("Independent adaptivity requires a common state vector length."))
cf = candidate.f
cf.f === f.f && cf.jac === f.jac && cf.tgrad === f.tgrad &&
SciMLBase.isinplace(candidate) == SciMLBase.isinplace(prob) ||
throw(ArgumentError("Independent adaptivity requires common RHS and derivative functions."))
vector_time_parameter_layout(candidate.p) === layout ||
throw(ArgumentError("Independent adaptivity requires a common parameter layout."))
cf.mass_matrix === I && !SciMLBase.has_initialization_data(cf) &&
all(isnothing, (cf.jvp, cf.vjp, cf.paramjac, cf.Wfact, cf.Wfact_t, cf.W_prototype)) &&
(cf.jac_prototype === nothing || cf.jac_prototype isa StridedMatrix) &&
(cf.sparsity === nothing || cf.sparsity isa StridedMatrix) &&
(!hasproperty(cf, :nlstep_data) || cf.nlstep_data === nothing) ||
throw(ArgumentError("Use plain ODEs with an identity mass matrix and dense Jacobians for independent adaptivity."))
all(k -> k in (:dt, :saveat, :callback, :dense), keys(candidate.kwargs)) ||
throw(ArgumentError("Pass solve options to solve and set trajectory data with prob_func."))
get(candidate.kwargs, :callback, nothing) === nothing && !get(candidate.kwargs, :dense, false) ||
throw(ArgumentError("Independent adaptivity requires callback = nothing and dense = false."))
end
return nothing
end

function vector_time_save_grid(t0::T, tf::T, saveat) where {T}
saveat === nothing && return T[]
if saveat isa Real
spacing = T(saveat)
isfinite(spacing) && spacing > 0 || throw(ArgumentError("Scalar saveat must be positive and finite."))
t0 == tf && return T[t0]
increment = copysign(spacing, tf - t0)
(t0 + increment != t0 && tf - increment != tf) ||
throw(ArgumentError("Scalar saveat is smaller than the representable time spacing."))
return unique!(collect(t0:increment:tf))
end
all(isfinite, saveat) || throw(ArgumentError("Save times must be finite."))
grid = T[t for t in saveat if min(t0, tf) <= t <= max(t0, tf)]
return unique!(sort!(grid; rev = tf < t0))
end

function solve_vector_time_batch(
probs, alg, backend; dt, abstol = 1.0e-6, reltol = 1.0e-3, dtmin = 0,
dtmax = Inf, maxiters = 100_000, saveat = nothing, save_everystep = nothing,
save_start = nothing, save_end = nothing, dense = false, callback = nothing,
kwargs...
)
isempty(kwargs) || throw(ArgumentError("Unsupported independent adaptivity keywords: $(keys(kwargs))."))
callback === nothing && !dense ||
throw(ArgumentError("Independent adaptivity requires callback = nothing and dense = false."))
applicable(vector_time_batch_stats) ||
throw(ArgumentError("Load a version of OrdinaryDiffEq with batched stepping support to use independent adaptivity."))
batch_stats = vector_time_batch_stats()
check_vector_time_problems(probs)
batch_alg = if hasproperty(alg, :linsolve)
isnothing(alg.linsolve) ||
throw(ArgumentError("Use the default linsolve option on the OrdinaryDiffEq algorithm for independent adaptivity."))
SciMLBase.remake(alg; linsolve = VectorTimeLinearSolve(backend))
else
alg
end
u0 = stack(Array(prob.u0) for prob in probs)
T = mapreduce(prob -> typeof(float(first(prob.tspan))), promote_type, probs)
t0 = T[first(prob.tspan) for prob in probs]
tf = T[last(prob.tspan) for prob in probs]
eltype(u0) <: AbstractFloat && T <: AbstractFloat ||
throw(ArgumentError("Independent adaptivity requires floating-point states and times."))
if isnothing(dt) && any(prob -> get(prob.kwargs, :dt, nothing) !== nothing, probs)
dt = T[
something(get(prob.kwargs, :dt, nothing), max(abs(tf[i] - t0[i]) / T(100), eps(t0[i])))
for (i, prob) in enumerate(probs)
]
end

local_saveat = [saveat === nothing ? get(prob.kwargs, :saveat, nothing) : saveat for prob in probs]
grids = [vector_time_save_grid(t0[i], tf[i], local_saveat[i]) for i in eachindex(probs)]
no_grid = [at === nothing || (!(at isa Real) && isempty(at)) for at in local_saveat]
allsteps = [something(save_everystep, no_grid[i]) for i in eachindex(probs)]
start = [something(save_start, no_grid[i] || allsteps[i] || local_saveat[i] isa Real || t0[i] in grids[i]) for i in eachindex(probs)]
finish = [something(save_end, no_grid[i] || allsteps[i] || local_saveat[i] isa Real || tf[i] in grids[i]) for i in eachindex(probs)]
times = [start[i] ? T[t0[i]] : T[] for i in eachindex(probs)]
states = [start[i] ? [u0[:, i]] : Vector{eltype(u0)}[] for i in eachindex(probs)]
cursor = [!isempty(grids[i]) && first(grids[i]) == t0[i] ? 2 : 1 for i in eachindex(probs)]
next = [get(grids[i], cursor[i], tf[i]) for i in eachindex(probs)]
observe_steps = any(allsteps) || any(i -> next[i] != tf[i], eachindex(probs))

accepted_cpu = Vector{Bool}(undef, length(probs))
save = similar(accepted_cpu)
times_cpu = similar(t0)
states_cpu = similar(u0)
function observe(integrator, accepted, targets)
copyto!(accepted_cpu, accepted)
any(accepted_cpu) || return nothing
copyto!(times_cpu, integrator.t.values)
changed = false
for i in eachindex(accepted_cpu)
now = times_cpu[i]
at_save = accepted_cpu[i] && cursor[i] <= length(grids[i]) && now == next[i]
save[i] = accepted_cpu[i] && (now == tf[i] ? finish[i] : allsteps[i] || at_save)
if at_save
cursor[i] += 1
next[i] = get(grids[i], cursor[i], tf[i])
changed = true
end
end
changed && copyto!(targets, next)
if any(save)
copyto!(states_cpu, integrator.uprev)
for i in eachindex(save)
save[i] || continue
push!(times[i], times_cpu[i])
push!(states[i], states_cpu[:, i])
end
end
return nothing
end

f = first(probs).f
iip = Val(SciMLBase.isinplace(first(probs)))
active = adapt(backend, fill(false, length(probs)))
failed = similar(active)
masks = (active, failed)
rhs = VectorTimeRHS(backend, f.f, iip, masks)
jac = SciMLBase.has_jac(f) ? VectorTimeJacobian(backend, f.jac, iip, masks) : nothing
tgrad = SciMLBase.has_tgrad(f) ? VectorTimeGradient(backend, f.tgrad, iip, masks) : nothing
wrapped = ODEFunction(rhs; jac, tgrad)

u_device = adapt(backend, u0)
p_device = adapt(backend, pack_ordinary_parameters(probs))
batch_prob = ODEProblem(wrapped, u_device, (adapt(backend, t0), adapt(backend, tf)), p_device)
initial_steps = dt isa AbstractVector ? adapt(backend, dt) : dt
integrator = SciMLBase.init(
batch_prob, batch_alg;
dt = initial_steps, abstol = eltype(u0)(abstol), reltol = eltype(u0)(reltol),
dtmin, dtmax, maxiters, targets = adapt(backend, next), active, failed,
observer = observe_steps ? observe : nothing,
save_start = false, save_end = false, save_everystep = false
)
SciMLBase.solve!(integrator)
result = batch_stats(integrator)
naccept, nreject, retcodes = map(Array, (result.naccept, result.nreject, result.retcode))
last_times, last_states = Array(integrator.t.values), Array(integrator.u)
return map(eachindex(probs)) do i
save_last = finish[i] && (
retcodes[i] == ReturnCode.Success || save_end === true ||
no_grid[i] || local_saveat[i] isa Real || isempty(times[i])
)
if save_last && (isempty(times[i]) || last(times[i]) != last_times[i])
push!(times[i], last_times[i])
push!(states[i], last_states[:, i])
end
stats = SciMLBase.DEStats(-1)
stats.naccept = naccept[i]
stats.nreject = nreject[i]
return SciMLBase.build_solution(probs[i], alg, times[i], states[i]; stats, retcode = retcodes[i])
end
end
Loading
Loading