solve#
modax.solve is the primary function modax exposes. It integrates an ensemble of
trajectories of one right-hand side function, using the specified method, method=:
Tsit5, Rodas5P (the default) or
Auto, which switches between them. Each method carries its own
options (see Methods). Importing modax enables JAX float64 by default, and the solvers compute in
double precision unless modax.set_precision() is called to override it to single precision.
- modax.solve(ode_fn: OdeFn, y0: ArrayLike, t_span: ArrayLike, params: Params, *, method: Method | None = None, rtol: float = 1e-08, atol: float = 1e-10, first_step: float | None = None, max_steps: int = 100000, error_weights: ArrayLike | None = None, return_stats: bool = False, sparsity: Sparsity | None = None, sens_error_control: bool = True, max_directions_per_thread: int | None = None, save_hook: SaveHook | None = None, save_history: bool = True, trajectories_per_block: int | None = None, max_registers: int | None = None, cache: bool = False) SolveOutput | HookedOutput[source]#
Integrate an ensemble of ODE trajectories.
methodpicks the stepper:Rodas5P(the default),Tsit5, orAuto, which switches between them. The method object holds its own numerical options, and the arguments here cover the problem and the launch.A list of
Blockin place ofode_fnsolves a graph of systems together, each reading the outputs of the blocks it names: a background that many trajectories share, integrated once per distinct background, and the perturbations that read it. A block’s outputs are its save hook’s quantities, or its state without a hook. It publishes them at every step it accepts, and its readers’ callbacks take them attas a fourth argument.y0anderror_weightsthen hold one entry per block,paramsis shared, and the solve returns a tuple of what each block alone would return. The method, sparsity, save hook and history flag belong to each block.The solve is
jit-traceable, and an outerjax.vmapbecomes one larger ensemble launch.jax.jvpandjax.jacfwddifferentiate it with respect toy0andparamsby integrating the forward-sensitivity system with the state, one column along each tangent:jax.jvpcosts one column whatever the number of parameters, andjax.jacfwdone column per direction. Reverse mode (jax.grad,jax.vjpand the rest) integrates a column per moving input, asjax.jacfwddoes, and transposes the resulting Jacobian: it costs what forward mode costs, andjitmust sit outside it. A trajectory and its directions share one thread, unlessmax_directions_per_threadspreads them over replicas. Derivatives pass through blocks in both modes, a parameter both blocks read counting once.- Parameters:
ode_fn – The right-hand side
(y, t, p) -> tupleof scalars. A plain function iscuda.jit-ed for you. See Writing ODE callbacks. Or a list ofBlock, each reading the blocks it names.y0 – Initial state,
(n_vars,)or(*batch, n_vars). Every trajectory shares a 1-D state. With blocks, a tuple of one per block.t_span – Save times,
(n_save,)shared by the ensemble or(*batch, n_save)with one increasing row per trajectory. A row’s first entry is where that trajectory starts and its last where it stops, so trajectories can start and end at times of their own. Not differentiable.params – Parameters: an array,
(n_params,)or(*batch, n_params), or a pytree of them (a tuple, a dict) whose leaves are(),(k,)or(*batch, k)and concatenate, injax.tree.leavesorder, into the rowode_fnsees. The ensemble’s batch shape is the broadcast of the batch shapes ofy0,paramsandt_span, so an ensemble may be(N,)or any shape, and a 1-D input is shared by all of it.rtol – Relative tolerance of the weighted RMS error norm.
atol – Absolute tolerance of the weighted RMS error norm.
first_step – The first step size.
None(or a non-positive value) starts each trajectory from1e-6of its own integration window.max_steps – Attempted steps a trajectory may take before it stops. Save times it did not reach hold its final state.
error_weights – Per-component weights of the error norm,
(n_vars,)or(N, n_vars). A zero takes a component out of step-size control. With blocks, a tuple of one per block.return_stats – Also return a dict of per-trajectory step counters,
accepted_steps,rejected_stepsandloop_steps, each(N,).sparsity – The Jacobian’s pattern: an
(n_vars, n_vars)mask, a scipy sparse matrix, or an(nnz, 2)array of(row, col)pairs. It must cover every structural nonzero. Rodas5P colours the Jacobian’s columns (one AD sweep per colour, not per column) and compiles a sparse direct LU for the pattern. Tsit5 forms no Jacobian and ignores it.sens_error_control – Hold the sensitivities to the tolerance too, when differentiated.
Falsetakes them out of step-size control, so the joint solve takes the plain solve’s steps.max_directions_per_thread – The most directions one thread integrates when the solve is differentiated.
Noneputs every direction in its trajectory’s thread. An integer splits the directions into groups of at most that many, each in a thread of its own beside a copy of the trajectory, so a small ensemble’s directions run side by side. Every copy repeats the primal.save_hook – A function
(y, t, p) -> tupleof quantities to keep at every save time, shaped likeode_fnand compiled the same way. The solve returns(history, quantities), the quantities(N, n_save, n_out)withn_outthe length of the tuple the hook returns. They are differentiable like the history.save_history –
Falsekeeps only the final state, for a hook that consumes the saves itself.trajectories_per_block – Trajectories per CUDA block, one per thread.
Nonemeans a warp, since trajectories step adaptively and divergence within a warp costs nothing.max_registers – A cap on the kernel’s registers per thread.
cache – Keep the compiled kernel on disk, keyed by everything that built it, so a later process loads it.
- Returns:
The integration history,
(*batch, n_save, n_vars), withbatchthe ensemble’s shape,(N,)for 2-D inputs. Withreturn_stats,(history, stats). With a save hook,(history, quantities)or(history, quantities, stats). With blocks, a tuple of that per block.- Raises:
TypeError – If
methodis not a Rodas5P, Tsit5 or Auto, or asave_hookdoes not return a tuple of numbers.ValueError – If
t_span’s rows disagree with the ensemble,save_history=Falsecomes without a hook,max_directions_per_threadis below 1, or the batch shapes ofy0,paramsandt_spando not broadcast.
Every problem size and set of options compiles a kernel of its own, cached for the life of the process. A process that sweeps problem sizes can drop them.
- modax.clear_caches() None[source]#
Drop the compiled kernels and the derivative helpers this process holds.
Every problem size and option set compiles a kernel of its own, and the caches keep it alive for the life of the process, so call this when sweeping problem sizes in one process.
Step control#
- class modax.PIDGains(pcoeff: float = 0.0, icoeff: float = 1.0, dcoeff: float = 0.0)[source]#
Bases:
objectGains of the proportional-integral-derivative step controller.
The default
(0, 1, 0)is the elementary integral controller. Non-zero proportional and derivative gains smooth the step-size sequence and cut rejected steps on stiff and mildly oscillatory problems. That narrows the spread of step counts across an ensemble, and so the divergence between threads of a warp.- exponents(order: int) tuple[float, float, float][source]#
(e1, e2, e3)of Soderlind’s controller for an error oforder.h_next = h * 0.9 * err^e1 * err_prev^e2 * err_prev2^e3, withe1 = -(k_I + k_P + k_D) / q,e2 = (k_P + 2 k_D) / qande3 = -k_D / q. The defaults givee1 = -1 / qande2 = e3 = 0, which is exactly the elementary controller.
Composing solves#
One-way coupled ODEs can be solved together as a graph of systems, with each block’s callbacks taking the outputs of input blocks as a fourth argument. See Composing solves.
- class modax.Block(rhs: OdeFn, reads: Block | Sequence[Block] = (), method: Method | None = None, sparsity: Sparsity | None = None, save_hook: SaveHook | None = None, save_history: bool = True, max_nodes: int = 2048, node_times: ArrayLike | None = None, save_ends: bool = False, save_states: Sequence[int] | None = None)[source]#
Bases:
objectOne system of a
modax.solve()over several, with its own options.- Parameters:
rhs – The right-hand side,
(y, t, p) -> tuple, or(y, t, p, u)for a block that reads others,uthe tuple of their outputs att, the first block’s and then the next’s.reads – The blocks whose outputs this one reads, a block or a sequence of them, each in the same solve. A block’s outputs are its save hook’s quantities, or its state without a hook.
sparsity – The block’s Jacobian pattern, as
modax.solve()takes it.save_hook – Quantities to keep at the save times, as
modax.solve()takes them,(y, t, p, u)in a block that reads others. They are also what the block’s readers read.save_history –
Falsekeeps the final state alone.max_nodes – The most nodes a trajectory of the block publishes for its readers: its start, its accepted steps and its
node_times. A trajectory that runs out stops, and its readers with it, their remaining saves not numbers.node_times – Times, increasing and known when the solve is traced, at which the block also publishes nodes inside its steps, from its continuous extension: values and slopes, with no right-hand side to evaluate. A reader then sees the outputs at least this densely, wherever the block’s own steps are longer.
Nonepublishes at the steps alone.save_ends – Save at the first and last of the solve’s times alone, for a block whose readers take all they need from its nodes: its history and hook values are then at those two times.
save_states – The states
save_hookreads, when it reads only some. A Rodas5P block withsave_history=Falseand no sensitivities then evaluates only these at a save, and the hook sees NaN in the others.Noneevaluates every state.
- modax.by_forward_mode(fn: Callable[[...], Any], *, independent_rows: bool = False) Callable[[...], Any][source]#
Wrap
fnso that reverse mode differentiates it infn’s own arguments, by forward sensitivities.fntakes arrays and returns one array: typically a model whose few parameters set the inputs of amodax.solve()(initial states, parameter rows) and whose output comes from the solve.What it does. Forward mode (
jax.jvp,jax.jacfwd) passes through unchanged. Under reverse mode (jax.grad,jax.vjp,jax.jacrev) the wrapper integrates a forward-sensitivity column per element of the arguments that move, hands JAX the product of that Jacobian with the tangent, and JAX transposes the product. An argument that does not move takes no column.Why it helps. Without it, reverse mode reaches the solve with tangents whose dependence on the parameters JAX does not show it, so modax seeds a unit column per raw input of the solve, every initial state and every column of the parameter rows, and transposes those. That costs a column per raw input where a handful of parameters move, and unit columns lie outside the error control: where they are large and the physical combination small, their integration error survives the cancellation. On DISCO-EB the derivative in
T_cmbcame out 12 percent offjax.jacfwdatrtol=1e-4in single precision. The wrapper differentiates in the parameters instead, a column for each, along a physical direction.independent_rows. Set it when row
rof the output depends on rowrof every argument alone, as in a batch of independent problems, with the rows on the first axis of every argument and of the output. Each column is then seeded with the same element in every row, so one column per element of a row gives every row’s derivative, wherejax.jacfwdwould take a column per element of every row. DISCO-EB’ssolve_ebuses it, one row per cosmology: a gradient of two cosmologies’ CMB spectra in four parameters took 0.68 s, against 6.4 s through the unit columns, and eight cosmologies, which ran out of memory before, 0.92 s.When to use it. Wrap the function of the parameters whenever a gradient, a VJP or
jax.jacrevpasses through a solve whose inputs come from fewer parameters than the solve has inputs, or whose gradient must agree withjax.jacfwd. It changes nothing in forward mode.jitmust sit outside the reverse-mode transform:jax.jit(jax.grad(f)), notjax.grad(jax.jit(f)).
Precision#
- modax.set_precision(precision: str) None[source]#
Choose the precision of every solve in this process:
"double"(the default) or"single".Call it before the first solve. In single precision
y0,params, the save times and every output are float32, the kernel compiler types real constants and integers meeting reals as float32, in user callbacks too, a float32 division is within 2 ulp instead of exact, and denormals flush to zero.- Raises:
ValueError –
precisionis neither name.RuntimeError – A kernel was already built in the other precision.
- modax.precision: str#
The precision in force,
"double"or"single". It reads the setting each time, so it followsmodax.set_precision().