diff --git a/HISTORY.md b/HISTORY.md index 793d8c528..f8b9d45a8 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,6 +1,10 @@ # Breaking updates and feature summaries across releases ## Unreleased + - New `isolated_copy(jprob)` returns a copy of a `JumpProblem` with its own jump state, for + concurrent solves and integrators that are alive at the same time. Unlike `deepcopy`, it + shares the wrapped problem, which makes it much cheaper for problems built with + ModelingToolkit or Catalyst. - `SortingDirect`, `RDirect`, `DirectCR`, `RSSA` and `RSSACR` now recompute their running sums of the rates when rounding errors may have made them inaccurate, using a bound on those errors that they update as the rates change. When every rate became zero, the diff --git a/docs/src/api.md b/docs/src/api.md index 454de5b4d..1380ddf84 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -14,6 +14,7 @@ SSAStepper SplitCoupledJumpProblem reset_aggregated_jumps! remake(::JumpProblem) +isolated_copy ``` ## Jump Types diff --git a/docs/src/tutorials/ensembles_and_problem_reuse.md b/docs/src/tutorials/ensembles_and_problem_reuse.md index 72e75a2f0..69b2623a7 100644 --- a/docs/src/tutorials/ensembles_and_problem_reuse.md +++ b/docs/src/tutorials/ensembles_and_problem_reuse.md @@ -12,7 +12,8 @@ of every solve. They never copy it. This makes repeated solves fast, but it mean **one `JumpProblem` supports one active solve or integrator at a time**: - Repeated serial solves of one problem are safe and fast. - - Concurrent solves, from threads or tasks, need independent copies of the problem. + - Concurrent solves, from threads or tasks, need independent copies of the problem, + made with [`isolated_copy`](@ref). - Problems created with `remake` share the original's jump state. - `EnsembleProblem`s create the copies they need for you. @@ -81,8 +82,8 @@ end ``` However, the original and remade problems must not be solved concurrently, and must -not be used for integrators that are alive at the same time. Use `deepcopy` when you -need an independent problem. +not be used for integrators that are alive at the same time. Use +[`isolated_copy`](@ref) when you need an independent problem. ## Ensembles @@ -168,14 +169,16 @@ between all threads. ## Manual threading When launching tasks yourself, give each task its own copy of the problem, made once -per task and reused for all of that task's solves: +per task and reused for all of that task's solves. [`isolated_copy`](@ref) copies the +problem's jump state but shares the problem it wraps, which makes it much cheaper than +`deepcopy` for problems built with ModelingToolkit or Catalyst: ```@example reuse nsims = 1000 chunks = Iterators.partition(1:nsims, cld(nsims, Threads.nthreads())) tasks = map(chunks) do chunk Threads.@spawn begin - local_prob = deepcopy(jprob) # one independent copy per task + local_prob = isolated_copy(jprob) # one independent copy per task [solve(local_prob, SSAStepper()).u[end][1] for _ in chunk] end end @@ -189,8 +192,8 @@ independent problems: ```@example reuse Random.seed!(3) # hide -integrator1 = init(deepcopy(jprob), SSAStepper()) -integrator2 = init(deepcopy(jprob), SSAStepper()) +integrator1 = init(isolated_copy(jprob), SSAStepper()) +integrator2 = init(isolated_copy(jprob), SSAStepper()) step!(integrator1) step!(integrator2) integrator1.t, integrator2.t @@ -286,6 +289,6 @@ serial and threaded runs generally give different trajectories. | `prob_func` returning a shared problem | Avoid | n/a | No | | Stateful callbacks in ensembles | Pass to `JumpProblem`, reset in `initialize` | Copied with the problem | Yes | | Stateful callbacks passed to `solve` | Avoid with threads | Shared | No | -| Manual threads or tasks | `deepcopy` once per task | One per task | Yes | -| Simultaneously alive integrators | `deepcopy` each problem | One per integrator | Yes | +| Manual threads or tasks | `isolated_copy` once per task | One per task | Yes | +| Simultaneously alive integrators | `isolated_copy` for each integrator | One per integrator | Yes | | `EnsembleDistributed`, `pmap_batch_size > 1` | `safetycopy = true` or `pmap_batch_size = 1` | One per trajectory, or per worker | Yes with these settings | diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index e70af8dca..55dd00beb 100644 --- a/src/JumpProcesses.jl +++ b/src/JumpProcesses.jl @@ -154,7 +154,7 @@ export PureLeaping # core problem and timestepping include("problem.jl") -export JumpProblem, SplitCoupledJumpProblem +export JumpProblem, SplitCoupledJumpProblem, isolated_copy include("solve.jl") export init, solve, solve! diff --git a/src/problem.jl b/src/problem.jl index 5ac596c5d..505945cb5 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -102,7 +102,8 @@ examples and commonly asked questions. - Repeated serial solves of one problem are safe, and avoid copying. - Concurrent solves from multiple threads or tasks, and integrators that are alive at - the same time, each need an independent copy, such as `deepcopy(jprob)`. + the same time, each need an independent copy. [`isolated_copy`](@ref) copies only + the jump state, while `deepcopy(jprob)` also copies the wrapped problem. - `remake(jprob; ...)` shares the original's jump state, so remade problems are not independent for concurrent use. - `EnsembleProblem` supplies isolation. `EnsembleSerial` reuses the problem @@ -221,8 +222,8 @@ The new problem shares the original's jump aggregator and jump callbacks rather copying them. Solvers owned by JumpProcesses re-initialize this state from the problem being solved at every `init`, so the original and remade problems can be solved one after another. They must not be solved concurrently, or used for integrators that are alive at -the same time; use `deepcopy` to obtain an independent problem. `SortingDirect`'s learned -search order is also shared. +the same time; use [`isolated_copy`](@ref) to obtain an independent problem. +`SortingDirect`'s learned search order is also shared. """ function DiffEqBase.remake(jprob::JumpProblem; u0 = missing, p = missing, interpret_symbolicmap = true, use_defaults = false, kwargs...) @@ -283,6 +284,96 @@ function DiffEqBase.remake(jprob::JumpProblem; u0 = missing, p = missing, jprob.massaction_jump, jprob.kwargs) end +""" + isolated_copy(jprob::JumpProblem) + +Return a copy of `jprob` with its own jump state, so that it can be solved concurrently with +`jprob`, or used for an integrator that is alive at the same time as one of `jprob`. + +## Arguments + + - `jprob`: the `JumpProblem` to copy. + +## Returns + +A `JumpProblem` of the same type as `jprob`, sharing the wrapped problem `jprob.prob`. + +## Details + +The copy is like `deepcopy(jprob)`, except that it shares the wrapped problem, including its +function, initial condition and parameters. The jump aggregator and its callbacks, the +jumps, and the callbacks passed to the `JumpProblem` constructor are copied, so the copy +starts from the same state as `jprob`, including `SortingDirect`'s learned search order. +For problems built with ModelingToolkit or Catalyst, sharing the wrapped problem makes +`isolated_copy` much cheaper than `deepcopy`. + +Since the parameters are shared and solvers alias them by default, a callback that modifies +`integrator.p` also modifies the parameters of `jprob`. To give the copy its own +parameters, use `remake(isolated_copy(jprob); p = new_p)`. Likewise, solves that alias +`u0` modify the shared initial condition. Rate and affect functions should not store +mutable state, since copies may share them. + +## Example + +```julia +# One copy per task, each with its own parameters +tasks = map([1.0, 2.0, 3.0]) do birth_rate + Threads.@spawn solve(remake(isolated_copy(jprob); p = [birth_rate, 0.1]), SSAStepper()) +end +sols = fetch.(tasks) +``` +""" +function isolated_copy(jprob::JumpProblem) + state = JumpState((jprob.discrete_jump_aggregation, jprob.jump_callback, + jprob.constant_jumps, jprob.variable_jumps, jprob.regular_jump, + jprob.massaction_jump, jprob.kwargs)) + agg, cbs, crjs, vrjs, rj, maj, kwargs = deepcopy(state).fields + remaker_of(jprob)(jprob.prob, jprob.aggregator, agg, cbs, crjs, vrjs, rj, maj, kwargs) +end + +# The fields of a `JumpProblem` other than the wrapped problem and the aggregator, copied +# together so that the copied callbacks use the copied aggregation +struct JumpState{F <: Tuple} + fields::F +end + +# A deep copy of a `FunctionWrapper` keeps calling the original object through a raw +# pointer, so the wrappers in the jump state are shared instead. Solves don't mutate them. +function Base.deepcopy_internal(state::JumpState, stackdict::IdDict) + share_function_wrappers!(stackdict, state.fields, IdSet{Any}()) + JumpState(Base.deepcopy_internal(state.fields, stackdict)) +end + +function share_function_wrappers!(stackdict, wrapper::FunctionWrappers.FunctionWrapper, + seen) + stackdict[wrapper] = wrapper + nothing +end + +function share_function_wrappers!(stackdict, x::Array, seen) + (isbitstype(eltype(x)) || x in seen) && return nothing + push!(seen, x) + for i in eachindex(x) + isassigned(x, i) && share_function_wrappers!(stackdict, x[i], seen) + end + nothing +end + +# Wrappers are only stored in JumpProcesses' own types and in SciMLBase callbacks +function share_function_wrappers!(stackdict, x, seen) + (x isa Union{Tuple, NamedTuple} || is_jump_state_type(x)) || return nothing + if ismutable(x) + x in seen && return nothing + push!(seen, x) + end + for i in 1:nfields(x) + isdefined(x, i) && share_function_wrappers!(stackdict, getfield(x, i), seen) + end + nothing +end + +is_jump_state_type(x) = parentmodule(typeof(x)) in (JumpProcesses, SciMLBase) + DiffEqBase.isinplace(::JumpProblem{iip}) where {iip} = iip JumpProblem(prob::JumpProblem) = prob diff --git a/test/isolated_copy.jl b/test/isolated_copy.jl new file mode 100644 index 000000000..5a7cc772b --- /dev/null +++ b/test/isolated_copy.jl @@ -0,0 +1,164 @@ +using JumpProcesses, OrdinaryDiffEq, SciMLBase, Test + +# `isolated_copy` gives a problem its own jump state while sharing the wrapped problem. +# Copies must behave like independent problems (`deepcopy`), also when used at the same +# time as the original. + +path(sol) = (sol.t, sol.u) + +# A <-> B, as mass-action or constant-rate jumps +function ab_jprob(aggregator; massaction = true, kwargs...) + prob = DiscreteProblem([12, 8], (0.0, 5.0), [0.7, 0.4]) + reactant_stoch = [[1 => 1], [2 => 1]] + net_stoch = [[1 => -1, 2 => 1], [1 => 1, 2 => -1]] + if massaction + maj = MassActionJump(reactant_stoch, net_stoch; param_idxs = [1, 2]) + return JumpProblem(prob, aggregator, maj; kwargs...) + end + + ab!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing) + ba!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing) + jumps = (ConstantRateJump((u, p, t) -> p[1] * u[1], ab!), + ConstantRateJump((u, p, t) -> p[2] * u[2], ba!)) + JumpProblem(prob, aggregator, jumps...; dep_graph = [[1, 2], [1, 2]], + vartojumps_map = [[1], [2]], jumptovars_map = [[1, 2], [1, 2]], kwargs...) +end + +# Steps two integrators in turn before finishing both, so that both are alive at once +function interleaved_paths(prob1, prob2, alg; seeds = (1, 2), nsteps = 10) + integrators = (init(prob1, alg; seed = seeds[1]), init(prob2, alg; seed = seeds[2])) + for _ in 1:nsteps + foreach(step!, integrators) + end + foreach(solve!, integrators) + map(integrator -> path(integrator.sol), integrators) +end + +# Stops a simulation after `n` jumps; its counter is callback state +function stop_after_jumps(n) + njumps = Ref(0) + reset!(cb, u, t, integrator) = (njumps[] = 0) + function affect!(integrator) + njumps[] += 1 + njumps[] >= n && terminate!(integrator) + end + DiscreteCallback((u, t, integrator) -> true, affect!; initialize = reset!) +end + +@testset "Shares the wrapped problem and copies the jump state" begin + jprob = ab_jprob(Direct(); callback = stop_after_jumps(5), tstops = [1.0]) + jcopy = isolated_copy(jprob) + + @test jcopy isa typeof(jprob) + @test jcopy.prob === jprob.prob + @test jcopy.aggregator === jprob.aggregator + @test jcopy.discrete_jump_aggregation !== jprob.discrete_jump_aggregation + @test jcopy.jump_callback !== jprob.jump_callback + @test jcopy.kwargs[:callback] !== jprob.kwargs[:callback] + @test jcopy.kwargs[:tstops] == jprob.kwargs[:tstops] + + # The copied callback uses the copied aggregation, also in integrators + jump_cb = only(jcopy.jump_callback.discrete_callbacks) + @test jump_cb.condition === jcopy.discrete_jump_aggregation + @test init(jcopy, SSAStepper()).cb.condition === jcopy.discrete_jump_aggregation + + # A remade copy shares the copy's jump state, not the original's + remade = remake(jcopy; p = [1.0, 1.0]) + @test remade.discrete_jump_aggregation === jcopy.discrete_jump_aggregation + @test remade.prob.p == [1.0, 1.0] + @test jprob.prob.p == [0.7, 0.4] +end + +@testset "Integrators alive at the same time: $(nameof(typeof(aggregator))), \ + massaction = $massaction" for aggregator in JumpProcesses.JUMP_AGGREGATORS, + massaction in (true, false) + + jprob = ab_jprob(aggregator; massaction) + refs = map(seed -> path(solve(deepcopy(jprob), SSAStepper(); seed)), (1, 2)) + + # `jprob` stays unsolved until the last check: SortingDirect's learned order is copied + copies = (isolated_copy(jprob), isolated_copy(jprob)) + @test interleaved_paths(copies..., SSAStepper()) == refs + @test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs +end + +@testset "ODE problems with variable-rate jumps: $(nameof(typeof(vr_aggregator)))" for vr_aggregator in (VR_FRM(), VR_Direct(), VR_DirectFW()) + + # Growth of u[1], with births of u[2] at rate u[1] and resets of u[1] at a constant rate + f!(du, u, p, t) = (du[1] = p[1] * u[1]; du[2] = 0; nothing) + oprob = ODEProblem(f!, [1.0, 0.0], (0.0, 3.0), [0.5]) + birth = VariableRateJump((u, p, t) -> u[1], + integrator -> (integrator.u[2] += 1; nothing)) + reset = ConstantRateJump((u, p, t) -> 1.0, + integrator -> (integrator.u[1] = 1.0; nothing)) + jprob = JumpProblem(oprob, Direct(), birth, reset; vr_aggregator) + + refs = map(seed -> path(solve(deepcopy(jprob), Tsit5(); seed)), (1, 2)) + @test interleaved_paths(jprob, isolated_copy(jprob), Tsit5(); nsteps = 3) == refs +end + +@testset "Concurrent solves" begin + for jprob in (ab_jprob(SortingDirect()), ab_jprob(NRM(); massaction = false)) + refs = [path(solve(deepcopy(jprob), SSAStepper(); seed)) for seed in 1:8] + tasks = [Threads.@spawn path(solve(isolated_copy(jprob), SSAStepper(); seed)) + for seed in 1:8] + @test fetch.(tasks) == refs + end +end + +@testset "Callbacks passed to the JumpProblem are copied" begin + birth = MassActionJump([[0 => 1]], [[1 => 1]]; param_idxs = [1]) + jprob = JumpProblem(DiscreteProblem([0], (0.0, 100.0), [1.0]), Direct(), birth; + callback = stop_after_jumps(5)) + + # A shared counter would stop both simulations early + (_, u1), (_, u2) = interleaved_paths(jprob, isolated_copy(jprob), SSAStepper(); + nsteps = 3) + @test u1[end] == u2[end] == [5] +end + +@testset "Copies don't depend on the original's memory" begin + # Function-wrapper aggregators store the rates in wrappers that call through pointers + function rate_seen_by_copy() + k = 2.0 + rate = (u, p, t) -> k + jprob = JumpProblem(DiscreteProblem([0], (0.0, 1.0)), DirectFW(), + ConstantRateJump(rate, integrator -> (integrator.u[1] += 1; nothing))) + isolated_copy(jprob) + end + copies = [rate_seen_by_copy() for _ in 1:20] + for _ in 1:5 + GC.gc(true) + junk = [fill(-1.0, 4) for _ in 1:10_000] + end + rate_at_start(jprob) = only(jprob.discrete_jump_aggregation.rates)(jprob.prob.u0, + jprob.prob.p, 0.0) + @test all(==(2.0) ∘ rate_at_start, copies) +end + +@testset "Spatial aggregators: $(nameof(typeof(aggregator)))" for aggregator in ( + NSM(), DirectCRDirect()) + + # A + B <--> C on a line of three sites + majumps = MassActionJump([0.5, 1.0], [[1 => 1, 2 => 1], [3 => 1]], + [[1 => -1, 2 => -1, 3 => 1], [1 => 1, 2 => 1, 3 => -1]]) + u0 = zeros(Int, 3, 3) + u0[:, 2] .= [20, 20, 0] + prob = DiscreteProblem(u0, (0.0, 2.0), [0.5, 1.0]) + jprob = JumpProblem(prob, aggregator, majumps; hopping_constants = fill(1.0, size(u0)), + spatial_system = CartesianGrid((3,))) + + refs = map(seed -> path(solve(deepcopy(jprob), SSAStepper(); seed)), (1, 2)) + @test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs +end + +@testset "PureLeaping" begin + maj = MassActionJump([[1 => 1], [2 => 1]], [[1 => -1, 2 => 1], [1 => 1, 2 => -1]]; + param_idxs = [1, 2]) + jprob = JumpProblem(DiscreteProblem([12, 8], (0.0, 5.0), [0.7, 0.4]), PureLeaping(), + maj) + jcopy = isolated_copy(jprob) + @test jcopy.prob === jprob.prob + @test path(solve(jcopy, SimpleExplicitTauLeaping(); seed = 1)) == + path(solve(deepcopy(jprob), SimpleExplicitTauLeaping(); seed = 1)) +end diff --git a/test/qa.jl b/test/qa.jl index e82eff0a3..a5eae1aad 100644 --- a/test/qa.jl +++ b/test/qa.jl @@ -28,8 +28,9 @@ run_qa( # Names not (yet) declared public in their owner package's released API. all_qualified_accesses_are_public = (; ignore = ( - # Base / Base.Broadcast / Base.FastMath internals - Symbol("@pure"), :BroadcastStyle, :Broadcasted, :Cartesian, + # Base / Base.Broadcast / Base.FastMath internals; `deepcopy_internal` is + # extended to customise `deepcopy`, as its docstring describes + Symbol("@pure"), :BroadcastStyle, :Broadcasted, :Cartesian, :deepcopy_internal, :DefaultArrayStyle, :FastMath, :Unknown, :result_style, :sqrt_fast, # SciMLBase non-public :ConstantInterpolation, :DISCRETE_INPLACE_DEFAULT, diff --git a/test/runtests.jl b/test/runtests.jl index a198d9fa3..81eb0113a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -52,6 +52,7 @@ end @time @safetestset "Stochastic dispatch tests" begin include("stochastic_dispatch.jl") end @time @safetestset "Jump-diffusion replay and jump state" begin include("jump_diffusion_state.jl") end @time @safetestset "Jump-state ownership and alias controls" begin include("jump_state_ownership.jl") end + @time @safetestset "isolated_copy" begin include("isolated_copy.jl") end @time @safetestset "Ensemble Uniqueness test" begin include("ensemble_uniqueness.jl") end @time @safetestset "Ensemble Problem Tests" begin include("ensemble_problems.jl") end @time @safetestset "A + B <--> C" begin include("reversible_binding.jl") end @@ -75,6 +76,7 @@ end if GROUP == "All" || GROUP == "ThreadSafety" @time @safetestset "Thread Safety test (threaded)" begin include("thread_safety.jl") end @time @safetestset "Jump-state ownership (threaded)" begin include("jump_state_ownership.jl") end + @time @safetestset "isolated_copy (threaded)" begin include("isolated_copy.jl") end end if GROUP == "CUDA"