diff --git a/Project.toml b/Project.toml index 824634be..8fe2acd4 100644 --- a/Project.toml +++ b/Project.toml @@ -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" @@ -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"] @@ -54,6 +56,7 @@ OpenCLExt = ["OpenCL"] oneAPIExt = ["oneAPI"] [compat] +OrdinaryDiffEqCore = "4" AMDGPU = "2" Adapt = "4" CUDA = "6" diff --git a/docs/src/tutorials/gpu_ensemble_basic.md b/docs/src/tutorials/gpu_ensemble_basic.md index 9a9a7414..f1221a4e 100644 --- a/docs/src/tutorials/gpu_ensemble_basic.md +++ b/docs/src/tutorials/gpu_ensemble_basic.md @@ -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) diff --git a/ext/OrdinaryDiffEqCoreExt.jl b/ext/OrdinaryDiffEqCoreExt.jl new file mode 100644 index 00000000..ee10ad68 --- /dev/null +++ b/ext/OrdinaryDiffEqCoreExt.jl @@ -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 diff --git a/src/DiffEqGPU.jl b/src/DiffEqGPU.jl index 0ab2f9a2..fd456615 100644 --- a/src/DiffEqGPU.jl +++ b/src/DiffEqGPU.jl @@ -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") diff --git a/src/algorithms.jl b/src/algorithms.jl index 11ca0024..41e3d93f 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -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. @@ -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. diff --git a/src/ensemblegpuarray/vector_time.jl b/src/ensemblegpuarray/vector_time.jl new file mode 100644 index 00000000..8af67a03 --- /dev/null +++ b/src/ensemblegpuarray/vector_time.jl @@ -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 diff --git a/src/ensemblegpuarray/vector_time_device.jl b/src/ensemblegpuarray/vector_time_device.jl new file mode 100644 index 00000000..dd194913 --- /dev/null +++ b/src/ensemblegpuarray/vector_time_device.jl @@ -0,0 +1,182 @@ +@inline vector_time_column(A::AbstractMatrix, i) = @inbounds view(A, :, i) +@inline vector_time_column(A::AbstractArray{T, 3}, i) where {T} = @inbounds view(A, :, :, i) + +@inline vector_time_active(::Nothing, i) = true +@inline vector_time_active(active, i) = @inbounds active[i] +@inline vector_time_active(masks::Tuple, i) = @inbounds masks[1][i] && !masks[2][i] + +struct VectorTimeEvaluation{Kind, B, F, IIP, M} + backend::B + f::F + iip::Val{IIP} + active::M +end + +function VectorTimeEvaluation{Kind}(backend, f, iip::Val{IIP}, active = nothing) where {Kind, IIP} + return VectorTimeEvaluation{Kind, typeof(backend), typeof(f), IIP, typeof(active)}(backend, f, iip, active) +end + +function VectorTimeEvaluation{Kind}(backend, f, iip::Bool, active = nothing) where {Kind} + return VectorTimeEvaluation{Kind}(backend, f, Val(iip), active) +end + +const VectorTimeRHS = VectorTimeEvaluation{:rhs} +const VectorTimeJacobian = VectorTimeEvaluation{:jac} +const VectorTimeGradient = VectorTimeEvaluation{:tgrad} + +function (evaluation::VectorTimeEvaluation{Kind})(dest, states, params, t) where {Kind} + n = size(states, 2) + iszero(n) && return nothing + backend = evaluation.backend + vector_time_evaluation_kernel!(backend)( + dest, states, params, adapt(backend, t.values), adapt(backend, evaluation.active), + evaluation.f, evaluation.iip, Val(Kind); ndrange = n, workgroupsize = workgroupsize(backend, n) + ) + return nothing +end + +@muladd @kernel function vector_time_evaluation_kernel!( + dest, states, params, @Const(times), @Const(active), + f, ::Val{IIP}, ::Val{Kind} + ) where {IIP, Kind} + i = @index(Global, Linear) + out = vector_time_column(dest, i) + if vector_time_active(active, i) + u = vector_time_column(states, i) + p = ensemble_param(params, i) + @inbounds t = times[i] + if IIP + if Kind === :jac + for j in 1:length(out) + @inbounds out[j] = zero(eltype(out)) + end + end + f(out, u, p, t) + else + result = f(u, p, t) + for j in 1:length(out) + @inbounds out[j] = result[j] + end + end + else + for j in 1:length(out) + @inbounds out[j] = zero(eltype(out)) + end + end +end + +struct VectorTimeLinearSolve{B} + backend::B +end + +function (::VectorTimeLinearSolve)(::Val{:init}, W) + return similar(W, Int, (size(W, 1), size(W, 3))) +end + +function (linsolve::VectorTimeLinearSolve)(::Val{:factor}, pivots, W, active, failed) + n = size(W, 3) + iszero(n) && return nothing + backend = linsolve.backend + vector_time_factor_kernel!(backend)( + W, pivots, active, failed; ndrange = n, workgroupsize = workgroupsize(backend, n) + ) + return nothing +end + +function (linsolve::VectorTimeLinearSolve)(::Val{:solve}, pivots, dest, W, rhs, active, failed) + n = size(W, 3) + iszero(n) && return nothing + backend = linsolve.backend + vector_time_solve_kernel!(backend)( + dest, W, pivots, rhs, active, failed; ndrange = n, workgroupsize = workgroupsize(backend, n) + ) + return nothing +end + +@muladd @kernel function vector_time_factor_kernel!(W, pivots, @Const(active), failed) + i = @index(Global, Linear) + @inbounds if active[i] && !failed[i] + failed[i] = !vector_time_lu!(view(W, :, :, i), view(pivots, :, i)) + end +end + +@muladd @inline function vector_time_lu!(A, pivots) + n = size(A, 1) + @inbounds for k in 1:n + pivot = k + largest = abs(A[k, k]) + isfinite(largest) || return false + for i in (k + 1):n + magnitude = abs(A[i, k]) + isfinite(magnitude) || return false + if magnitude > largest + largest = magnitude + pivot = i + end + end + iszero(largest) && return false + pivots[k] = pivot + if pivot != k + for j in 1:n + A[k, j], A[pivot, j] = A[pivot, j], A[k, j] + end + end + d = A[k, k] + for i in (k + 1):n + A[i, k] /= d + end + for j in (k + 1):n + u = A[k, j] + for i in (k + 1):n + A[i, j] -= A[i, k] * u + end + end + end + @inbounds for j in 1:n, i in 1:j + isfinite(A[i, j]) || return false + end + return true +end + +@muladd @kernel function vector_time_solve_kernel!( + dest, @Const(W), @Const(pivots), rhs, @Const(active), failed + ) + i = @index(Global, Linear) + @inbounds begin + x = view(dest, :, i) + if active[i] && !failed[i] + failed[i] = !vector_time_ldiv!(x, view(W, :, :, i), view(pivots, :, i), view(rhs, :, i)) + end + if !active[i] || failed[i] + for j in 1:length(x) + x[j] = zero(eltype(x)) + end + end + end +end + +@muladd @inline function vector_time_ldiv!(x, factors, pivots, b) + n = length(x) + @inbounds begin + for i in 1:n + x[i] = b[i] + end + for k in 1:n + pivot = pivots[k] + x[k], x[pivot] = x[pivot], x[k] + end + for k in 1:n + for i in (k + 1):n + x[i] -= factors[i, k] * x[k] + end + end + for k in n:-1:1 + x[k] /= factors[k, k] + isfinite(x[k]) || return false + for i in 1:(k - 1) + x[i] -= factors[i, k] * x[k] + end + end + end + return true +end diff --git a/src/solve.jl b/src/solve.jl index 6e86882f..96ea8648 100644 --- a/src/solve.jl +++ b/src/solve.jl @@ -9,13 +9,26 @@ function SciMLBase.__solve( EnsembleKernelAlgorithm, }; trajectories, batch_size = trajectories, - unstable_check = (dt, u, p, t) -> false, adaptive = true, + unstable_check = nothing, adaptive = true, independent_adaptivity = false, seed = nothing, rng = nothing, rng_func = SciMLBase.default_rng_func, kwargs... ) - if trajectories == 1 + if independent_adaptivity + ensemblealg isa EnsembleGPUArray && adaptive || + throw(ArgumentError("Independent adaptivity requires EnsembleGPUArray and adaptive stepping.")) + unstable_check === nothing || + throw(ArgumentError("Independent adaptivity handles nonfinite trials internally.")) + dt = get(kwargs, :dt, nothing) + if dt isa AbstractVector && length(dt) != trajectories + throw(DimensionMismatch("Pass one initial step size per trajectory.")) + end + else + unstable_check = something(unstable_check, (dt, u, p, t) -> false) + end + + if trajectories == 1 && !independent_adaptivity return SciMLBase.__solve( ensembleprob, alg, EnsembleSerial(); trajectories = 1, seed, rng, rng_func, kwargs... @@ -34,7 +47,7 @@ function SciMLBase.__solve( master_rng = rng, ) - cpu_trajectories = ( + cpu_trajectories = !independent_adaptivity && ( ( ensemblealg isa EnsembleGPUArray || ensemblealg isa EnsembleGPUKernel @@ -93,7 +106,7 @@ function SciMLBase.__solve( ensembleprob, alg, ensemblealg, 1:gpu_trajectories, adaptive; sim_seeds, rng_func, master_rng = rng, - unstable_check, kwargs... + unstable_check, independent_adaptivity, kwargs... ) if cpu_work !== nothing wait(cpu_work.t) @@ -103,16 +116,20 @@ function SciMLBase.__solve( end converged::Bool = false - u = ensembleprob.u_init === nothing ? + u = if independent_adaptivity && ensembleprob.reduction === SciMLBase.DEFAULT_REDUCTION + nothing + elseif ensembleprob.u_init === nothing similar( batch_solve( - ensembleprob, alg, ensemblealg, 1:batch_size, adaptive; + ensembleprob, alg, ensemblealg, 1:min(batch_size, gpu_trajectories), adaptive; sim_seeds, rng_func, master_rng = rng, - unstable_check, kwargs... + unstable_check, independent_adaptivity, kwargs... ), 0 - ) : + ) + else ensembleprob.u_init + end if nprocs() == 1 # While pmap works, this makes much better error messages. @@ -126,7 +143,7 @@ function SciMLBase.__solve( batch_data = batch_solve( ensembleprob, alg, ensemblealg, I, adaptive; sim_seeds, rng_func, master_rng = rng, - unstable_check, kwargs... + unstable_check, independent_adaptivity, kwargs... ) if ensembleprob.reduction !== SciMLBase.DEFAULT_REDUCTION u, _ = ensembleprob.reduction(u, batch_data, I) @@ -147,7 +164,7 @@ function SciMLBase.__solve( x = batch_solve( ensembleprob, alg, ensemblealg, I, adaptive; sim_seeds, rng_func, master_rng = rng, - unstable_check, kwargs... + unstable_check, independent_adaptivity, kwargs... ) yield() if ensembleprob.reduction !== SciMLBase.DEFAULT_REDUCTION @@ -271,7 +288,7 @@ function batch_solve( ensembleprob, alg, ensemblealg::Union{EnsembleArrayAlgorithm, EnsembleKernelAlgorithm}, I, adaptive; - sim_seeds = nothing, + sim_seeds = nothing, independent_adaptivity = false, rng_func = SciMLBase.default_rng_func, master_rng = nothing, kwargs... @@ -346,6 +363,14 @@ function batch_solve( ensembleprob.prob_func(ensembleprob.prob, ctx) end end + if independent_adaptivity + (; dt, options) = vector_time_batch_options(I; kwargs...) + sols = solve_vector_time_batch(probs, alg, ensemblealg.backend; dt, options...) + return map(eachindex(sols)) do i + ctx = _make_ensemble_context(I[i], sim_seeds, rng_func, master_rng) + return ensembleprob.output_func(sols[i], ctx)[1] + end + end u0 = _hcat_batch([Array(probs[i].u0) for i in 1:length(I)]) if !all( diff --git a/test/Project.toml b/test/Project.toml index 68eb659c..90a02f90 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -22,6 +22,7 @@ OrdinaryDiffEqNonlinearSolve = "127b3ac7-2247-4354-8eb6-78cf4e7c58e8" OrdinaryDiffEqRosenbrock = "43230ef6-c299-4910-a778-202eb28ce4ce" OrdinaryDiffEqSDIRK = "2d112036-d095-4a1e-ab9a-08536f3ecdbf" OrdinaryDiffEqStabilizedRK = "358294b1-0aab-51c3-aafe-ad5ab194a2ad" +OrdinaryDiffEqTsit5 = "b1df2697-797e-41e3-8120-5422d3b24e4a" Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" @@ -54,11 +55,12 @@ Optimization = "5" OptimizationOptimisers = "0.3" OrderedCollections = "1, 2.0" OrdinaryDiffEq = "7" -OrdinaryDiffEqCore = "4.18.1" +OrdinaryDiffEqCore = "4.21" OrdinaryDiffEqNonlinearSolve = "2.9" -OrdinaryDiffEqRosenbrock = "2.6.0" +OrdinaryDiffEqRosenbrock = "2.8" OrdinaryDiffEqSDIRK = "2.8.2" OrdinaryDiffEqStabilizedRK = "2" +OrdinaryDiffEqTsit5 = "2.2" Pkg = "< 0.0.1, 1" Random = "< 0.0.1, 1" SafeTestsets = "0.1" diff --git a/test/ensemblegpuarray_vector_time.jl b/test/ensemblegpuarray_vector_time.jl new file mode 100644 index 00000000..7b2713a5 --- /dev/null +++ b/test/ensemblegpuarray_vector_time.jl @@ -0,0 +1,197 @@ +using DiffEqGPU, Test +using OrdinaryDiffEqRosenbrock: Rodas5P +using OrdinaryDiffEqTsit5: Tsit5 +using SciMLBase: ODEFunction, ODEProblem, ReturnCode, remake, solve +using StaticArrays: SVector + +include("utils.jl") + +function rhs_values(u, rate, t) + return (rate * (-u[1] + u[2] / 4) + sin(t), rate * (u[1] / 2 - 2 * u[2]) + t^2) +end + +rhs(u, rate, t) = SVector(rhs_values(u, rate, t)) + +function rhs!(du, u, rate, t) + du[1], du[2] = rhs_values(u, rate, t) + return nothing +end + +function jac!(J, u, rate, t) + J[1, 1] = -rate + J[2, 1] = rate / 2 + J[1, 2] = rate / 4 + J[2, 2] = -2 * rate + return nothing +end + +function tgrad!(dT, u, rate, t) + dT[1] = cos(t) + dT[2] = 2 * t + return nothing +end + +const ode_f = ODEFunction(rhs!; jac = jac!, tgrad = tgrad!, jac_prototype = zeros(2, 2)) +const prob = ODEProblem(ode_f, [1.0, 2.0], (0.0, 1.5), 1.0) +const array_alg = EnsembleGPUArray(backend, 0.0) +const rates = (1.0, 200.0, 1.0) +const opts = (; dt = 0.125, abstol = 1.0e-8, reltol = 1.0e-6) + +@testset "Vector time with $name" for (name, alg, problem) in ( + ("Tsit5", Tsit5(), prob), + ("Rodas5P with analytic derivatives", Rodas5P(), prob), + ("Rodas5P with in-place RHS", Rodas5P(), ODEProblem(rhs!, prob.u0, prob.tspan, prob.p)), + ("Rodas5P with out-of-place RHS", Rodas5P(), ODEProblem(rhs, SVector{2}(prob.u0), prob.tspan, prob.p)), + ) + ensemble = EnsembleProblem(problem; prob_func = (p, ctx) -> remake(p; p = rates[ctx.sim_id])) + mixed = solve( + ensemble, alg, array_alg; + trajectories = length(rates), independent_adaptivity = true, opts... + ).u + singleton = only( + solve( + EnsembleProblem(problem), alg, array_alg; + trajectories = 1, independent_adaptivity = true, opts... + ).u + ) + @test mixed[2].stats.nreject > mixed[1].stats.nreject + @test mixed[2].stats.naccept > mixed[1].stats.naccept + for (i, trajectory) in enumerate(mixed) + reference = solve(remake(problem; p = rates[i]), alg; opts...) + @test trajectory.retcode == ReturnCode.Success + @test first(trajectory.t) == first(problem.tspan) + @test last(trajectory.t) == last(problem.tspan) + @test trajectory.stats.naccept == length(trajectory.t) - 1 + @test last(trajectory.u) ≈ last(reference.u) atol = 5.0e-8 rtol = 2.0e-6 + if rates[i] == 1.0 + @test trajectory.t == singleton.t + @test trajectory.stats.nreject == singleton.stats.nreject + end + end +end + +@testset "Vector-time samples on different physical spans" begin + spans = ((0.0, 1.0), (0.25, 1.5), (1.0, 2.0)) + problem = ODEProblem(rhs!, prob.u0, prob.tspan, prob.p) + ensemble = EnsembleProblem( + problem; prob_func = (p, ctx) -> remake(p; p = rates[ctx.sim_id], tspan = spans[ctx.sim_id]) + ) + alg = Rodas5P() + steps = [1 / 32, 1 / 8, 1 / 64] + tolerances = (; opts.abstol, opts.reltol) + accepted_steps = solve( + ensemble, alg, array_alg; + trajectories = length(spans), independent_adaptivity = true, dt = steps, tolerances... + ).u + for i in (1, 3) + @test accepted_steps[i].t[2] == first(spans[i]) + steps[i] + end + + saveat = 0.25 + sampled = solve( + ensemble, alg, array_alg; + trajectories = length(spans), independent_adaptivity = true, dt = steps, saveat, tolerances... + ).u + for (i, trajectory) in enumerate(sampled) + span = spans[i] + reference = solve(remake(problem; p = rates[i], tspan = span), alg; dt = steps[i], saveat, tolerances...) + @test trajectory.retcode == ReturnCode.Success + @test trajectory.t == collect(first(span):saveat:last(span)) + @test trajectory.t == reference.t + for (u, uref) in zip(trajectory.u, reference.u) + @test u ≈ uref atol = 5.0e-8 rtol = 2.0e-6 + end + end +end + +@testset "Vector trials use the representable time increment" begin + unit_speed!(du, u, p, t) = (du[1] = p; nothing) + t0 = Float64(2^53) + ensemble = EnsembleProblem(ODEProblem(unit_speed!, [0.0], (t0, t0 + 8.0), 1.0)) + sol = solve( + ensemble, Tsit5(), array_alg; + trajectories = 2, independent_adaptivity = true, dt = [3.0, 2.0] + ) + @test sol.u[1].t[2] == t0 + 4.0 + @test sol.u[2].t[2] == t0 + 2.0 + for trajectory in sol.u + @test trajectory.retcode == ReturnCode.Success + @test only.(trajectory.u) ≈ trajectory.t .- t0 atol = 1.0e-14 rtol = 0 + end + + bounded = solve( + ensemble, Tsit5(), array_alg; + trajectories = 2, independent_adaptivity = true, dt = [3.0, 2.0], dtmax = 3.0 + ) + @test bounded.u[1].t[2] == t0 + 2.0 + for trajectory in bounded.u + @test maximum(diff(trajectory.t)) <= 3.0 + @test only.(trajectory.u) ≈ trajectory.t .- t0 atol = 1.0e-14 rtol = 0 + end + + endpoints = solve( + ensemble, Tsit5(), EnsembleGPUArray(backend); + trajectories = 2, independent_adaptivity = true, dt = [3.0, 2.0], save_everystep = false + ) + for (i, trajectory) in enumerate(endpoints.u) + @test trajectory.t == [t0, t0 + 8.0] + @test trajectory.u == sol.u[i].u[[1, end]] + end + + @test_throws DimensionMismatch solve( + ensemble, Tsit5(), array_alg; + trajectories = 2, independent_adaptivity = true, dt = [3.0] + ) +end + +@testset "Rodas5P isolates a nonfinite Jacobian block" begin + function jac_or_inf!(J, u, rate, t) + jac!(J, u, rate, t) + if rate < 0 + J[1, 1] = Inf + end + return nothing + end + f = ODEFunction(rhs!; jac = jac_or_inf!, tgrad = tgrad!, jac_prototype = zeros(2, 2)) + problem = ODEProblem(f, [1.0, 2.0], (0.0, 0.5), 1.0) + ensemble = EnsembleProblem(problem; prob_func = (p, ctx) -> remake(p; p = ctx.sim_id == 1 ? 1.0 : -1.0)) + alg = Rodas5P() + limits = (; dtmin = 1 / 256, maxiters = 20) + healthy, failed = solve( + ensemble, alg, array_alg; + trajectories = 2, independent_adaptivity = true, opts..., limits... + ).u + singleton = only( + solve( + EnsembleProblem(problem), alg, array_alg; + trajectories = 1, independent_adaptivity = true, opts..., limits... + ).u + ) + @test healthy.retcode == ReturnCode.Success + @test healthy.t == singleton.t + @test healthy.u == singleton.u + @test failed.retcode in (ReturnCode.MaxIters, ReturnCode.DtLessThanMin) + @test failed.stats.naccept == 0 + @test failed.t == [0.0] +end + +if GROUP == "CPU" + @testset "The CPU backend supports broadcast into column views" begin + function broadcast_rhs!(du, u, p, t) + du .= p .* u + return nothing + end + initial = [1.0, 2.0] + decay_rates = [-1.0, -2.0] + ensemble = EnsembleProblem(ODEProblem(broadcast_rhs!, initial, (0.0, 0.5), decay_rates)) + sol = solve( + ensemble, Tsit5(), array_alg; + trajectories = 2, independent_adaptivity = true, save_everystep = false, opts... + ) + for trajectory in sol.u + @test trajectory.retcode == ReturnCode.Success + @test trajectory.t == [0.0, 0.5] + @test last(trajectory.u) ≈ initial .* exp.(0.5 .* decay_rates) atol = 5.0e-8 rtol = 2.0e-6 + end + end +end diff --git a/test/runtests.jl b/test/runtests.jl index f6b850a8..1a155416 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -44,6 +44,9 @@ if GROUP in ("CPU", "JLArrays", "CUDA", "AMDGPU") @time @safetestset "EnsembleGPUArray batched LU" begin include("ensemblegpuarray_lufact.jl") end + @time @safetestset "EnsembleGPUArray vector-time OrdinaryDiffEq integration" begin + include("ensemblegpuarray_vector_time.jl") + end end if GROUP == "CPU" || GROUP in SUPPORTS_LUFACT