Source code for discoeb.solver._kernel

"""
The modax GPU kernels of a model and their launches.

The equations themselves say which states evolve without the wave number
(:meth:`Equations.stages <discoeb.components._component.Equations.stages>`):
the conformal time, the recombination history, the optical depth and
whatever a model adds. Those are the *background*, solved once per
cosmology. The perturbations of every (wave mode, cosmology) pair read what
they need of it at every step the background takes: the two are the blocks
of one modax solve (:class:`modax.Block`). This module builds the two
systems, packs a batch into parameter rows and initial states, launches
them and compiles the save hooks that keep named quantities.
"""

import functools
import math
from dataclasses import dataclass
from typing import Callable, NamedTuple

import jax
import jax.numpy as jnp
import numpy as np

from ..components._component import Equations, _compile, parameter_values
from ..components.recombination import REIO_ERROR_WEIGHT, THERMO_ERROR_WEIGHT
from ..models._model import RECOMBINATION, Model, _model_of

A_START = 2.0e-7
"""The scale factor where every trajectory starts, deep in radiation
domination (``tau`` near 0.1 Mpc). The solve integrates in ``a`` from here
to 1, today."""

PERTURB_RTOL = 1.0e-4
PERTURB_ATOL = 1.0e-4
PERTURB_FIRST_STEP = A_START  # in a: 0.1 Mpc of conformal time
PERTURB_MAX_STEPS = 20000


@dataclass(frozen=True)
class ParameterLayout:
    """The columns of a model's parameter row, generated from its parameters.

    The row is ``(k, what the kernel reads of a cosmology)``: the wave
    number, which the solver sets, then the parameters and the quantities
    computed from parameters only that a method running in the kernel
    names in its signature (:meth:`Equations.frontier
    <discoeb.components._component.Equations.frontier>`). The host
    evaluates those quantities before the launch (``omega_g`` from
    ``T_cmb``). A parameter that only they or an observable read
    (``N_eff``, ``A_s``) stays on the host. The parameters come first, in
    component and declaration order, then the quantities in provider
    order, so the layout is a function of the resolved model and the
    kernels cached on it stay valid. A derivative may move any column:
    modax integrates a sensitivity column along the row's tangent
    (:func:`~discoeb.solver.solve_eb`).
    """

    columns: dict
    """Column by the name the providers read it under: ``omega_c``, ``k``."""
    values: tuple[tuple[str, int], ...]
    """``(name, column)`` of the parameters and quantities the row holds."""

    @property
    def n(self) -> int:
        return len(self.columns)


def parameter_layout(model: type[Model], extra=()) -> ParameterLayout:
    """Return the row layout of ``model`` with the component classes ``extra`` appended (cached)."""

    return _parameter_layout(_model_of(model).resolved(), tuple(extra))


@functools.lru_cache(maxsize=None)
def _parameter_layout(model: type[Model], extra) -> ParameterLayout:
    parameters = model.parameters(extra)
    if "k" in parameters:
        raise ValueError("'k' names the wave number's column, not a parameter")
    joint = joint_model(model, extra)
    provided = sorted({p.attr for p in joint._all_providers()} & set(parameters))
    if provided:
        raise ValueError(f"{provided} are parameters and methods of the model both")
    held = joint.frontier(parameters)
    columns = {name: i for i, name in enumerate(("k", *held))}
    return ParameterLayout(columns, tuple((n, columns[n]) for n in held))


BACKGROUND_NODES = 2048
"""The most nodes a cosmology's background publishes for its wave modes: its start, its steps and :data:`NODE_TIMES`.

Left to its error control the background takes about 210 steps, more when
differentiated. Each node holds the published quantities and their slopes,
and a wave mode reads the cubic Hermite between two. A cosmology that runs
out stops, and its wave modes with it."""

NODE_TIMES = 512
"""Scale factors, geometric from :data:`A_START` to 1, at which the background also publishes inside its steps.

Its steps follow the thermal states, and reionization, which only the
optical depth integrates, does not shorten them: across it a wave mode read
the opacity between nodes far apart, and EE at l = 18 came out 0.9 percent
from CLASS. Nodes 0.03 apart in ln a, from the background's continuous
extension, leave it 0.39 percent off (128 LCDM cosmologies, CLASS's modes),
and keep every gap below the 0.04 a wave mode needs to converge. 1024 gain
nothing and cost 8 ms of a batch of 128 spectra."""

