You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Jump problem violates immutable problem assumption #287
The integrators seem to inherit shared mutable state from the jump problem. This seems to violate the assumption that "Problem-related types in DifferentialEquations.jl are immutable." (https://docs.sciml.ai/DiffEqDocs/latest/basics/problem/). Here is a MWE of the issue:
using JumpProcesses
rate1(u,p,t) = p.λ
rate2(u,p,t) = p.λ
affect1!(integrator) = (integrator.u[1] +=1)
affect2!(integrator) = (integrator.u[1] +=2)
crj1 =ConstantRateJump(rate1, affect1!)
crj2 =ConstantRateJump(rate2, affect2!)
u₀ = [0]
p = (λ =2.0, )
tspan = (0.0, 10.0)
dprob =DiscreteProblem(u₀, tspan, p)
jprob =JumpProblem(dprob, Direct(), crj1, crj2)
# Integrators inherit shared mutable state from the jump problem.
integrator1 =init(jprob, SSAStepper())
integrator2 =init(jprob, SSAStepper())
integrator1.cb.condition === integrator2.cb.condition
# This causes the solve of one integrator to affect the other.solve!(integrator1)
println(integrator1.cb.condition.prev_jump)
# prints 1solve!(integrator2)
println(integrator2.cb.condition.prev_jump)
# prints 2 (depending on random luck)println(integrator1.cb.condition.prev_jump)
# also prints 2
Presumably this would lead to issues if one were to e.g. manually do multithreaded parallelism over many solve's with the same problem, which in my understanding should be a valid thing to do, even if an EnsembleProblem is preferred?
There's already #184, which looks related, but from the discussion there it didn't seem like this issue was a precise dup.
I think the immutable problem assumption docs were added long after JumpProblem, so it looks like it was forgotten that it does not hold here when those docs were written. But we should definitely get some internals-type docs here that make clear it doesn't hold for JumpProblem. At the end of the day, JumpProblem is a weird entity since it actually stores its simulation algorithm (i.e. aggregator), and the associated cache structure (which stores the rng too). I'm not sure any other problem type does this.
Regarding multithreading, are you experiencing a bug? @ChrisRackauckas had added some checks in SSAStepper's init to deepcopy the JumpProblem in the multi-threaded case. We intentionally don't deepcopy in the serial case as that can destroy performance when one is trying to sequentially run a bunch of simulations for sampling purposes (due to reallocating memory for the internal data structures of the aggregators).
If you have suggestions on an alternative approach please do let me know! It might be worth making a big breaking change if we can make this cleaner.
I encountered this issue because I was making my own aggregator where I tracked some stateful information within the aggregator and directly extracted integrator.cb.condition.{some state} after running solve! on the integrator. This became an issue when I did this for multiple integrators, because all the cb.conditions pointed to the result of the most recent run and additionally the state accumulated over all the runs together. So a bit of an obscure case, I suppose, and I solved it exactly by just deepcopy'ing the problem on creation of the integrator.
I don't like that we have different behavior in the multithreaded (where we also deepcopy) and the serial cases, but I'm not sure of how we should resolve this and still allow reuse of the cache structures from solve to solve within a thread.
I don't know how often this special feature of non-allocating repeated solves is used: perhaps it's quite a lot, in which case removing it would be a breaking change in practice.
Indeed Gaurav is correct here that we usually try to make sure any and all caches are in the init phase and not in the problem type, specifically to avoid any re-solve issues. We might not have made that clear enough on CommonSolve.jl's docs, but it is intended.
So it could be that it's totally expected to have to allocate the aggregator on init?
That would be fine. I think something we might need is a way to choose a new seed on an inited integrator: SDEs need this too so it's just a missing feature, but seemingly a bit more important for jump processes where the init would be a lot heavier than the solve in many cases.
Those docs seem clear enough, they just postdate when the design here was created by quite a bit. (JumpProcesses' design goes back to before I started working on the library in 2018...)
I'd think running many repeated solves in a loop to generate statistics is the most common JumpProcesses workflow. Isn't that what serial EnsembleProblems also do (i.e. they don't use the integrator interface)?
So we could make this change, but it seems like then JumpProcesses would have to have the docs updated to use the integrator interface for all workflows, as I'd think running just one simulation is an unusual case (we'd also need to explain that users should avoid serial EnsembleProblems for the same reason unless they are also changed to use the integrator interface).
Internally, we'd also have to defer construction and/or initialization of the constant rate jump DiscreteCallback till the call to init (since it wraps the caches).
Reviving this as it's a recurring issue for me when I try to simulate agent-based models. For problems built with ModelingToolkit or Catalyst, this is slow as it copies the problem's function, symbolic system and observed-function cache, which never change. Copying only the jump state is 50x faster in my experiments. In my case, where I want to simulate cell populations, this matters a lot, and I'd imagine this to be the case for EnsembleThreads as well.
I've described a similar issue with callbacks here. The solution could be a simple way to re-instantiate jump callbacks, which would be just an additional function and a non-breaking change... I can currently do this, but it's a delve into package internals I'd rather avoid.
The best I’ve been able to come up with for this is to make JumpProblem store a dynamic pool of aggregator mutable state caches. I had planned a switch to that as JP11 as a quick follow up to JP10, but honestly the process to get JP10 out, with all the needed SciML wide updates done and released, took so long I no longer had time to work on it (I.e. I needed to focus on work relevant for my own research).
The other alternative I see is building an integrator-based ensemble approach that uses reinit!. Then we could switch to that and remove aggregations from JumpProblem. That completely messes up the whole SciML design that changing parameters and initial conditions is via remaking problems though.
If you have a third approach you’ve worked out that is not breaking please do let me know.
One other thing to be aware of is the changes in SciML’s specialization policy. These can have significant performance and memory allocation impacts on non-SSAStepper jump problems. MTK has a fix for this that turns on full specialization for them, but if you are building them any other way you may be getting hit by that issue too.
This is a summary of what I had put together for the plan. If I can find the time, I can try to get this together over my winter break. I would need to coordinate with @ChrisRackauckas for a time period when he is around as it will likely require updates and releases from SciMLBase, StochasticDiffEq, and then MTK/Catalyst once JP11 is out.
The design. (1) Split JumpProblem into a fully immutable struct (wrapped problem, jump definitions, rate/affect functions, dependency graphs, maps) plus a JumpWorkspace type holding the mutable aggregation state and VR_Direct caches; the jump callback is built at init around a workspace rather than stored as jump_callback. (2) A WorkspacePool{W} (a Vector{W} of idle workspaces plus a ReentrantLock) is a field of each JumpProblem, not a global, so W stays concrete and the pool’s lifetime is tied to the problem. solve acquires, runs, releases; init acquires and never returns the workspace since the user owns the integrator (abandoned integrators just get GC’d). Pool size grows to the peak number of simultaneous solves. remake shares the pool when W is unchanged, which is safe because workspaces are re-initialized from the integrator’s u and p at init. Task-local storage was rejected because two live integrators in one task would collide. (3) Copying goes through a dedicated SciMLBase hook, not a deepcopy overload — your 2026-10-08 decision. SciMLBase would add something like isolated_copy(prob) defaulting to deepcopy, use it at the three ensemble sites, and optionally replace the hard-coded isa AbstractJumpProblem per-task check with a trait. JP11’s method shares the JP-built immutable structure, gives the copy a fresh empty pool, and still deep-copies user rate/affect closures. Plain deepcopy keeps working but duplicates idle workspaces and reads the free list without the lock, so docs would steer users to isolated_copy and declare deepcopy of an in-use problem unsupported. For distributed, three options are left open: serialize isolated_copy(prob), call the hook per task on workers, or customize serialization of the pool type only.
Looking at your other issue about callbacks, I think we could put a chunk of what I mention above in JP10 via adding the isolated_copy(::JumpProblem) function. That might be sufficient for your use case of multiple integrators (outside of the callback issues you are having).
I'll have a look at your proposals Sam! Would the workspace be something like an integrator cache? If I understand correctly, this is how ODE solvers do it for example. I'm not sure if that would need a pool vs. just a single mutable cache per remake.
For now, your quick fix might be a good idea, as it would be non-breaking - I can see if I can generate a suitable PR. Otherwise I could use this as a hotfix!
The workspace is like an integrator cache, but unlike for ODEs it would still live in the JumpProblem. However, it would live as part of a pool, for which new solves/integrators can request a workspace that they own during their lifetime. If there is one available they get it, if not a new one is created. So there is still mutable state within the JumpProblem, but there is a locking mechanism so it is assigned to exactly one integrator at a time, with an additional copy created when all of them are checked out and one is requested. For threaded use this should mean having just one JumpProblem is completely safe. This would be breaking, so has to wait for JP11.
The idea for isolated_copy, which sounds like what you want, is:
isolated_copy(jp::JumpProblem) -> JumpProblem
Returns a JumpProblem that can be solved concurrently with jp, and used for an integrator
alive at the same time as one of jp's, without sharing any state that a JumpProcesses solver
mutates.
Shared (===):jp.prob (so f, the symbolic system, the observed cache, u0, p, tspan), jp.aggregator, jp.constant_jumps, jp.variable_jumps, jp.regular_jump, jp.massaction_jump, jp.kwargs (stored callback and tstops); every user rate, affect
and bound function and their FunctionWrappers; the dependency maps; BracketData;
spatial systems and hopping constants.
Fresh:discrete_jump_aggregation (a new aggregator with copied working state) and jump_callback (a new CallbackSet around it, and for VR_Direct/VR_DirectFW a new event
cache). The two are rebuilt together, so the callback's condition, affect! and initialize are the new aggregator, as the constructor makes them.
Copied working state: the copy starts from jp's current working state, as deepcopy
would. Call it between solves, not during one. SortingDirect's learned search order
carries over.
Not isolated:p, u0 and the stored callbacks are shared, as remake shares them;
isolate parameters with remake(jp; p). Closures are shared, so mutable state captured by a
rate or affect is the user's responsibility, as for an ODEProblem's right-hand side.
Problems without jump state (PureLeaping, RegularJump-only, no aggregator and no
variable-rate callbacks): return a new JumpProblem sharing every field, so the result is
always a distinct object.
My only question is whether the restriction that it is for use between solves still works for you. Do you want to dynamically create integrators during a solve?
Activity
isaacsas commentedon Jan 27, 2023
I think the immutable problem assumption docs were added long after
JumpProblem, so it looks like it was forgotten that it does not hold here when those docs were written. But we should definitely get some internals-type docs here that make clear it doesn't hold forJumpProblem. At the end of the day,JumpProblemis a weird entity since it actually stores its simulation algorithm (i.e. aggregator), and the associated cache structure (which stores therngtoo). I'm not sure any other problem type does this.Regarding multithreading, are you experiencing a bug? @ChrisRackauckas had added some checks in
SSAStepper'sinittodeepcopytheJumpProblemin the multi-threaded case. We intentionally don'tdeepcopyin the serial case as that can destroy performance when one is trying to sequentially run a bunch of simulations for sampling purposes (due to reallocating memory for the internal data structures of the aggregators).If you have suggestions on an alternative approach please do let me know! It might be worth making a big breaking change if we can make this cleaner.
gaurav-arya commentedon Jan 27, 2023
I encountered this issue because I was making my own aggregator where I tracked some stateful information within the aggregator and directly extracted
integrator.cb.condition.{some state}after runningsolve!on the integrator. This became an issue when I did this for multiple integrators, because all the cb.conditions pointed to the result of the most recent run and additionally the state accumulated over all the runs together. So a bit of an obscure case, I suppose, and I solved it exactly by just deepcopy'ing the problem on creation of the integrator.isaacsas commentedon Jan 27, 2023
In the call to
inityou can also setalias_jump = false, seeJumpProcesses.jl/src/SSA_stepper.jl
Line 136 in eeede56
I don't like that we have different behavior in the multithreaded (where we also deepcopy) and the serial cases, but I'm not sure of how we should resolve this and still allow reuse of the cache structures from
solvetosolvewithin a thread.gaurav-arya commentedon Jan 27, 2023
Reading around, it seems is that it's expected behaviour in SciML for all the caches etc. to be created upon initialization of an integrator, and if one wanted to avoid this for repeated solves one should create an
integratorand repeatedlyreinitit (https://discourse.julialang.org/t/solving-same-diffeq-repeatedly-but-with-different-initial-conditions/49402/2, https://docs.sciml.ai/DiffEqDocs/stable/basics/integrator/#SciMLBase.reinit!). So it could be that it's totally expected to have to allocate the aggregator oninit? (And perhaps a higher effort change would be a redesign such that these caches are not at all part of the problem, but only created when the integrator is formed).I don't know how often this special feature of non-allocating repeated solves is used: perhaps it's quite a lot, in which case removing it would be a breaking change in practice.
ChrisRackauckas commentedon Feb 6, 2023
Indeed Gaurav is correct here that we usually try to make sure any and all caches are in the
initphase and not in the problem type, specifically to avoid any re-solve issues. We might not have made that clear enough on CommonSolve.jl's docs, but it is intended.https://docs.sciml.ai/CommonSolve/stable/
That would be fine. I think something we might need is a way to choose a new seed on an inited integrator: SDEs need this too so it's just a missing feature, but seemingly a bit more important for jump processes where the init would be a lot heavier than the solve in many cases.
isaacsas commentedon Feb 7, 2023
Those docs seem clear enough, they just postdate when the design here was created by quite a bit. (JumpProcesses' design goes back to before I started working on the library in 2018...)
I'd think running many repeated solves in a loop to generate statistics is the most common JumpProcesses workflow. Isn't that what serial
EnsembleProblems also do (i.e. they don't use the integrator interface)?So we could make this change, but it seems like then JumpProcesses would have to have the docs updated to use the integrator interface for all workflows, as I'd think running just one simulation is an unusual case (we'd also need to explain that users should avoid serial
EnsembleProblems for the same reason unless they are also changed to use the integrator interface).Internally, we'd also have to defer construction and/or initialization of the constant rate jump
DiscreteCallbacktill the call toinit(since it wraps the caches).kaandocal commentedon Nov 7, 2026
Reviving this as it's a recurring issue for me when I try to simulate agent-based models. For problems built with ModelingToolkit or Catalyst, this is slow as it copies the problem's function, symbolic system and observed-function cache, which never change. Copying only the jump state is 50x faster in my experiments. In my case, where I want to simulate cell populations, this matters a lot, and I'd imagine this to be the case for
EnsembleThreadsas well.I've described a similar issue with callbacks here. The solution could be a simple way to re-instantiate jump callbacks, which would be just an additional function and a non-breaking change... I can currently do this, but it's a delve into package internals I'd rather avoid.
isaacsas commentedon Nov 7, 2026
The best I’ve been able to come up with for this is to make JumpProblem store a dynamic pool of aggregator mutable state caches. I had planned a switch to that as JP11 as a quick follow up to JP10, but honestly the process to get JP10 out, with all the needed SciML wide updates done and released, took so long I no longer had time to work on it (I.e. I needed to focus on work relevant for my own research).
The other alternative I see is building an integrator-based ensemble approach that uses reinit!. Then we could switch to that and remove aggregations from JumpProblem. That completely messes up the whole SciML design that changing parameters and initial conditions is via remaking problems though.
If you have a third approach you’ve worked out that is not breaking please do let me know.
One other thing to be aware of is the changes in SciML’s specialization policy. These can have significant performance and memory allocation impacts on non-SSAStepper jump problems. MTK has a fix for this that turns on full specialization for them, but if you are building them any other way you may be getting hit by that issue too.
isaacsas commentedon Nov 7, 2026
This is a summary of what I had put together for the plan. If I can find the time, I can try to get this together over my winter break. I would need to coordinate with @ChrisRackauckas for a time period when he is around as it will likely require updates and releases from SciMLBase, StochasticDiffEq, and then MTK/Catalyst once JP11 is out.
The design. (1) Split JumpProblem into a fully immutable struct (wrapped problem, jump definitions, rate/affect functions, dependency graphs, maps) plus a JumpWorkspace type holding the mutable aggregation state and VR_Direct caches; the jump callback is built at init around a workspace rather than stored as jump_callback. (2) A WorkspacePool{W} (a Vector{W} of idle workspaces plus a ReentrantLock) is a field of each JumpProblem, not a global, so W stays concrete and the pool’s lifetime is tied to the problem. solve acquires, runs, releases; init acquires and never returns the workspace since the user owns the integrator (abandoned integrators just get GC’d). Pool size grows to the peak number of simultaneous solves. remake shares the pool when W is unchanged, which is safe because workspaces are re-initialized from the integrator’s u and p at init. Task-local storage was rejected because two live integrators in one task would collide. (3) Copying goes through a dedicated SciMLBase hook, not a deepcopy overload — your 2026-10-08 decision. SciMLBase would add something like isolated_copy(prob) defaulting to deepcopy, use it at the three ensemble sites, and optionally replace the hard-coded isa AbstractJumpProblem per-task check with a trait. JP11’s method shares the JP-built immutable structure, gives the copy a fresh empty pool, and still deep-copies user rate/affect closures. Plain deepcopy keeps working but duplicates idle workspaces and reads the free list without the lock, so docs would steer users to isolated_copy and declare deepcopy of an in-use problem unsupported. For distributed, three options are left open: serialize isolated_copy(prob), call the hook per task on workers, or customize serialization of the pool type only.
isaacsas commentedon Nov 7, 2026
Looking at your other issue about callbacks, I think we could put a chunk of what I mention above in JP10 via adding the
isolated_copy(::JumpProblem)function. That might be sufficient for your use case of multiple integrators (outside of the callback issues you are having).kaandocal commentedon Nov 7, 2026
I'll have a look at your proposals Sam! Would the workspace be something like an integrator cache? If I understand correctly, this is how ODE solvers do it for example. I'm not sure if that would need a pool vs. just a single mutable cache per remake.
For now, your quick fix might be a good idea, as it would be non-breaking - I can see if I can generate a suitable PR. Otherwise I could use this as a hotfix!
isaacsas commentedon Nov 7, 2026
The workspace is like an integrator cache, but unlike for ODEs it would still live in the JumpProblem. However, it would live as part of a pool, for which new solves/integrators can request a workspace that they own during their lifetime. If there is one available they get it, if not a new one is created. So there is still mutable state within the JumpProblem, but there is a locking mechanism so it is assigned to exactly one integrator at a time, with an additional copy created when all of them are checked out and one is requested. For threaded use this should mean having just one JumpProblem is completely safe. This would be breaking, so has to wait for JP11.
The idea for
isolated_copy, which sounds like what you want, is:Returns a
JumpProblemthat can be solved concurrently withjp, and used for an integratoralive at the same time as one of
jp's, without sharing any state that a JumpProcesses solvermutates.
===):jp.prob(sof, the symbolic system, the observed cache,u0,p,tspan),jp.aggregator,jp.constant_jumps,jp.variable_jumps,jp.regular_jump,jp.massaction_jump,jp.kwargs(storedcallbackandtstops); every user rate, affectand bound function and their
FunctionWrappers; the dependency maps;BracketData;spatial systems and hopping constants.
discrete_jump_aggregation(a new aggregator with copied working state) andjump_callback(a newCallbackSetaround it, and for VR_Direct/VR_DirectFW a new eventcache). The two are rebuilt together, so the callback's
condition,affect!andinitializeare the new aggregator, as the constructor makes them.jp's current working state, asdeepcopywould. Call it between solves, not during one.
SortingDirect's learned search ordercarries over.
p,u0and the stored callbacks are shared, asremakeshares them;isolate parameters with
remake(jp; p). Closures are shared, so mutable state captured by arate or affect is the user's responsibility, as for an
ODEProblem's right-hand side.PureLeaping,RegularJump-only, no aggregator and novariable-rate callbacks): return a new
JumpProblemsharing every field, so the result isalways a distinct object.
My only question is whether the restriction that it is for use between solves still works for you. Do you want to dynamically create integrators during a solve?
isaacsas commentedon Nov 7, 2026
Actually, I think copying if you are manually stepping an integrator is probably fine with this design (as long as it is done between steps).