From 6aa660617c5f00ca5c4528f3315309ee30b1381a Mon Sep 17 00:00:00 2001 From: sasmith-14 <210313780+sasmith-14@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:07:07 +0530 Subject: [PATCH 1/3] Support `DynamicalODEFunction` in `EnsembleGPUArray` `generate_problem` read `prob.f.f`, which a `DynamicalODEFunction` doesn't have, so `DynamicalODEProblem` and `SecondOrderODEProblem` failed with the array ensembles. Split each batched `[v; u]` column and call `f1` and `f2`. Fixes #109 --- src/ensemblegpuarray/problem_generation.jl | 33 ++++++++++++++- test/ensemblegpuarray_dynamical.jl | 49 ++++++++++++++++++++++ test/runtests.jl | 3 ++ 3 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 test/ensemblegpuarray_dynamical.jl diff --git a/src/ensemblegpuarray/problem_generation.jl b/src/ensemblegpuarray/problem_generation.jl index a3799d1a..ce2a2b97 100644 --- a/src/ensemblegpuarray/problem_generation.jl +++ b/src/ensemblegpuarray/problem_generation.jl @@ -22,6 +22,37 @@ 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. +struct DynamicalColumnRHS{F1, F2} + f1::F1 + f2::F2 + n::Int # length of `v` +end + +@inline function (f::DynamicalColumnRHS)(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)(u, p, t) + n = f.n + @views v, x = u[1:n], u[(n + 1):end] + return vcat(f.f1(v, x, p, t), f.f2(v, x, p, t)) +end + +column_rhs(f, u0) = f.f +function column_rhs(f::SciMLBase.DynamicalODEFunction, u0) + return DynamicalColumnRHS(f.f1, f.f2, length(u0.x[1])) +end + function generate_problem( prob::SciMLBase.AbstractODEProblem, u0, @@ -29,7 +60,7 @@ function generate_problem( 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 = DiffEqBase.isinplace(prob) ? gpu_kernel : gpu_kernel_oop function (du, u, p, t) version = get_backend(u) wgs = workgroupsize(version, size(u, 2)) diff --git a/test/ensemblegpuarray_dynamical.jl b/test/ensemblegpuarray_dynamical.jl new file mode 100644 index 00000000..0ee1cfff --- /dev/null +++ b/test/ensemblegpuarray_dynamical.jl @@ -0,0 +1,49 @@ +using DiffEqGPU +using OrdinaryDiffEq: Tsit5 +using SciMLBase: DynamicalODEProblem, SecondOrderODEProblem, EnsembleProblem, + EnsembleSerial, remake, solve +using Test + +# 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 +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 + +probs = [ + "DynamicalODEProblem oop" => DynamicalODEProblem{false}(dv, dx, v0, x0, tspan, Float32[1]), + "DynamicalODEProblem iip" => DynamicalODEProblem{true}(dv!, dx!, v0, x0, tspan, Float32[1]), + "SecondOrderODEProblem" => SecondOrderODEProblem{false}(dv, v0, x0, tspan, Float32[1]), +] + +@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(), EnsembleCPUArray(); 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 diff --git a/test/runtests.jl b/test/runtests.jl index f6b850a8..e2e138cb 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -142,6 +142,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 From b72a36d372386fe432263a332a13ae6638984ef9 Mon Sep 17 00:00:00 2001 From: sasmith-14 <210313780+sasmith-14@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:01:48 +0530 Subject: [PATCH 2/3] Copy out-of-place dynamical derivatives into their slices of du Concatenating the two halves with vcat is generic array code, which doesn't compile for GPUs when a half returns a view of the state (e.g. dx(v, x, p, t) = v, and every out-of-place SecondOrderODEProblem). Write each half into its slice of du instead, through the in-place kernel, and run the DynamicalODEFunction tests on the CUDA, AMDGPU and Metal groups too, with allocation-free out-of-place cases. --- src/ensemblegpuarray/problem_generation.jl | 30 +++++++++++++++++----- test/ensemblegpuarray_dynamical.jl | 25 ++++++++++++++---- test/runtests.jl | 6 +++++ 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src/ensemblegpuarray/problem_generation.jl b/src/ensemblegpuarray/problem_generation.jl index ce2a2b97..6029203b 100644 --- a/src/ensemblegpuarray/problem_generation.jl +++ b/src/ensemblegpuarray/problem_generation.jl @@ -25,14 +25,18 @@ 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. -struct DynamicalColumnRHS{F1, F2} +# 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)(du, u, p, t) +@inline function (f::DynamicalColumnRHS{true})(du, u, p, t) n = f.n @views begin v, x = u[1:n], u[(n + 1):end] @@ -42,17 +46,29 @@ end return nothing end -@inline function (f::DynamicalColumnRHS)(u, p, t) +@inline function (f::DynamicalColumnRHS{false})(du, u, p, t) n = f.n @views v, x = u[1:n], u[(n + 1):end] - return vcat(f.f1(v, x, p, t), f.f2(v, x, p, t)) + 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(f.f1, f.f2, length(u0.x[1])) + return DynamicalColumnRHS{SciMLBase.isinplace(f)}(f.f1, f.f2, length(u0.x[1])) end +# `DynamicalColumnRHS` always writes into `du`, so it runs in the in-place kernel +column_kernel(f, prob) = DiffEqBase.isinplace(prob) ? gpu_kernel : gpu_kernel_oop +column_kernel(::DynamicalColumnRHS, prob) = gpu_kernel + function generate_problem( prob::SciMLBase.AbstractODEProblem, u0, @@ -60,7 +76,7 @@ function generate_problem( jac_prototype, colorvec ) - _f = let f = column_rhs(prob.f, prob.u0), 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)) diff --git a/test/ensemblegpuarray_dynamical.jl b/test/ensemblegpuarray_dynamical.jl index 0ee1cfff..c714f9c3 100644 --- a/test/ensemblegpuarray_dynamical.jl +++ b/test/ensemblegpuarray_dynamical.jl @@ -1,12 +1,16 @@ -using DiffEqGPU +using DiffEqGPU, StaticArrays using OrdinaryDiffEq: Tsit5 using SciMLBase: DynamicalODEProblem, SecondOrderODEProblem, EnsembleProblem, EnsembleSerial, remake, solve 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 +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] @@ -31,16 +35,27 @@ function exact(k, t) return vcat(-w .* x0 .* sin(w * t) .+ v0 .* cos(w * t), x0 .* cos(w * t) .+ v0 ./ w .* sin(w * t)) end -probs = [ +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]), - "DynamicalODEProblem iip" => DynamicalODEProblem{true}(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]), + "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(), EnsembleCPUArray(); kw...) + 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 diff --git a/test/runtests.jl b/test/runtests.jl index e2e138cb..e41cd000 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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") From e3c781c6206e7cc661587b1b47e3adf675d2bfd3 Mon Sep 17 00:00:00 2001 From: sasmith-14 <210313780+sasmith-14@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:22:50 +0530 Subject: [PATCH 3/3] Reject unsupported dynamical batches, fix in-place SecondOrderODEProblem on CPU Array ensembles split every column where the first trajectory's state splits, and the batched ODEFunction has no mass matrix, so a batch with different v lengths or a non-identity mass matrix returned wrong states with Success. batch_solve and vectorized_map_solve now throw an ArgumentError for those before packing the state, and the EnsembleGPUArray docstring states both limits. The dynamical right-hand side now runs in a kernel without @Const(u). On the CPU, @Const wraps u in Base.Experimental.Const, and broadcasting from a view of it, like the du .= v that SecondOrderODEProblem generates, throws a MethodError (elsize) in Base's aliasing check. --- src/algorithms.jl | 3 ++ src/ensemblegpuarray/kernels.jl | 5 +++ src/ensemblegpuarray/lowerlevel_solve.jl | 1 + src/ensemblegpuarray/problem_generation.jl | 23 ++++++++++- src/solve.jl | 1 + test/ensemblegpuarray_dynamical.jl | 44 +++++++++++++++++++++- 6 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/algorithms.jl b/src/algorithms.jl index 11ca0024..e00736b4 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -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 diff --git a/src/ensemblegpuarray/kernels.jl b/src/ensemblegpuarray/kernels.jl index 832092f7..33931011 100644 --- a/src/ensemblegpuarray/kernels.jl +++ b/src/ensemblegpuarray/kernels.jl @@ -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) diff --git a/src/ensemblegpuarray/lowerlevel_solve.jl b/src/ensemblegpuarray/lowerlevel_solve.jl index 1e3440f3..3f576af3 100644 --- a/src/ensemblegpuarray/lowerlevel_solve.jl +++ b/src/ensemblegpuarray/lowerlevel_solve.jl @@ -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)]) diff --git a/src/ensemblegpuarray/problem_generation.jl b/src/ensemblegpuarray/problem_generation.jl index 6029203b..355f6530 100644 --- a/src/ensemblegpuarray/problem_generation.jl +++ b/src/ensemblegpuarray/problem_generation.jl @@ -65,9 +65,28 @@ function column_rhs(f::SciMLBase.DynamicalODEFunction, u0) return DynamicalColumnRHS{SciMLBase.isinplace(f)}(f.f1, f.f2, length(u0.x[1])) end -# `DynamicalColumnRHS` always writes into `du`, so it runs in the in-place kernel +# 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) = gpu_kernel +column_kernel(::DynamicalColumnRHS, prob) = dynamical_kernel function generate_problem( prob::SciMLBase.AbstractODEProblem, diff --git a/src/solve.jl b/src/solve.jl index 6e86882f..257d8167 100644 --- a/src/solve.jl +++ b/src/solve.jl @@ -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( diff --git a/test/ensemblegpuarray_dynamical.jl b/test/ensemblegpuarray_dynamical.jl index c714f9c3..910c8542 100644 --- a/test/ensemblegpuarray_dynamical.jl +++ b/test/ensemblegpuarray_dynamical.jl @@ -1,7 +1,9 @@ using DiffEqGPU, StaticArrays using OrdinaryDiffEq: Tsit5 -using SciMLBase: DynamicalODEProblem, SecondOrderODEProblem, EnsembleProblem, - EnsembleSerial, remake, solve +using OrdinaryDiffEqRosenbrock: Rosenbrock23 +using SciMLBase: DynamicalODEFunction, DynamicalODEProblem, SecondOrderODEProblem, + EnsembleProblem, EnsembleSerial, ReturnCode, remake, solve +using LinearAlgebra: Diagonal using Test include("utils.jl") @@ -45,6 +47,8 @@ cpu_probs = [ # 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" => @@ -62,3 +66,39 @@ GROUP == "CPU" && append!(probs, cpu_probs) @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