FUSE_STAGES = True
"""Whether the perturbations take each stage's right-hand side straight into its rows (modax's ``fuse_stages``).

With every index of a stage a literal, the compiler keeps the stage vectors
in registers and lets ptxas spill what it must, in place of arrays in local
memory: at 128 cosmologies the LCDM P(k) ran 24.3 -> 18.1 ms, the spectra
192 -> 154 ms, the massive neutrinos' P(k) 248 -> 197 ms. Two launches
compiled differently then no longer integrate bit for bit alike, so a test
that compares them turns it off."""

MAX_SENSITIVITY_STATE = 330
"""The most components one thread integrates in a sensitivity launch: the
state and its sensitivity columns. The driver reserves every resident
thread's local memory, so this bounds the columns per thread, and modax
splits a derivative along more directions into groups of one width, each
in a thread of its own beside a copy of its trajectory. 330 is five
columns of the 55-state LCDM system, which fills 9 GB of a 12 GB card.
Seven exhaust it."""


[docs] def joint_model(model: type[Model], extra=()) -> Equations: """Return the components of ``model`` with the recombination code (:data:`~discoeb.models._model.RECOMBINATION`) appended. The recombination states come after the perturbations', so the perturbation state keeps the indices of :meth:`Model.state_names <discoeb.models.Model.state_names>`. The thermal states (the conformal time, the optical depth and RECFAST's ``x_H``, ``x_He`` and ``T_m``) are the last columns of every history, at ``model.index["tau"]`` and so on. ``extra`` lists component classes to append after them (the line-of-sight sources). The joint model integrates in the scale factor: its time is ``a`` and its clock ``a_prime = a'``, the rate of ``a`` in the conformal time the components write their rates in. Every cosmology then runs from :data:`A_START` to 1, and since ``a`` grows as ``tau`` in the radiation era, the early solutions are the low-order polynomials they are in ``tau``. """ return _joint_model(_model_of(model), tuple(extra))
@functools.lru_cache(maxsize=None) def _joint_model(cosmology_model: type[Model], extra) -> Equations: def build(last=()): return cosmology_model.build( extra=[RECOMBINATION(), *(cls() for cls in extra)], time="a", clock="a_prime", last=last, ) # modax lays the two blocks out one after the other, the perturbations # first. The recombination states are the last declared, but a # model's own background states (a scalar field's) are not: put every # background state last. Until 2026-11-17 they kept their place, so the # kernel evolved the field in the slots the hook read as its # perturbation, and the other way round. model = build() background = model.stages()[0] indices = model.state_indices(background) if indices != list(range(model.nvar - len(indices), model.nvar)): model = build(last=background) return model def density_parameters(param, model: type[Model], xp=jnp, extra=()) -> dict: """The parameters of ``model`` for a parameter dictionary, and what the model computes from them. The keys pass through, a missing one at its default. Every quantity that depends on parameters only (:meth:`Equations.hoisted <discoeb.components._component.Equations.hoisted>`) is evaluated by its method: ``omega_g`` and ``omega_ur`` the photons' and massless neutrinos' densities, ``omega_nu_flavour`` and ``amnu`` the massive neutrinos'. Pass ``xp=jnp`` for a traced cosmology and ``xp=np`` for one given as floats. """ parameters = model.parameters(extra) joint = joint_model(model, extra) values = parameter_values(parameters, param) names = joint.hoisted(parameters) module = math if xp is np else jnp computed = joint.evaluate(*names, math=module, **values) if names else () if len(names) == 1: computed = (computed,) return {**values, **dict(zip(names, computed))} def _restrict(pattern: np.ndarray, indices) -> np.ndarray: """Return the ``(nnz, 2)`` pattern's rows and columns ``indices``, renumbered.""" position = {idx: k for k, idx in enumerate(indices)} kept = [ (position[r], position[c]) for r, c in pattern.tolist() if r in position and c in position ] return np.array(sorted(kept), dtype=np.int64).reshape(-1, 2) def modax(): """Return the modax module, set to single precision.""" import modax as module if module.precision != "single": module.set_precision("single") return module class SplitKernels(NamedTuple): """The two systems modax integrates for a model, as the equations split them. The joint state holds the ``n`` perturbation states, then the background's (:func:`joint_model`). """ background: Callable """``rhs(y, a, p)`` of the background states.""" background_sparsity: np.ndarray outputs: Callable """``(y, a, p)`` of the background to ``u``, what the perturbations read of it at every step it takes: the published quantities, then the background states not among them (a save hook may name any). It is the background block's save hook.""" states: tuple[int, ...] """For every background state, in the joint model's order, its place in ``u``.""" output_names: tuple[str, ...] """The names of ``outputs``, in order: what :func:`solve_eb` takes from the background's own saves.""" perturbations: Callable """``rhs(y, a, p, u)`` of the perturbation states.""" n: int """The number of perturbation states.""" sparsity: np.ndarray def joint_kernel(model: type[Model], extra=()): """Return ``(joint model, kernels)`` of ``model``, cached per resolved model and ``extra``. The kernels are the two systems the equations themselves split into (:meth:`Equations.stages <discoeb.components._component.Equations.stages>`). The background holds every state whose rate reads no wave number: the conformal time, the recombination history, the optical depth, and whatever a model adds, such as a scalar field. The perturbations take as given the fewest quantities that separate them from it (:meth:`Equations.published <discoeb.components._component.Equations.published>`: the conformal time, the opacity and the baryon sound speed for the built-in models). One modax solve integrates the background per cosmology, which publishes those quantities at its own steps, and the perturbations per wave mode, which read them as inputs. So the perturbation Jacobian has no background columns, and the thermal providers run once per cosmology and step. The state keeps the joint model's order. """ return _joint_kernel(_model_of(model).resolved(), tuple(extra)) @functools.lru_cache(maxsize=None) def _joint_kernel(cosmology_model, extra): model = joint_model(cosmology_model, extra) columns = _parameter_layout(cosmology_model, extra).columns pattern = model.sparsity() background, others = model.stages() published = model.published() thermal = model.state_indices(background) hierarchy_idx = model.state_indices(others) # what the perturbations read: the published quantities, then the # background states not among them, by element name element = {index: name for name, index in model.index.items()} states = [element[i] for i in thermal] inputs = (*published, *(name for name in states if name not in published)) outputs = model.build_function( inputs, inputs=("y", "a"), params=columns, states=background, name="background_inputs", ) # its right-hand side reads the published quantities, the first of the inputs perturbations = model.build( columns, states=others, quantities=published, name="hierarchy_rhs", ) return model, SplitKernels( background=model.build(columns, states=background, name="recombination_rhs"), background_sparsity=_restrict(pattern, thermal), outputs=outputs, states=tuple(inputs.index(name) for name in states), output_names=tuple(inputs), perturbations=perturbations, n=len(hierarchy_idx), sparsity=_restrict(pattern, hierarchy_idx), ) class _PreparedSolve(NamedTuple): """A batch ready to launch: the joint model, its kernels, the rows and the initial state. The arrays are JAX arrays, traced under ``jit``. Rows go as ``row = k_idx * n_cosmo + cosmology_idx``, so consecutive rows share a wave mode, over the ascending ``k_sorted``. """ cosmologies: tuple cosmology_model: type[Model] model: Equations layout: ParameterLayout kernels: SplitKernels params: jax.Array # (n_k * n_cosmologies, layout.n) y0: jax.Array # (n_k * n_cosmologies, nvar) order: np.ndarray # the caller's wave modes, sorted k_sorted: np.ndarray def _prepare_solve( model: type[Model], cosmologies, k_values, extra=(), columns=None ) -> _PreparedSolve: """Return a batch packed for launch at ``k_values``: parameter rows and initial states. ``cosmologies`` are the batch's parameter dictionaries (:func:`~discoeb.models._model._batch_of`). Their values may be traced under ``jit``. ``k_values`` must be numbers: they set the launch's shape and order. ``columns`` are the cosmologies' :func:`_columns` if already at hand. Every cosmology must suit the model (:meth:`Model.validate <discoeb.models.Model.validate>`), checked when its values are numbers. The kernel compiles once per model, and :func:`_pack` once per model, wave-mode grid and batch size. The rows and the initial state carry the cosmologies' tangents, and :func:`~discoeb.solver.solve_eb` differentiates through both. """ resolved = _model_of(model).resolved() for cosmology in cosmologies: resolved.validate(cosmology) joint, kernels = joint_kernel(resolved, extra) k = np.asarray(k_values, dtype=np.float64).reshape(-1) order = np.argsort(k, kind="stable") k_sorted = k[order] if columns is None: columns = _columns(cosmologies, resolved) params, y0 = _pack(resolved, tuple(extra), tuple(k_sorted.tolist()), columns) return _PreparedSolve( cosmologies, resolved, joint, parameter_layout(resolved, extra), kernels, params, y0, order, k_sorted, ) @functools.partial(jax.jit, static_argnums=(0, 1, 2)) def _pack(model: type[Model], extra, k_sorted, columns): """Return ``(params, y0)`` of a batch's columns, on the device. The rows come from :func:`_rows` and the initial state from the joint model's initial conditions at :data:`A_START`, in ``jax.numpy``. Nothing is integrated: the conformal time there is a closed form, and a model's own background states start from their initial conditions. """ joint = joint_model(model, extra) layout = parameter_layout(model, extra) values = density_parameters(columns, model=model, extra=extra) n_cosmo = next(iter(columns.values())).shape[0] n_k = len(k_sorted) params = jnp.tile(_rows(layout, values, n_cosmo), (n_k, 1)) k = jnp.repeat(jnp.asarray(k_sorted, dtype=jnp.float64), n_cosmo) params = params.at[:, layout.columns["k"]].set(k) y0 = joint.initial_state( k, xp=jnp, a=A_START, **{name: jnp.tile(value, n_k) for name, value in values.items()}, ) return params, y0 def _columns(cosmologies, model: type[Model]) -> dict: """Return a batch's parameters as JAX columns ``(n_cosmologies,)`` by key. ``cosmologies`` are the batch's parameter dictionaries (:func:`~discoeb.models._model._batch_of`), their values numbers or JAX values, traced or not. A key of another model that a cosmology holds (:meth:`Model.from_dict <discoeb.models.Model.from_dict>`) is left out: the kernel never reads it. """ columns = {} for key in _model_of(model).parameter_keys(): values = [c[key] for c in cosmologies] if any(isinstance(v, jax.Array) for v in values): column = jnp.stack([jnp.asarray(v, dtype=jnp.float64) for v in values]) else: # one device array, not one per cosmology column = jnp.asarray(np.asarray(values, dtype=np.float64)) columns[key] = column return columns def _rows(layout: ParameterLayout, values, n_cosmo: int): """Return the cosmologies' parameter rows ``(n_cosmologies, layout.n)``, without the wave number. ``values`` are the model's parameters and the quantities computed from them (:func:`density_parameters`), each ``(n_cosmologies,)``. """ by_column = {column: values[name] for name, column in layout.values} return jnp.stack( [ jnp.broadcast_to( jnp.asarray(by_column.get(i, 0.0), jnp.float64), (n_cosmo,), ) for i in range(layout.n) ], axis=1, ) def _error_weights( joint: Equations, n: int, k_launch, weights=None, thermo_weight=THERMO_ERROR_WEIGHT ): """Return the solver's error weights of the joint state: ``(nvar,)`` for every trajectory, or ``(n_traj, nvar)``. ``weights`` is ``None``, an array ``(nvar,)`` or ``(n_traj, nvar)`` in launch order, or ``{state name: weight}``. A named weight is a number or a function of the trajectories' wave numbers ``k_launch`` (launch order) that returns one per trajectory, and unnamed states keep their declared weight (``State(error_weight=)``: one, and zero for the massive-neutrino bins ``psi``). The names are the state elements of the joint model, so a caller never needs the state's index order or the launch's trajectory order. An array may leave the background states out. ``thermo_weight`` then weights the background states, the joint state's last after its ``n`` perturbation states, and :data:`REIO_ERROR_WEIGHT` ``kappa_reio`` if the model has it. The optical depth gets the block's weight too, so its error counts against ``rtol |kappa|``. The block's steps then resolve its increments where ``kappa`` is of order one, through recombination and after, which is where ``exp(-kappa)`` reads them. Unweighted, it leaves the lensed TT 0.5 percent off CLASS at ``l = 1500``. """ index = joint.index named = isinstance(weights, dict) if named: unknown = [name for name in weights if name not in index] if unknown: raise KeyError( f"{unknown} are not states of the model: {joint.state[:6]} ..." ) # one row for every trajectory unless the caller weights them apart uniform = weights is None or (not named and np.ndim(weights) == 1) declared = joint.error_weights() out = declared if uniform else np.tile(declared, (len(k_launch), 1)) if named: k_launch = np.asarray(k_launch, dtype=np.float64) for name, weight in weights.items(): out[:, index[name]] = weight(k_launch) if callable(weight) else weight elif weights is not None: base = np.asarray(weights, dtype=np.float64) out[..., : base.shape[-1]] = base out[..., n:] = thermo_weight if "kappa_reio" in index: out[..., index["kappa_reio"]] = REIO_ERROR_WEIGHT return out def _launch( prepared, params, y0, t_span, *, rtol, atol, first_step, max_steps, error_weights=None, thermo_weight=THERMO_ERROR_WEIGHT, split_derivatives=False, save_hook=None, save_states=None, save_history=True, return_stats=False, background_history=False, ): """Solve the prepared batch: the background of every cosmology and the perturbations of every trajectory. One modax solve of two Rodas5P blocks. The first integrates the background states of each cosmology once (the rows go as ``k_idx * n_cosmo + cosmology_idx``, so the first ``n_cosmo`` hold every cosmology) and publishes the perturbations' inputs at each of its steps and at :data:`NODE_TIMES`. The second integrates the perturbations of every (wave mode, cosmology) pair as a ``(n_k, n_cosmo)`` ensemble, each reading its cosmology's background between those steps. modax runs the two in one launch. Every trajectory runs over the same span of the scale factor, ``t_span``. ``error_weights`` and ``thermo_weight`` weight the error norm (:func:`_error_weights`). Returns ``(background, perturbations)``, the two blocks' outputs. The background's are modax's, one per cosmology, at the two ends of ``t_span`` or, with ``background_history``, at every time of it. The perturbations' are a tuple in launch order: their history ``(n_traj, n_save, n)``, or the final state alone without ``save_history``, then the quantities of ``save_hook`` (a device function ``(y, a, p)`` of the joint state, :func:`build_keep_hook`) and the step counters with ``return_stats``. ``save_states``, the perturbation states the hook reads (:func:`_hook_reads`), lets a solve without history evaluate only those at a save. Differentiated, modax integrates the sensitivity columns in the same launches, with these settings, and the background's published nodes carry its derivatives to the perturbations. A cosmological parameter both read is one input, so reverse mode works too. A thread holds at most :data:`MAX_SENSITIVITY_STATE` components, so more directions run in groups, each in a thread of its own beside a copy of its trajectory. ``split_derivatives`` gives every direction such a thread. """ m = modax() kernels, model = prepared.kernels, prepared.model n = kernels.n # the perturbation states, then the background's method = m.Rodas5P( gains=m.PIDGains(pcoeff=0.3, icoeff=0.4), fuse_stages=FUSE_STAGES, ) n_traj = np.shape(y0)[0] n_k = len(prepared.k_sorted) n_cosmo = n_traj // n_k weights = _error_weights( model, n, np.repeat(prepared.k_sorted, n_cosmo), error_weights, thermo_weight ) y0, params, t_span = jnp.asarray(y0), jnp.asarray(params), jnp.asarray(t_span) columns = max(1, MAX_SENSITIVITY_STATE // n - 1) # One modax solve of two blocks: the background of every cosmology, which publishes the # perturbations' inputs at its steps and node times, and the perturbations of every # (wave mode, cosmology) pair, a (n_k, n_cosmo) ensemble whose rows read their cosmology's. The # highest wave modes, which take the most steps, launch first: the last blocks to start # are then the short ones, and the launch ends without a tail of long lanes. The row is # (k, the cosmology's columns). The wave number varies across the wave modes alone, # so the background, one per cosmology, holds none. rows = params.reshape(n_k, n_cosmo, -1) shared = (rows[::-1, :1, :1], rows[0, :, 1:]) def shaped(x): return x.reshape((n_k, n_cosmo) + x.shape[1:])[::-1] background = m.Block( kernels.background, # what it keeps is what the perturbations read save_hook=kernels.outputs, # the conformal time and the optical depth feed nothing back, so the Jacobian # takes three sweeps and not five sparsity=kernels.background_sparsity, # The recombination rates are a right-hand side of some 3500 instructions over # five states. Unrolled eight times, the step stalls on instruction fetches, and # at a few cosmologies the wave modes wait for it. method=m.Rodas5P( gains=m.PIDGains(pcoeff=0.3, icoeff=0.4), stage_loop=True, ), max_nodes=BACKGROUND_NODES, node_times=np.geomspace(A_START, 1.0, NODE_TIMES), # the wave modes read its nodes: its saves are only for a caller who asks save_ends=not background_history, ) if save_hook is not None: save_hook = _split_hook( save_hook, n, kernels.states, None if save_states is None else tuple(save_states), ) perturbations = m.Block( kernels.perturbations, reads=background, sparsity=kernels.sparsity, method=method, save_hook=save_hook, save_history=save_history, save_states=save_states, ) out_bg, out = m.solve( [background, perturbations], (y0[:n_cosmo, n:], shaped(y0[:, :n])), t_span, shared, error_weights=( (weights[n:], weights[:n]) if weights.ndim == 1 else (weights[:n_cosmo, n:], shaped(weights[:, :n])) ), rtol=rtol, atol=atol, first_step=first_step, max_steps=max_steps, return_stats=return_stats, sens_error_control=False, max_directions_per_thread=1 if split_derivatives else columns, cache=True, ) out = out if isinstance(out, tuple) else (out,) return out_bg, jax.tree.map(lambda x: x[::-1].reshape((n_traj,) + x.shape[2:]), out) @functools.lru_cache(maxsize=None) def _split_hook(hook, n: int, states: tuple[int, ...], reads=None): """Return ``hook(y, a, p)`` of the joint state as a hook ``(y, a, p, u)`` of the perturbations and their inputs. ``hook`` is a device function such as :func:`build_keep_hook` returns. The joint state is the ``n`` perturbation states followed by the background's, and ``u`` holds each background state at its place in ``states`` (:class:`SplitKernels`). With ``reads``, the perturbation states ``hook`` reads, the others are NaN, which ``hook`` never sees. """ from ..components._component import _device_names lines = [ "def perturbation_hook(y, a, p, u):", f" joint = cuda.local.array({n + len(states)}, float64)", *( f" joint[{i}] = y[{i}]" if reads is None or i in reads else f" joint[{i}] = math.nan" for i in range(n) ), *(f" joint[{n + i}] = u[{place}]" for i, place in enumerate(states)), " return quantities(joint, a, p)", ] return _compile( "perturbation_hook", "\n".join(lines) + "\n", {**_device_names(), "math": math, "quantities": hook}, ) @functools.lru_cache(maxsize=None) def _hook_reads(model: type[Model], extra, names, n: int): """The perturbation states the quantities ``names`` read, increasing, or ``None`` for none.""" reads = tuple(j for j in joint_model(model, extra).state_reads(names) if j < n) return reads or None def build_keep_hook(model, names, layout: ParameterLayout): """Return a modax save hook ``(y, a, p) -> tuple`` of the quantities ``names``, a device function. A name is a state element or a quantity the joint model provides. State elements (``delta_c``, ``F_2``, ``psi_0_1``: the :meth:`~discoeb.models.Model.state_names`, or ``tau``, ``thermo_0`` ... ``kappa`` of the recombination block) come straight from the state. Provided quantities (``R``, ``alpha``, ``phi`` with the line-of-sight sources appended, ``opacity`` or ``cs2`` from the thermal states) come from :meth:`~discoeb.components._component.Equations.build_function`, with the state, the time and the parameter row of ``layout`` as inputs. modax keeps what it returns at every save, and differentiates it like the history: a forward-sensitivity launch stores each quantity's derivative along every sensitivity column beside it, one Enzyme sweep of the hook per column. """ names = tuple(names) if not names: raise ValueError("keep at least one quantity") return model.build_function(names, inputs=("y", "a"), params=layout.columns) @functools.lru_cache(maxsize=None) def _keep_hook(model: type[Model], extra, names): """Return the compiled hook for a resolved model, extra components and names (cached).""" return build_keep_hook( joint_model(model, extra), names, _parameter_layout(model, extra) )