diff --git a/src/solve.jl b/src/solve.jl index 43651591..6e86882f 100644 --- a/src/solve.jl +++ b/src/solve.jl @@ -190,7 +190,8 @@ struct KernelODEProblem{U, T, IIP, P, F, K, PT} <: SciMLBase.AbstractODEProblem{ end _kernel_record(prob) = prob @noinline function _kernel_record(prob::SciMLBase.ImmutableODEProblem{U, T, IIP, P, F, K, PT}) where {U, T, IIP, P, F, K, PT} - return KernelODEProblem{U, T, IIP, P, F, K, PT}(prob.p, prob.u0, prob.tspan, prob.f, prob.kwargs, prob.problem_type) + kwargs = NamedTuple(prob.kwargs) + return KernelODEProblem{U, T, IIP, P, F, typeof(kwargs), PT}(prob.p, prob.u0, prob.tspan, prob.f, kwargs, prob.problem_type) end @inline function _ensemble_problem_fields_isbits(prob) @@ -213,7 +214,7 @@ _shallow_reconstruct_problem(prob) = deepcopy(prob) deepcopy(prob) end -@noinline function _make_kernel_problem(ensembleprob, i, sim_seeds, rng_func, master_rng) +@noinline function _make_kernel_problem(ensembleprob, i, sim_seeds, rng_func::F, master_rng) where {F} ctx = _make_ensemble_context(i, sim_seeds, rng_func, master_rng) prob = ensembleprob.safetycopy ? _safety_copy_ensemble_prob(ensembleprob.prob) : ensembleprob.prob @@ -226,16 +227,15 @@ end @inline _unwrap_kernel_host(prob::Ref) = prob[] # Kernels read problem fields (`f`, `u0`, `tspan`, `p`, `kwargs`) directly, so -# outside autodiff a CPU kernel can consume the adapted problem without the +# outside autodiff kernels can consume the adapted problem without the # `KernelODEProblem` repackaging. Enzyme needs the record layout for host # aggregate shadows. -@inline function _adapt_kernel_problem(backend::CPU, prob) +@inline function _adapt_kernel_problem(backend, prob) adapted = adapt(backend, prob) return within_autodiff() ? _kernel_record(adapted) : adapted end -@inline _adapt_kernel_problem(backend, prob) = _kernel_record(adapt(backend, prob)) -function _prepare_kernel_problems(ensembleprob, backend, I, sim_seeds, rng_func, master_rng) +function _prepare_kernel_problems(ensembleprob, backend, I, sim_seeds, rng_func::F, master_rng) where {F} first_prob = _make_kernel_problem(ensembleprob, first(I), sim_seeds, rng_func, master_rng) first_adapted = _adapt_kernel_problem(backend, first_prob) first_ref = _wrap_kernel_host(first_prob) diff --git a/test/enzyme/problem_adaptation.jl b/test/enzyme/problem_adaptation.jl new file mode 100644 index 00000000..6644668c --- /dev/null +++ b/test/enzyme/problem_adaptation.jl @@ -0,0 +1,37 @@ +using DiffEqGPU, Enzyme, KernelAbstractions, SciMLBase, StaticArrays, Test + +const adaptation_backends = if get(ENV, "GROUP", "Enzyme") == "CUDA" + using CUDA + (CUDA.CUDABackend(),) +else + using JLArrays + (CPU(), JLArrays.JLBackend()) +end + +function adaptation_field_loss(x::Vector{T}, backend) where {T} + f = let rate = x[5] + (u, p, t) -> rate * u + end + prob = SciMLBase.ImmutableODEProblem{false}( + f, SVector(x[1]), (x[2], x[3]), SVector(x[4]); weight = x[6] + ) + adapted = DiffEqGPU._adapt_kernel_problem(backend, prob) + if Enzyme.within_autodiff() + @assert adapted isa DiffEqGPU.KernelODEProblem + end + return adapted.u0[1]^2 + adapted.tspan[1] * adapted.tspan[2] + + adapted.p[1]^2 + only(adapted.f(SVector(T(3)), adapted.p, zero(T))) + + adapted.kwargs[:weight]^2 +end + +@testset "Problem adaptation preserves active fields ($backend)" for backend in adaptation_backends + for T in (Float32, Float64) + x = T[2, 0.25, 1.25, 0.5, 0.75, 7] + @test adaptation_field_loss(x, backend) == T(55.8125) + dx = ones(T, 6) + for repetitions in 1:2 + Enzyme.autodiff(Reverse, adaptation_field_loss, Active, Duplicated(x, dx), Const(backend)) + @test dx == ones(T, 6) + repetitions * T[4, 1.25, 0.25, 1, 3, 14] + end + end +end diff --git a/test/enzyme_environment.jl b/test/enzyme_environment.jl index 90eb6140..c07bfa66 100644 --- a/test/enzyme_environment.jl +++ b/test/enzyme_environment.jl @@ -7,6 +7,7 @@ let using SciMLTesting SciMLTesting.activate_group_env($(repr(envdir))) include($(repr(joinpath(envdir, "imports.jl")))) + include($(repr(joinpath(envdir, "problem_adaptation.jl")))) if $cuda include($(repr(joinpath(envdir, "cuda_records.jl")))) end diff --git a/test/gpu_kernel_de/host_fastpath.jl b/test/gpu_kernel_de/host_fastpath.jl index 8fe6b511..badbdf3b 100644 --- a/test/gpu_kernel_de/host_fastpath.jl +++ b/test/gpu_kernel_de/host_fastpath.jl @@ -1,23 +1,4 @@ -using Adapt, DiffEqGPU, KernelAbstractions, SciMLBase, StaticArrays, Test - -struct HostAdaptRecipe{T} - rate::T -end -Adapt.adapt_structure(::KernelAbstractions.CPU, p::HostAdaptRecipe) = SVector(p.rate) - -struct PrecisionRecipe <: AbstractVector{Float32} - rate::Float32 -end -Base.size(::PrecisionRecipe) = (1,) -Base.getindex(p::PrecisionRecipe, i::Int) = p.rate -Adapt.adapt_structure(::KernelAbstractions.CPU, p::PrecisionRecipe) = SVector(Float64(p.rate)) - -struct RateRecipe - rate::Float64 -end -const _ADAPT_CALLS = Ref(0) -Adapt.adapt_structure(::KernelAbstractions.CPU, p::RateRecipe) = - (_ADAPT_CALLS[] += 1; SVector(p.rate * _ADAPT_CALLS[])) +using DiffEqGPU, KernelAbstractions, SciMLBase, StaticArrays, Test @testset "Kernel ensemble host storage" begin f(u, p, t) = SVector(p[1] * u[1]) @@ -102,56 +83,27 @@ Adapt.adapt_structure(::KernelAbstractions.CPU, p::RateRecipe) = @test bits_prob.p == SVector(0.2f0) end -@testset "Kernel host storage respects user adapt_structure" begin - f(u, p, t) = p[1] * u - prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), HostAdaptRecipe(0.2)) - @test isbits(DiffEqGPU.make_prob_compatible(prob)) - backend = KernelAbstractions.CPU() - for safetycopy in (true, false) - ensemble = EnsembleProblem(prob; safetycopy) - sol = solve( - ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); - trajectories = 2, adaptive = false, dt = 0.01, save_everystep = false - ) - @test only(sol.u[1].u[end]) ≈ exp(0.2) rtol = 1.0e-10 - end -end +include("problem_adaptation.jl") -@testset "Kernel host storage honors precision-changing adaptation" begin - # Float32 `p[1] + 1 - p[1]` is zero for rate 2^24; the adapted Float64 - # parameter makes it one, so the adapted endpoint must reach the kernel. - f(u, p, t) = (p[1] + 1 - p[1]) * u - prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), PrecisionRecipe(2.0f0^24)) +function kernel_preparation_allocations(::Type{T}, n) where {T} + f(u, p, t) = p[1] * u + prob = ODEProblem{false}(f, SVector{3, T}(1, 0, 0), (zero(T), one(T)), SVector(T(0.2))) + ensemble = EnsembleProblem( + prob; safetycopy = false, + prob_func = (prob, ctx) -> remake(prob; p = SVector(T(ctx.sim_id) / n)) + ) backend = KernelAbstractions.CPU() - compatible = DiffEqGPU.make_prob_compatible(prob) - adapted = Adapt.adapt(backend, compatible) - @test isbits(compatible) - @test isequal(compatible.p, adapted.p) - @test f(compatible.u0, compatible.p, 0.0) == SVector(0.0) - @test f(adapted.u0, adapted.p, 0.0) == SVector(1.0) - for safetycopy in (true, false) - ensemble = EnsembleProblem(prob; safetycopy) - sol = solve( - ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); - trajectories = 2, adaptive = false, dt = 0.01, save_everystep = false - ) - @test only(sol.u[1].u[end]) ≈ exp(1.0) rtol = 1.0e-10 - end + prepare() = DiffEqGPU._prepare_kernel_problems( + ensemble, backend, 1:n, nothing, SciMLBase.default_rng_func, nothing + ) + probs = prepare() + bytes = @allocated prepare() + return bytes, Base.summarysize(probs) end -@testset "Kernel host storage adapts once per trajectory" begin - f(u, p, t) = p[1] * u - prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), RateRecipe(0.1)) - backend = KernelAbstractions.CPU() - for safetycopy in (true, false) - _ADAPT_CALLS[] = 0 - ensemble = EnsembleProblem(prob; safetycopy) - sol = solve( - ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); - trajectories = 3, adaptive = false, dt = 0.01, save_everystep = false - ) - endpoints = [only(s.u[end]) for s in sol.u] - @test _ADAPT_CALLS[] == 3 - @test endpoints ≈ exp.([0.1, 0.2, 0.3]) rtol = 1.0e-10 - end +@testset "Kernel preparation temporary allocations" for T in (Float32, Float64) + kernel_preparation_allocations(T, 4096) + bytes, storage = kernel_preparation_allocations(T, 4096) + # The storage multiple permits allocator overhead while bounding temporary allocations. + @test bytes < 4storage end diff --git a/test/gpu_kernel_de/problem_adaptation.jl b/test/gpu_kernel_de/problem_adaptation.jl new file mode 100644 index 00000000..f79c476d --- /dev/null +++ b/test/gpu_kernel_de/problem_adaptation.jl @@ -0,0 +1,107 @@ +using Adapt, DiffEqGPU, KernelAbstractions, SciMLBase, StaticArrays, Test + +const backend = if get(ENV, "GROUP", "CPU") == "CUDA" + using CUDA + CUDA.CUDABackend() +elseif get(ENV, "GROUP", "CPU") == "JLArrays" + using JLArrays + JLArrays.JLBackend() +else + KernelAbstractions.CPU() +end + +struct HostAdaptRecipe{T} + rate::T +end +Adapt.adapt_structure(::typeof(backend), p::HostAdaptRecipe) = SVector(p.rate) + +struct PrecisionRecipe <: AbstractVector{Float32} + rate::Float32 +end +Base.size(::PrecisionRecipe) = (1,) +Base.getindex(p::PrecisionRecipe, i::Int) = p.rate +Adapt.adapt_structure(::typeof(backend), p::PrecisionRecipe) = SVector(Float64(p.rate)) + +struct RateRecipe + rate::Float64 +end +const _ADAPT_CALLS = Ref(0) +Adapt.adapt_structure(::typeof(backend), p::RateRecipe) = + (_ADAPT_CALLS[] += 1; SVector(p.rate * _ADAPT_CALLS[])) + +@testset "Primal kernel problem representation" for T in (Float32, Float64) + f = let rate = T(0.25) + (u, p, t) -> rate * p[1] * u + end + prob = ODEProblem{false}(f, SVector(one(T)), (zero(T), one(T)), SVector(T(0.2))) + for safetycopy in (false, true) + ensemble = EnsembleProblem( + prob; safetycopy, + prob_func = (prob, ctx) -> remake(prob; p = SVector(T(ctx.sim_id) / 10)) + ) + host, adapted = DiffEqGPU._prepare_kernel_problems( + ensemble, backend, 1:3, nothing, SciMLBase.default_rng_func, nothing + ) + @test eltype(host) <: SciMLBase.ImmutableODEProblem + @test eltype(adapted) <: SciMLBase.ImmutableODEProblem + @test adapted[1] === Adapt.adapt(backend, host[1]) + @test [p.p[1] for p in host] == T[0.1, 0.2, 0.3] + @test all(p -> isbits(p), adapted) + @test all(p -> p.f(p.u0, p.p, zero(T)) == T(0.25) * p.p[1] * p.u0, adapted) + end +end + +@testset "Kernel host storage respects user adapt_structure" begin + f(u, p, t) = p[1] * u + prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), HostAdaptRecipe(0.2)) + @test isbits(DiffEqGPU.make_prob_compatible(prob)) + for safetycopy in (true, false) + ensemble = EnsembleProblem(prob; safetycopy) + sol = solve( + ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); + trajectories = 2, adaptive = false, dt = 0.01, save_everystep = false + ) + @test only(sol.u[1].u[end]) ≈ exp(0.2) rtol = 1.0e-10 + @test sol.u isa Vector + @test sol.u[1].prob isa SciMLBase.ImmutableODEProblem + @test sol.u[1].prob.p === prob.p + end +end + +@testset "Kernel host storage honors precision-changing adaptation" begin + # Float32 `p[1] + 1 - p[1]` is zero for rate 2^24; the adapted Float64 + # parameter makes it one, so the adapted endpoint must reach the kernel. + f(u, p, t) = (p[1] + 1 - p[1]) * u + prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), PrecisionRecipe(2.0f0^24)) + compatible = DiffEqGPU.make_prob_compatible(prob) + adapted = Adapt.adapt(backend, compatible) + @test isbits(compatible) + @test isequal(compatible.p, adapted.p) + @test f(compatible.u0, compatible.p, 0.0) == SVector(0.0) + @test f(adapted.u0, adapted.p, 0.0) == SVector(1.0) + for safetycopy in (true, false) + ensemble = EnsembleProblem(prob; safetycopy) + sol = solve( + ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); + trajectories = 2, adaptive = false, dt = 0.01, save_everystep = false + ) + @test only(sol.u[1].u[end]) ≈ exp(1.0) rtol = 1.0e-10 + end +end + +@testset "Kernel host storage adapts once per trajectory" begin + f(u, p, t) = p[1] * u + prob = ODEProblem{false}(f, SVector(1.0), (0.0, 1.0), RateRecipe(0.1)) + for safetycopy in (true, false) + _ADAPT_CALLS[] = 0 + ensemble = EnsembleProblem(prob; safetycopy) + sol = solve( + ensemble, GPUTsit5(), EnsembleGPUKernel(backend, 0.0); + trajectories = 3, adaptive = false, dt = 0.01, save_everystep = false + ) + endpoints = [only(s.u[end]) for s in sol.u] + @test _ADAPT_CALLS[] == 3 + @test endpoints ≈ exp.([0.1, 0.2, 0.3]) rtol = 1.0e-10 + @test all(s -> s.prob.p === prob.p, sol.u) + end +end diff --git a/test/runtests.jl b/test/runtests.jl index a0a4a6b1..f6922a1e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -153,6 +153,12 @@ if GROUP == "JLArrays" end end +if GROUP in ("CUDA", "JLArrays") + @time @safetestset "Kernel problem adaptation" begin + include("gpu_kernel_de/problem_adaptation.jl") + end +end + if GROUP == "CUDA" @testset "Callbacks" begin # Causes dynamic function invocation