Skip to content

scirex.experimental

Code in scirex.experimental has no stability guarantee. Any name here can change its signature or behaviour, move, or disappear in any release, including a patch release, without a deprecation period and without a CHANGELOG entry under Deprecated. Notable changes are listed in the CHANGELOG on a best-effort basis.

Use it if you accept that. Pin the exact ScireX version when you do, and expect to adapt on upgrade. Code moves out of scirex.experimental into a stable package once its interface has settled; the move is announced in the CHANGELOG.

Everything is imported from its module, for example from scirex.experimental.giwo import GIWO. There is no package-level export list.

What lives here

Module What it provides Status
scirex.experimental.giwo GIWO, a geometry-informed wavelet neural operator (GINO's outer graph layers around a WNO latent operator) Not a published architecture; the interface is not settled. get_model_jax builds it under the name "giwo".
scirex.experimental.patching MultigridPatching2D, make_patches, MGPatchingDataProcessor: multigrid domain decomposition for high-resolution inputs 2D only; the interface is not settled
scirex.experimental.distributed Model-parallel communication, tensor splitting and gather helpers (comm, helpers, mappings) Ported from a PyTorch implementation; the model-parallel interface is not settled
scirex.experimental.losses PDEResidualLoss and the AdvectionTerm, DivergenceTerm, GradientTerm, ReactionTerm, TransientTerm terms; NavierStokesEqnLoss; T3Galerkin, T6Galerkin; FourierDiff; the automatic-differentiation residuals (ADDiff, *TermAD) Not used by the released benchmarks; the interface is not settled
scirex.experimental.training Trainer, SimpleDataLoader, save_training_state, load_training_state: a generic training loop for any object with the train_step / __call__ contract Only the Car-CFD benchmark uses it; the other benchmarks have their own loops. The interface is not settled
scirex.experimental.tuning tune, suggest_params, TrialContext: Optuna hyperparameter tuning tracked in MLflow Needs the hpo extra (pip install "scirex[hpo]"); the interface is not settled
scirex.experimental.distributed.config DistributedConfig, the multi-GPU / model-parallel config class Used by the Car-CFD experiment config; not part of scirex.config
scirex.experimental.geometry Mesh I/O (mesh_io) and Gmsh mesh generation (gmsh_mesh) for the Galerkin losses Needs optional packages (meshio, gmsh); the interface is not settled
scirex.experimental.analysis spectrum_2d, compute_rank, compute_stable_rank, compute_explained_variance Research helpers; their semantics may change

GIWO

GIWO

Bases: BaseModel

GNO-in -> WNO (latent) -> GNO-out -> projection.

Args:

Name Type Description
in_channels int

Feature dimension of the input/output point-cloud functions.

out_channels int

Feature dimension of the input/output point-cloud functions.

gno_coord_dim int

Geometric dimension of input/output queries. Default: 3

in_gno_radius float

Neighbor-search radius for the input/output GNO. Same role as GINO's own fields of the same name -- a neighbor-search cutoff, not a model weight, so it does not move the parameter count.

out_gno_radius float

Neighbor-search radius for the input/output GNO. Same role as GINO's own fields of the same name -- a neighbor-search cutoff, not a model weight, so it does not move the parameter count.

in_gno_transform_type str

Unlike GINO (whose separate lifting ChannelMLP can bridge a channel-count mismatch between the input GNO's output and the latent operator's width), GIWO feeds the input GNO's output straight into the WNO with no lifting layer in between -- so every mode except "nonlinear_kernelonly" (the default) requires in_channels == wno_hidden_channels, since IntegralTransform multiplies the kernel output by f_y elementwise in those modes.

wno_size tuple[int, ...]

Spatial shape of the fixed latent grid (e.g. (10, 10, 10)), passed straight through to WNO's own size.

wno_hidden_channels see `WNO`

Sized the same empirical way GINO's fno_hidden_channels is: by direct parameter-count measurement against a budget, not a closed-form formula (see scripts/benchmarks/shapenetcar/_config.py).

wno_n_layers see `WNO`

Sized the same empirical way GINO's fno_hidden_channels is: by direct parameter-count measurement against a budget, not a closed-form formula (see scripts/benchmarks/shapenetcar/_config.py).

wno_level see `WNO`

Sized the same empirical way GINO's fno_hidden_channels is: by direct parameter-count measurement against a budget, not a closed-form formula (see scripts/benchmarks/shapenetcar/_config.py).

wno_wavelet see `WNO`

Sized the same empirical way GINO's fno_hidden_channels is: by direct parameter-count measurement against a budget, not a closed-form formula (see scripts/benchmarks/shapenetcar/_config.py).

latent_embedding

latent_embedding(in_p: Any) -> Any

Run the latent WNO. in_p: (batch, n_1, ..., n_k, wno_hidden_channels).

encode

encode(
    input_geom: Any,
    latent_queries: Any,
    x: Any = None,
    neighbors_in: dict | None = None,
) -> tuple[Any, Any]

Input GNO -> WNO: input mesh -> latent-grid embedding.

Same contract as encode (split out for the same reason: a caller can reuse one encode across several decode calls), minus the latent_features/ ada_in options GINO exposes, which nothing in this repo uses for GIWO yet.

decode

decode(
    latent_embed: Any,
    latent_queries: Any,
    output_queries: Any,
    neighbors_out: dict | None = None,
) -> Any

Output GNO + projection: latent-grid embedding -> output queries.

Same contract as decode.

Patching

MGPatchingDataProcessor

MGPatchingDataProcessor(
    model: Module,
    levels: int,
    padding_fraction: float,
    stitching: bool,
    device: str = "cpu",
    use_distributed: bool = False,
    in_normalizer: Any | None = None,
    out_normalizer: Any | None = None,
)

Bases: DataProcessor

Data processor that applies multigrid patching to the inputs of a model.

The input is cut into overlapping patches before the forward pass and, with stitching, the patch outputs are joined back into one field afterwards. An optional normalizer encodes the inputs and decodes the outputs.

MGPatchingDataProcessor Applies multigrid patching to inputs out-of-place with an optional output encoder/other data transform

Args:

Name Type Description Default
model Module

model to wrap in MultigridPatching2D

levels int

number of multi-grid patching levels to use

padding_fraction float

fraction by which to pad inputs in multigrid-patching

stitching bool

whether to stitch back the output from the multi-grid patches

in_normalizer Transform

OutputEncoder to decode model inputs, by default None

None
in_normalizer Transform

OutputEncoder to decode model outputs, by default None

None
device str

device 'cuda' or 'cpu' where computations are performed

'cpu'

preprocess

preprocess(data_dict: dict, batched: bool = True) -> dict

Preprocess data assuming that if encoder exists, it has encoded all data during data loading

Args:

Name Type Description Default
data_dict dict

dictionary keyed with 'x', 'y' etc represents one batch of data input to a model

batched bool

whether the first dimension of 'x', 'y' represents batching

True

postprocess

postprocess(
    out: ndarray, data_dict: dict, training: bool = True
) -> tuple[jnp.ndarray, dict]

Postprocess model outputs.

Args:

Name Type Description Default
data_dict dict

dictionary keyed with 'x', 'y' etc represents one batch of data input to a model

out ndarray

model output predictions

training bool

whether in training mode, by default True

True

MultigridPatching2D

Bases: Module

MultigridPatching2D wraps a model in multi-grid domain decomposition and patching.

Args:

Name Type Description
model Module

model to wrap

levels int

number of levels of patching to use, by default 0

padding_fraction float

fraction of input size to add as padding around patches, by default 0

use_distributed bool

whether patching is performed in distributed mode, by default False

stitching bool

whether patches are to be stitched back together in spatial dimensions during training, by default True. Stitching is always performed during evaluation.

patch

patch(
    x: ndarray, y: ndarray
) -> tuple[jnp.ndarray, jnp.ndarray]

use multi-grid domain decomposition to split x and y into patches. If in a distributed scheme, scatters patches across processes.

Args:

Name Type Description
x ndarray

model input function

y ndarray

model output function

unpatch

unpatch(
    x: ndarray, y: ndarray, evaluation: bool = False
) -> tuple[jnp.ndarray, jnp.ndarray]

unpatch tensors created by self.patch. Stitch patches together if in evaluation mode, or if stitching is applied.

Args:

Name Type Description Default
x ndarray

tensor with patching structure created patching input x. May be either inputs x or raw model outputs (same shape/patching structure) Shape (b * n^2, c, h / n + 2 * pad_h, w / n + 2 * pad_w)

y ndarray

tensor of patched ground-truth y. Shape (b * n^2, c, h / n, w / n) or (b, c, h, w) when not stitched

evaluation bool

whether in evaluation mode, by default False. If True, x and y are both evaluated after stitching, regardless of other settings.

False

make_patches

make_patches(
    x: ndarray, n: int | list[int], p: int | list[int] = 0
) -> jnp.ndarray

make_patches splits x into n equally-sized patches with padding fraction p. Stacks patches along the batch dimension.

Starting with an input tensor of shape (batch, C, s) or (batch, C, h, w), returns a corresponding patched output tensor of shape (n * batch, C, s / n + 2p) or (n1 * n2 * batch, C, h / n1 + 2 * p1, w / n2 + 2 * p2)

Args:

Name Type Description Default
x ndarray

input tensor, before patching

n int or list

number of patches into which to split each example in x

p int or list

number of pixels to use when padding x, by default 0

0

Tuning

import scirex.experimental.tuning always works. Using a name without the hpo extra raises an ImportError that names the extra.

tune

tune(
    build_model: BuildModel,
    train_fn: TrainFn,
    search_space: SearchSpace,
    *,
    n_trials: int | None = 50,
    timeout: float | None = None,
    direction: str = "minimize",
    metric_name: str = "val_loss",
    max_resource: int | None = None,
    min_resource: int = 1,
    reduction_factor: int = 3,
    pruner: BasePruner | None = None,
    sampler: BaseSampler | None = None,
    experiment_name: str = "hpo",
    tracking_uri: str | None = None,
    artifact_location: str | None = None,
    study_name: str | None = None,
    storage: str | None = None,
    seed: int | None = None,
    catch: Sequence[type[Exception]] = (),
    run_tags: Mapping[str, Any] | None = None,
    enabled: bool = True,
    default_params: Mapping[str, Any] | None = None,
) -> optuna.Study

Run an Optuna study over train_fn and record everything in MLflow.

max_resource is the most steps (usually epochs) a trial may run; it sets Hyperband's budget. storage (e.g. "sqlite:///optuna.db") makes the study resumable: calling tune again with the same study_name adds trials to it. Returns the optuna.Study.

With enabled=False there is no search: train_fn runs once, with no pruning, on default_params (every tunable key in search_space must be given; constants pass through). It logs one plain MLflow run and returns a one-trial in-memory study, so study.best_params / best_value still work. The HPO-only arguments (pruner, sampler, storage, ...) are ignored.

suggest_params

suggest_params(
    trial: Trial | FixedTrial, search_space: SearchSpace
) -> dict[str, Any]

Turn a search-space spec into concrete params for one trial.

Dict spec: each value is either a constant (passed through unchanged) or a dict with a type of float, int or categorical::

{
    "lr":         {"type": "float", "low": 1e-4, "high": 1e-1, "log": True},
    "hidden":     {"type": "int", "low": 16, "high": 256, "log": True},
    "optimizer":  {"type": "categorical", "choices": ["adam", "sgd"]},
    "epochs":     30,
}

For conditional spaces, pass a callable (trial) -> dict instead.

TrialContext

TrialContext(
    trial: Trial | FixedTrial,
    metric_name: str,
    max_resource: int | None,
)

The handle a training function uses to talk to the tuner.

The only required call is report, once per epoch/step.

number property

number: int

Index of this trial within its Optuna study.

report

report(
    value: float, step: int, **extra_metrics: float
) -> None

Record the objective at step.

Raises optuna.TrialPruned if the pruner decides this trial should stop, or if value is not finite. Let that exception propagate.

log_metrics

log_metrics(
    metrics: Mapping[str, float], step: int | None = None
) -> None

Log extra metrics to this trial's MLflow run (the pruner is not told).

Args:

Name Type Description Default
metrics mapping of str to float

Metric names and values.

step int

Step to attach the values to.

None

log_params

log_params(params: Mapping[str, Any]) -> None

Log additional parameters to this trial's MLflow run.

set_tag

set_tag(key: str, value: Any) -> None

Set a tag on this trial's MLflow run.

log_artifact

log_artifact(
    local_path: str | Path, artifact_path: str | None = None
) -> None

Upload a local file to this trial's MLflow run.

Args:

Name Type Description Default
local_path str or Path

File to upload.

artifact_path str

Sub-directory of the run's artifact store to put it in.

None

Distributed configuration

DistributedConfig

Bases: ConfigBase

DistributedConfig provides config options for multi-GPU and multi-node settings. Our current setup depends on torchrun-based Elastic Launch and the nccl distributed backend for communication.

Args:

Name Type Description
use_distributed

Whether to use distributed data/model parallelism

model_parallel_size

number of GPUs across which to spread model layers, by default 1. If 1, does not perform any model parallelism.

seed

special distributed random torch seed for reproducibility.

Experimental losses

PDEResidualLoss

PDEResidualLoss(
    terms: dict[str, tuple[float, Term]],
    reduction: str = "mean",
    name: str = "PDEResidualLoss",
)

A PDE residual assembled as a signed sum of reusable term primitives.

Rather than each PDE loss re-deriving its own flux/derivative logic, pde_terms provides a handful of reusable term kinds (diffusion, advection, transient, reaction, source); a specific PDE loss (e.g. DarcyEqnLoss) is just a particular signed combination of them -- terms that are absent for a given PDE are simply not included, rather than computed and zeroed out.

Args:

Name Type Description Default
terms dict[str, tuple[float, Term]]

name -> (sign, term) for each active term, must be non-empty. The residual is sum(sign * term(ctx) for sign, term in terms.values()).

reduction str

whether to reduce the squared residual across all remaining axes by summing ("sum") or averaging ("mean"), by default "mean"

'mean'
name str

human-readable identifier, by default "PDEResidualLoss"

'PDEResidualLoss'

name property

name: str

str: Human-readable identifier.

residual

residual(ctx: Context) -> jnp.ndarray

Pointwise residual: the signed sum of every active term.

A genuine Python float/int term (e.g. a constant SourceTerm) is allowed to broadcast against an array-valued term -- that's intentional. But two array-valued terms with different shapes -- including a term collapsed all the way down to a 0-d array -- broadcasting against each other almost always means one term's output is the wrong shape (e.g. a missing/extra batch dim, or a field accidentally reduced along an axis), so that case raises via _require_shape instead of silently broadcasting.

abs

abs(ctx: Context, take_root: bool = True) -> jnp.ndarray

Scalar residual norm: the (optionally root-ed) reduced squared residual.

AdvectionTerm

AdvectionTerm(
    axes: Sequence[AxisSpec],
    field: str = "u",
    velocity: str | Sequence[str] | None = None,
    scheme: str = "central",
    order: int = 1,
)

velocity . grad(field).

Args:

Name Type Description Default
axes Sequence[AxisSpec]

one entry per spatial axis to include, must be non-empty

field str

ctx key of the field being advected, by default "u"

'u'
velocity str, Sequence[str], or None

the advecting velocity, by default None

  • None -- self-advection: field advects itself along every axis (e.g. Burgers' u * u_x)
  • a single ctx key -- that field advects along every axis
  • a sequence of ctx keys, one per axis in axes -- e.g. the two velocity components (u, v) of a 2D advection term
None
scheme str

"central" (2nd-order accurate, can oscillate on advection-dominated/near-shock terms) or "upwind" (1st-order accurate, picks the FiniteDiff "backward" stencil where the local velocity is >= 0 and "forward" where it's negative -- biasing the stencil toward where the advected quantity is physically coming from, which is what makes it stable), by default "central". "upwind" requires every axis in axes to use a FiniteDiff axis (FourierDiff has no directional stencil to pick between).

'central'
order int

derivative order applied along each axis, by default 1 (the usual velocity . grad(field) meaning of "advection"). Passed straight through to each axis's derivative call, so any order the configured differentiator supports works here too -- e.g. a dispersion-like term v * u_xxx via order=3 with a FourierDiff axis. scheme="upwind" only combines with order=1 -- FiniteDiff itself rejects a directional scheme at any other order.

1

DivergenceTerm

DivergenceTerm(
    fields: Sequence[str],
    axes: Sequence[AxisSpec],
    order: int = 1,
    scheme: str = "central",
)

sum_i d(field_i)/d(axis_i) -- divergence of a vector field given componentwise, e.g. the incompressible-flow continuity residual div(velocity) = u_x + v_y.

Unlike DiffusionTerm, there is no coefficient here: each component's derivative is summed directly, since continuity has no coefficient to multiply by.

Args:

Name Type Description Default
fields Sequence[str]

ctx key of the vector field's component along each axis in axes (e.g. ["u", "v"] for a 2D velocity field), must be the same length as axes

axes Sequence[AxisSpec]

one entry per component in fields, must be non-empty

order int

derivative order applied to each component, by default 1 (the usual sum_i d(field_i)/d(axis_i) meaning of "divergence"). Passed straight through to each axis's derivative call.

1
scheme str

finite-difference scheme applied to each component, one of "central", "forward", "backward", by default "central". Passed straight through to each axis's derivative call -- "forward"/"backward" only combine with order=1, since FiniteDiff itself rejects a directional scheme at any other order, and a FourierDiff axis only accepts "central" (see AxisSpec).

'central'

GradientTerm

GradientTerm(
    axis: AxisSpec,
    field: str = "u",
    order: int = 1,
    scheme: str = "central",
)

d(field)/d(axis) -- one component of a scalar field's gradient.

Deliberately just one axis at a time (e.g. one call for p_x, another for p_y), rather than returning a full gradient vector, since a PDE residual needs each component summed into a different equation (the x-momentum residual gets p_x, y-momentum gets p_y) -- unlike DiffusionTerm/DivergenceTerm, which sum every axis's contribution into one residual.

Mathematically identical to TransientTerm (both are just axis.derivative(field, order=1)); kept as a separate class so a term's name still tells you which PDE role it plays -- a time derivative vs. a spatial pressure-gradient component.

Args:

Name Type Description Default
axis AxisSpec

the axis to differentiate along

field str

ctx key of the field being differentiated, by default "u"

'u'
order int

derivative order, by default 1 (d(field)/d(axis)). Passed straight through to axis.derivative, so it accepts whatever order the configured differentiator supports.

1
scheme str

finite-difference scheme, one of "central", "forward", "backward", by default "central". Passed straight through to axis.derivative -- "forward"/"backward" only combine with order=1, since FiniteDiff itself rejects a directional scheme at any other order, and a FourierDiff axis only accepts "central" (see AxisSpec).

'central'

ReactionTerm

ReactionTerm(field: str = 'u', coeff: str | float = 1.0)

coeff * field.

Args:

Name Type Description Default
field str

ctx key of the field, by default "u"

'u'
coeff str or float

ctx key of the (possibly spatially-varying) reaction coefficient, or a constant, by default 1.0

1.0

TransientTerm

TransientTerm(
    axis: AxisSpec,
    field: str = "u",
    order: int = 1,
    scheme: str = "central",
)

d(field)/dt along a single (typically non-periodic) time axis.

Args:

Name Type Description Default
axis AxisSpec

the time axis

field str

ctx key of the field, by default "u"

'u'
order int

how many times the field is differentiated in time, by default 1 (du/dt). Set to 2 for d^2u/dt^2 -- the time derivative a wave equation needs, since it contains a second time derivative rather than a first one. This is the differentiation order, not the numerical accuracy of the stencil approximating it (that's scheme below). Passed straight through to axis.derivative, so it accepts whatever order the configured differentiator supports.

1
scheme str

finite-difference scheme, one of "central", "forward", "backward", by default "central". Passed straight through to axis.derivative -- "forward"/"backward" only combine with order=1, since FiniteDiff itself rejects a directional scheme at any other order, and a FourierDiff axis only accepts "central" (see AxisSpec).

'central'

FourierDiff

Spectral derivatives (via FFT) of a field sampled on a periodic grid.

Differentiation in physical space becomes multiplication by (i*k) per Fourier mode, where k is the angular wavenumber -- exact for smooth periodic functions up to floating-point precision, rather than merely convergent with grid refinement as FiniteDiff is.

Note

axis and order must be static (plain Python values, not traced arrays); mark them as static_argnames if used inside jax.jit.

derivative

derivative(
    u: ndarray,
    axis: int,
    order: int = 1,
    spacing: float = 1.0,
) -> jnp.ndarray

Differentiate u along a periodic axis via FFT.

Args:

Name Type Description Default
u ndarray

field values on a regular, periodic grid, arbitrary rank

axis int

axis of u to differentiate along

order int

derivative order, by default 1. Any non-negative integer is supported (unlike FiniteDiff, which only supports 1 and 2), since spectral differentiation is just repeated multiplication by (i*k) in frequency space.

1
spacing float

grid spacing h along axis, by default 1.0. For n points sampled over a periodic domain of length L (no duplicated endpoint), use h = L / n.

1.0

Returns:

Type Description
ndarray

derivative of u along axis, same shape as u, dtype matching u (the imaginary part left over from floating-point round-off in the inverse FFT is discarded)

gradient

gradient(
    u: ndarray,
    axes: Sequence[int],
    spacing: Sequence[float] | float = 1.0,
) -> list[jnp.ndarray]

First derivative of u along each of axes.

Convenience wrapper for computing e.g. (du/dx, du/dy) in one call -- used by multi-dimensional PDE residuals (Phase 1) that need several partial derivatives of the same field.

Args:

Name Type Description Default
u ndarray

field values on a regular, periodic grid

axes Sequence[int]

axes of u to differentiate along

spacing float or Sequence[float]

grid spacing per axis in axes, by default 1.0 (either a single value applied to every axis, or one value per axis)

1.0

Returns:

Type Description
list[ndarray]

[du/d(axes[0]), du/d(axes[1]), ...], each the same shape as u

NavierStokesEqnLoss

NavierStokesEqnLoss(
    reynolds: float,
    measure: float | ndarray | Sequence[float] = 1.0,
    reduction: str = "mean",
    lid_velocity: float = 1.0,
    enforce_dirichlet: bool = True,
    pin_pressure: bool = True,
    pressure_pin_value: float = 0.0,
    weights: dict[str, float] | None = None,
    boundary_margin: int = 0,
)

PDE-residual loss for steady, incompressible 2D Navier-Stokes in primitive (velocity-pressure) form -- the lid-driven-cavity benchmark.

Measures how well a predicted (u, v, p) field satisfies, on the unit square with a no-slip wall on three sides and a moving lid on the fourth:

\[ \begin{aligned} u u_x + v u_y + p_x - \tfrac{1}{Re}(u_{xx} + u_{yy}) &= 0 \\ u v_x + v v_y + p_y - \tfrac{1}{Re}(v_{xx} + v_{yy}) &= 0 \\ u_x + v_y &= 0 \end{aligned} \]

Unlike DarcyEqnLoss (one equation, one PDEResidualLoss), this is three coupled equations, so it holds three independent PDEResidualLoss instances internally -- momentum-x, momentum-y, continuity -- and combines their three scalar norms into one loss value.

Note

No-slip + lid boundary handling. By default (enforce_dirichlet=True), the boundary rows/columns of the predicted u/v fields are overwritten before differentiating: u=lid_velocity, v=0 on the lid (the y_max edge -- axis 2's last index, matching DarcyEqnLoss's axis convention: u's axis 1 is x, axis 2 is y), and u=v=0 on the other three edges. As with DarcyEqnLoss, this means no gradient flows back to the model's own boundary predictions through this loss, so it is only safe when some other loss (e.g. a data loss against paired ground truth) already supervises the boundary, or when enforce_dirichlet=False is set instead.

Pressure pinning. Pressure only ever appears through its gradient (p_x, p_y), so it is determined only up to an additive constant -- the discrete analogue of the classical pure-Neumann pressure null space. By default (pin_pressure=True), a single grid point (p[:, 0, 0]) is hard-set to pressure_pin_value before differentiating, breaking that indeterminacy the same way the velocity Dirichlet values break theirs. Leaving both enforce_dirichlet and pin_pressure off is possible but not recommended without another loss constraining the boundary and the pressure level.

Args:

Name Type Description Default
reynolds float

the Reynolds number Re, required (there is no standard default the way Darcy's forcing=1.0 is -- the lid-driven-cavity benchmark is defined by which Re is used, e.g. 100, 400, 1000)

measure float, 0-d array, or Sequence[float]

physical domain length per spatial dimension, by default 1.0 (the standard unit-square cavity domain)

1.0
reduction str

whether to reduce the squared residual across the batch and spatial dims by summing ("sum") or averaging ("mean"), by default "mean"

'mean'
lid_velocity float

the moving lid's horizontal speed (u on the y_max edge), by default 1.0 (the standard lid-driven-cavity convention)

1.0
enforce_dirichlet bool

whether to hard-constrain u/v at the four walls before differentiating, by default True. See the note above.

True
pin_pressure bool

whether to hard-constrain p at one grid point before differentiating, by default True. See the note above.

True
pressure_pin_value float

the value p is pinned to at (0, 0) when pin_pressure=True, by default 0.0

0.0
weights dict[str, float]

per-equation weight applied before summing the three residual norms into one scalar, by default {"momentum_x": 1.0, "momentum_y": 1.0, "continuity": 1.0} -- must have exactly these three keys if given, since momentum and continuity residuals are not generally the same scale and an unweighted sum can let one equation dominate training.

None
boundary_margin int

number of outermost grid rings excluded from the residual norm, by default 0 (use the whole field). See _crop -- on a wall-bounded flow the one-sided boundary stencils dominate the norm with discretization error the true solution cannot satisfy either, so a small non-zero margin (4 on this repo's 129x129 cavity) is recommended whenever this loss is trained on rather than only reported.

0

Configure the Navier-Stokes equation loss. See the class docstring for parameters.

name property

name: str

str: Human-readable identifier.

residual

residual(y_pred: ndarray) -> dict[str, jnp.ndarray]

Pointwise residual for each of the three coupled equations.

Args:

Name Type Description
y_pred ndarray

predicted (u, v, p) field, shape (batch, n_x, n_y, 3)

Returns:

Type Description
dict[str, ndarray]

{"momentum_x": ..., "momentum_y": ..., "continuity": ...}, each shape (batch, n_x, n_y)

abs

abs(y_pred: ndarray, take_root: bool = True) -> jnp.ndarray

Scalar PDE-residual loss: the weighted sum of the three equations' (optionally root-ed) reduced squared residuals.

Args:

Name Type Description Default
y_pred ndarray

predicted (u, v, p) field, shape (batch, n_x, n_y, 3)

take_root bool

whether to take the square root of each equation's reduced squared residual before weighting/summing, by default True

True

residual_unsteady

residual_unsteady(
    y_pred: ndarray, y_pred_next: ndarray, dt: float
) -> dict[str, jnp.ndarray]

Pointwise residual for the transient (unsteady) equations.

Adds du/dt/dv/dt -- estimated by finite-differencing this prediction against y_pred_next (the same model's own prediction at the same spatial grid and same case, dt later in time) -- to the steady momentum residuals from residual. Continuity has no transient term: mass conservation (div(u) = 0) is an instantaneous constraint, independent of time.

Args:

Name Type Description
y_pred ndarray

predicted (u, v, p) field at time t, shape (batch, n_x, n_y, 3)

y_pred_next ndarray

predicted (u, v, p) field at time t + dt, same shape -- same case (Reynolds number / lid velocity) and same spatial grid as y_pred, differing only in the time input that produced each of the two forward passes.

dt float

time step between the two predictions, in whatever time units the caller's own time input uses -- this class has no opinion on time units, it just finite-differences whatever two predictions it's given.

Returns:

Type Description
dict[str, ndarray]

{"momentum_x": ..., "momentum_y": ..., "continuity": ...}, each shape (batch, n_x, n_y)

abs_unsteady

abs_unsteady(
    y_pred: ndarray,
    y_pred_next: ndarray,
    dt: float,
    take_root: bool = True,
) -> jnp.ndarray

Scalar unsteady PDE-residual loss.

Same weighted-sum-of-equations reduction as abs, applied to the transient residuals from residual_unsteady instead of the steady ones.

Args:

Name Type Description Default
y_pred see `residual_unsteady`
y_pred_next see `residual_unsteady`
dt see `residual_unsteady`
take_root bool

whether to take the square root of each equation's reduced squared residual before weighting/summing, by default True

True

DarcyHybridLossGINO

DarcyHybridLossGINO(
    physics_loss: DarcyEqnLoss,
    grid_shape: tuple[int, int],
    data_loss: LpLoss | H1Loss | None = None,
    data_weight: float = 0.0,
)

Combines DarcyEqnLoss (always active, physics term) with an optional weighted supervised data loss, for GINO's flat point-cloud output queried at a fixed regular grid.

Three conventions meet in this class, which is exactly why it exists as a separate adapter rather than being folded into DarcyEqnLoss itself:

  • GINO's own output layout: flat, (batch, n_x * n_y, 1), produced by querying GINO at the Darcy grid's coordinates (flattened in row-major order) via output_queries.
  • DarcyEqnLoss's layout: channels-last grid, (batch, n_x, n_y, 1).
  • LpLoss/H1Loss's layout: channel-first, (batch, 1, n_x, n_y) -- matching the Darcy dataset's own channel-first ground-truth convention, so the labeled target y needs no reshaping, only the reshaped prediction does.

Args:

Name Type Description Default
physics_loss DarcyEqnLoss

the physics (PDE-residual) term, always included

grid_shape tuple[int, int]

(n_x, n_y), the Darcy grid GINO was queried at -- used to fold GINO's flat output back into a grid, and must match the row-major ordering used to build output_queries

data_loss LpLoss or H1Loss

supervised data loss against the labeled pressure field, by default None. Construct with d=2 (matching the channel-first (batch, 1, n_x, n_y) layout this class feeds it).

None
data_weight float

weight applied to data_loss, by default 0.0 (pure physics-only training, matching PFEM's own pretraining stage). A nonzero weight requires data_loss to be given.

0.0

name property

name: str

str: Human-readable identifier.

BatchedVariableCoefficientGalerkinResidualLossT6

BatchedVariableCoefficientGalerkinResidualLossT6(
    galerkin: T6Galerkin,
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    source_fn: Callable[[ndarray, ndarray], ndarray],
    interior_mask: ndarray,
    energy_floor_weight: float = 0.0,
    energy_floor: float = 0.0,
)

T6 analogue of BatchedVariableCoefficientGalerkinResidualLossT3 -- identical calling convention, including the same optional energy_floor_weight/energy_floor amplitude-collapse mitigation (via T6Galerkin.grad_energy); only the element type (and therefore the quadrature machinery underneath) differs. See that class's docstring for the full parameter rationale.

ADDiff

Exact per-point derivatives of f(coords) via the AD sum trick.

Note

dim and order must be static (plain Python values, not traced arrays), matching the convention used by FiniteDiff / FourierDiff.

Warning

f must be block-diagonal in coords -- see the module docstring. This is a precondition, not something checked here.

owns_coords class-attribute instance-attribute

owns_coords = False

Stateless: every call needs its own coordinates, since this is meant to be reused with different or resampled coordinates across calls (a PINN resampling collocation points, GINO getting different query points per batch). See owns_coords for the differentiator where this is True instead, and ad_pde_terms for how PDE terms use this flag to decide whether to pass coords along at all.

nested_differentiator property

nested_differentiator: ADDiff

The differentiator a PDE term should use for a further, nested differentiation call made from inside a closure already being differentiated by this one (e.g. DiffusionTermAD's flux-form path, which differentiates a coefficient function and the field it multiplies separately). ADDiff has no internal state tied to a specific coordinate array, so it is always safe to call again on any input -- this simply returns self. See nested_differentiator for the differentiator where this is not true.

derivative

derivative(
    f: FieldFn, coords: ndarray, dim: int, order: int = 1
) -> jnp.ndarray

d^order u / d(coords[..., dim])^order at every point.

Args:

Name Type Description Default
f Callable[[ndarray], ndarray]

maps coords (shape (n_points, coord_dim)) to the field value at each point (shape (n_points,))

coords ndarray

query coordinates, shape (n_points, coord_dim)

dim int

which coordinate dimension to differentiate along (0 for x, 1 for y, ...)

order int

derivative order, 1 or 2, by default 1. Order 2 differentiates along dim twice -- a diagonal second derivative (d^2u/dx^2), not a full Hessian. The two passes deliberately use different differentiation modes: see _first_fwd for why.

1

Returns:

Type Description
ndarray

derivative at each point, shape (n_points,)

gradient

gradient(
    f: FieldFn, coords: ndarray, dims: Sequence[int]
) -> list[jnp.ndarray]

First derivative of f(coords) along each of dims, from a single backward pass (all coordinate dims come out of one jax.grad call already -- this just slices them out), rather than one call to derivative per dim.

Args:

Name Type Description
f Callable[[ndarray], ndarray]

as in derivative

coords ndarray

query coordinates, shape (n_points, coord_dim)

dims Sequence[int]

coordinate dimensions to differentiate along

Returns:

Type Description
list[ndarray]

[du/d(coords[...,dims[0]]), du/d(coords[...,dims[1]]), ...], each shape (n_points,)

AdvectionTermAD

AdvectionTermAD(
    dims: Sequence[int],
    field: str = "u_fn",
    velocity: str
    | Sequence[str | float]
    | float
    | None = None,
    differentiator: ADDifferentiator | None = None,
)

velocity . grad(field).

Like DiffusionTermAD, ctx["coords"] is only forwarded to differentiator.gradient when differentiator.owns_coords is False -- see _coords_kwarg.

Args:

Name Type Description Default
dims Sequence[int]

coordinate dimensions to include

field str

ctx key of the callable field being advected, by default "u_fn"

'u_fn'
velocity str, Sequence[str], float, or None

the advecting velocity, by default None

  • None -- self-advection: field advects itself along every dim (e.g. steady viscous Burgers' u * u_x), using u_fn evaluated (not differentiated) at coords
  • a single ctx key or constant -- that value advects along every dim
  • a sequence of ctx keys/constants, one per dim in dims
None
differentiator ADDifferentiator

which AD backend to differentiate field with, by default ADDiff() -- see ADDifferentiator and DiffusionTermAD's differentiator parameter.

None

DiffusionTermAD

DiffusionTermAD(
    dims: Sequence[int],
    field: str = "u_fn",
    coeff: str | float | FieldFn = 1.0,
    differentiator: ADDifferentiator | None = None,
)

div(coeff * grad(field)), in flux form.

See the module docstring for why coeff accepts a plain float or a coordinate function coeff_fn(coords) -> jnp.ndarray, but not a precomputed array. A float (trivially constant) takes the cheap coeff * laplacian(field) path; a callable takes the true flux-form path, computed with nested AD: flux_d(c) = coeff_fn(c) * d(field)/d(c[..., d]) for each dimension d, differentiated once more via the sum trick and summed over dims -- exactly the AD analogue of what DiffusionTerm does with FiniteDiff. Because flux_d is a genuine function of c, JAX's autodiff applies the product rule automatically when it's differentiated the second time, so this is correct whether or not coeff_fn actually varies -- it is not merely a fallback for the varying case.

d(field)/d(c[..., d]) inside flux_d is computed via differentiator.nested_differentiator, not differentiator itself -- this inner call happens from inside a closure differentiator is already differentiating (the outer flux_d derivative below it), and for PatchQuadratureADDiff specifically, calling back into the same instance for that would (and once did) fail, since by that point c is only one patch's worth of coordinates, not the full array that instance expects. Every ADDifferentiator exposes .nested_differentiator precisely so this term never needs to know which concrete differentiator was injected -- see PatchQuadratureADDiff's own nested_differentiator.

Similarly, ctx["coords"] is only forwarded to the outer differentiator.derivative call (the Laplacian path and the outer step of the flux-form path) when differentiator.owns_coords is False -- see _coords_kwarg. For a differentiator that owns its coordinates, ctx["coords"] is used only for the output array's shape/dtype, never actually passed in, so this term is unaffected even if ctx["coords"] does not match that differentiator's own coords.

Warning

A coeff_fn must be block-diagonal in coords, the exact same precondition ADDiff already documents for field -- point i's coefficient must not depend on point j's coordinates. This isn't checked here, for the same reason it isn't checked for field: there is no cheap way to detect non-block-diagonality from inside the primitive. coeff_fn(coords) is however checked for the same unbatched-output and shape requirements field gets.

Args:

Name Type Description Default
dims Sequence[int]

coordinate dimensions to include in the divergence

field str

ctx key of the callable field being diffused, by default "u_fn"

'u_fn'
coeff str, float, or Callable[[jnp.ndarray], jnp.ndarray]

a diffusion coefficient -- a constant, a coordinate function, or a ctx key resolving to either of those -- by default 1.0. A ctx key resolving to a precomputed array raises; see the module docstring for why.

1.0
differentiator ADDifferentiator

which AD backend to differentiate field (and, for the flux-form path, coeff_fn) with, by default ADDiff(). Pass ExactPointwiseADDiff or PatchQuadratureADDiff instead whenever field/coeff_fn mix points (e.g. Transolver's attention) -- see ADDifferentiator.

None

ReactionTermAD

ReactionTermAD(
    field: str = "u_fn", coeff: str | float = 1.0
)

coeff * field -- direct evaluation of the callable field at coords, no differentiation at all.

Args:

Name Type Description Default
field str

ctx key of the callable field, by default "u_fn"

'u_fn'
coeff str or float

ctx key of the reaction coefficient, or a constant, by default 1.0

1.0

SourceTermAD

SourceTermAD(value: str | float = 0.0)

A constant or sampled forcing term f -- identical in spirit to SourceTerm; no function needed since the source is never itself differentiated.

Args:

Name Type Description Default
value str or float

ctx key of the (possibly per-point) source values, or a constant, by default 0.0

0.0

T3Galerkin

T3Galerkin(xy: ndarray, tri: ndarray)

Generic linear (T3) triangular-element Galerkin gradient machinery, precomputed once for a fixed mesh and shared by every instance in a training batch, via known closed-form shape-function gradients on a triangulation.

A T3 element's shape functions are linear, so the gradient of a nodal field's piecewise-linear interpolant is constant per triangle -- element_gradient and element_areas reflect that with a leading (T,) shape throughout, T the triangle count.

Args:

Name Type Description
xy (array, shape(N, 2))

Node coordinates.

tri (array, shape(T, 3), int)

Triangle connectivity, 0-indexed.

element_gradient

element_gradient(
    u: ndarray,
) -> tuple[jnp.ndarray, jnp.ndarray]

u, shape (N,), a nodal field -> (du_dx, du_dy), each shape (T,): the constant gradient of u's T3 (piecewise-linear) interpolant over each triangle.

quadrature_points

quadrature_points() -> jnp.ndarray

Physical coordinates of the 3-point/degree-2 quadrature rule's points (see the module docstring's "Quadrature" section), shape (3, T, 2) -- exact for a field varying up to quadratic order within an element, unlike a single centroid-value point (exact only for a field constant per element). Precomputed once in __init__ since it depends only on the mesh, not on any per-instance field.

scatter_to_nodes

scatter_to_nodes(elem_contrib: ndarray) -> jnp.ndarray

elem_contrib, shape (T, 3) -- one value per triangle per local node (0, 1, 2) -- scattered/accumulated into a nodal array, shape (N,). This is the assembly step: summing every triangle's contribution to each test function N_i it touches.

element_kappa

element_kappa(
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    params: ndarray,
) -> jnp.ndarray

kappa_fn evaluated at the 3-point quadrature rule and combined into one effective per-element value, shape (T,) -- the quantity grad_energy and t3_weak_residual both need, factored out since both use it identically.

grad_energy

grad_energy(
    u: ndarray,
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    params: ndarray,
) -> jnp.ndarray

Scalar int kappa * |grad(u)|^2 dOmega, kappa evaluated via element_kappa's quadrature rule, exact quadrature for the piecewise-linear u's constant-per-element gradient.

T6Galerkin

T6Galerkin(xy: ndarray, tri: ndarray)

Generic quadratic (T6) triangular-element Galerkin machinery, precomputed once for a fixed mesh and shared by every instance in a PINO batch -- the T6 analogue of T3Galerkin.

Unlike T3, per-element quantities here (physical shape-function gradients, the Jacobian determinant) vary within an element and are only ever available at the quadrature points, not in closed form -- physical_grad_and_jacobian returns them at all 6 quadrature points at once, shape (Q, ...).

Args:

Name Type Description
xy (array, shape(N, 2))

Node coordinates (corners and mid-edge nodes together).

tri (array, shape(T, 6), int)

Triangle connectivity, 0-indexed, gmsh T6 node order (3 corners, then mid(1,2), mid(2,3), mid(3,1)).

physical_grad_and_jacobian

physical_grad_and_jacobian() -> tuple[
    jnp.ndarray, jnp.ndarray, jnp.ndarray
]

Physical-space shape-function gradients and the Jacobian determinant at every quadrature point, for every element. Precomputed once in __init__ (and validated away from a degenerate/near-zero determinant there) since it depends only on the mesh, not on any per-instance field.

Returns:

Name Type Description
dN_dx, dN_dy : array, shape (Q, T, 6)
det_j (array, shape(Q, T))

quadrature_points_physical

quadrature_points_physical() -> jnp.ndarray

Physical coordinates of every quadrature point, every element, shape (Q, T, 2), from the isoparametric map. Precomputed once in __init__ since it depends only on the mesh.

element_gradient_at_quad

element_gradient_at_quad(
    u: ndarray,
) -> tuple[jnp.ndarray, jnp.ndarray]

u, shape (N,) -> (du_dx, du_dy), each shape (Q, T): the gradient of u's T6 (piecewise-quadratic) interpolant, evaluated at every quadrature point of every element (linear within an element, unlike T3's constant-per-element gradient).

grad_energy

grad_energy(
    u: ndarray,
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    params: ndarray,
) -> jnp.ndarray

Scalar int kappa * |grad(u)|^2 dOmega, the T6 analogue of grad_energy, used by BatchedVariableCoefficientGalerkinResidualLossT6's own amplitude-collapse mitigation.

scatter_to_nodes

scatter_to_nodes(elem_contrib: ndarray) -> jnp.ndarray

elem_contrib, shape (T, 6) -- one value per triangle per local node (0..5) -- scattered/accumulated into a nodal array, shape (N,).

BatchedVariableCoefficientGalerkinResidualLossT3

BatchedVariableCoefficientGalerkinResidualLossT3(
    galerkin: T3Galerkin,
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    source_fn: Callable[[ndarray, ndarray], ndarray],
    interior_mask: ndarray,
    energy_floor_weight: float = 0.0,
    energy_floor: float = 0.0,
)

A batched training signal for div(kappa * grad(u)) = source on a fixed T3 mesh shared across every instance, using known linear shape-function gradients to assemble the weak-form residual.

Args:

Name Type Description Default
galerkin T3Galerkin

Built once over the mesh shared by every instance in the batch.

kappa_fn callable

(params, point) -> scalar, evaluated at each element's 3-point quadrature rule (see the module docstring's "Quadrature" section).

source_fn callable

(params, point) -> scalar, the manufactured source (e.g. a training script's own exact_source_point), evaluated the same way as kappa_fn. This is a function supplied once at construction, not a precomputed nodal array passed to every call -- the Galerkin residual needs the source at quadrature points, not just at nodes, and since the source is already a known closed form, evaluating it directly is simpler than precomputing and threading a nodal array through.

interior_mask (array, shape(N))

Only interior (non-Dirichlet-boundary) nodes contribute to the residual -- boundary nodes get their supervision from the model's own boundary ansatz upstream, not from this residual.

energy_floor_weight float

Mitigates a known failure mode of residual-squared physics losses: such a loss alone can be minimized by a near-zero-amplitude field that trivially satisfies the residual without solving the PDE. Adding energy_floor_weight * mean(relu(energy_floor - E_grad)^2), where E_grad = int kappa*|grad(u)|^2 (which shrinks monotonically toward zero as u -> 0, unlike the plain residual), penalizes that collapse. Both default to 0.0 (disabled) -- energy_floor has no principled default and should be calibrated from a reference solution's own E_grad at the mesh resolution being trained at, only if collapse is actually observed.

0.0
energy_floor float

Mitigates a known failure mode of residual-squared physics losses: such a loss alone can be minimized by a near-zero-amplitude field that trivially satisfies the residual without solving the PDE. Adding energy_floor_weight * mean(relu(energy_floor - E_grad)^2), where E_grad = int kappa*|grad(u)|^2 (which shrinks monotonically toward zero as u -> 0, unlike the plain residual), penalizes that collapse. Both default to 0.0 (disabled) -- energy_floor has no principled default and should be calibrated from a reference solution's own E_grad at the mesh resolution being trained at, only if collapse is actually observed.

0.0

Experimental training loop

Trainer needs a model wrapper that holds the parameters and optimiser and provides train_step; the Car-CFD benchmark (scripts/benchmarks/car_cfd/_models.py) shows one. The library models (FNO, GINO, ...) are plain Flax modules and cannot be passed to Trainer directly.

Trainer

Trainer(
    *,
    model: Any,
    n_epochs: int,
    wandb_log: bool = False,
    device: str = "cpu",
    mixed_precision: bool = False,
    data_processor: Any | None = None,
    eval_interval: int = 1,
    log_output: bool = False,
    use_distributed: bool = False,
    verbose: bool = False,
    stacked_train_data: Any | None = None,
)

A general Trainer class to train neural-operators on given datasets.

The Trainer expects datasets to provide batches as key-value dictionaries, ex.: {'x': x, 'y': y}, that are keyed to the arguments expected by models and losses.

Args:

Name Type Description Default
model Module

model to train. Duck-typed: any object exposing __call__(**sample) (and optionally train_step, eval, state_dict/ load_state_dict) is accepted, not just a Flax nn.Module.

n_epochs int

number of training epochs

wandb_log bool

whether to log results to wandb

is False
device str

device for computation (JAX handles placement automatically)

'cpu'
mixed_precision bool

Not implemented. Trainer.__init__ raises NotImplementedError if this is True.

is False
data_processor DataProcessor class to transform data

if not None, data from the loaders is transform first with data_processor.preprocess, then after getting an output from the model, that is transformed with data_processor.postprocess.

is None
eval_interval int

how frequently to evaluate model and log training stats

is 1
log_output bool

if True, and if wandb_log is also True, log output images to wandb

is False
use_distributed bool

whether to use distributed training (JAX pmap)

is False
verbose bool

whether to print training progress

is False

Initialize Trainer.

train

train(
    train_loader: Any,
    test_loaders: dict[str, Any],
    optimizer: Any,
    scheduler: Any,
    regularizer: Any | None = None,
    training_loss: Any | None = None,
    eval_losses: dict[str, Any] | None = None,
    eval_modes: dict[str, str] | None = None,
    save_every: int | None = None,
    save_best: str | None = None,
    save_dir: str | Path = "./ckpt",
    resume_from_dir: str | Path | None = None,
    max_autoregressive_steps: int | None = None,
) -> dict[str, Any]

Trains the given model on the given dataset.

Args:

Name Type Description Default
train_loader DataLoader

training dataloader

test_loaders dict

testing dataloaders keyed by name

optimizer optax optimizer

optimizer to use during training

scheduler scheduler object

learning rate scheduler to use during training

training_loss loss function

cost function to minimize

None
eval_losses dict

dict of losses to use in evaluation

None
eval_modes dict

optional mapping from loader name to evaluation mode ('single_step' or 'autoregressive')

None
save_every int

if provided, interval at which to save checkpoints

None
save_best str

if provided, key of metric to monitor for best model

None
save_dir str | Path

directory at which to save training states

"./ckpt"
resume_from_dir str | Path

if provided, resumes training state from this directory

None
max_autoregressive_steps int

max number of autoregressive steps for evaluation

None

Returns:

Name Type Description
epoch_metrics dict

dictionary of metrics for the last validation epoch

train_one_epoch

train_one_epoch(
    epoch: int, train_loader: Any, training_loss: Any
) -> tuple[float, float, float | None, float]

Train for one epoch and return training metrics.

Args:

Name Type Description
epoch int

epoch number

train_loader DataLoader

training data loader

training_loss loss function

training loss function

Returns:

Name Type Description
train_err float

average training error

avg_loss float

average loss per sample

avg_lasso_loss float or None

average regularization loss

epoch_train_time float

time taken for epoch

evaluate_all

evaluate_all(
    epoch: int,
    eval_losses: dict[str, Any],
    test_loaders: dict[str, Any],
    eval_modes: dict[str, str],
    max_autoregressive_steps: int | None = None,
) -> dict[str, Any]

Evaluate on all test loaders.

Args:

Name Type Description Default
epoch int

current training epoch

eval_losses dict

keyed loss_name: loss_obj for each loss

test_loaders dict

keyed loader_name: loader for each test loader

eval_modes dict

keyed loader_name: eval_mode for each test loader

max_autoregressive_steps int

max number of autoregressive steps

None

Returns:

Name Type Description
all_metrics dict

collected eval metrics for each loader

evaluate

evaluate(
    loss_dict: dict[str, Any],
    data_loader: Any,
    log_prefix: str = "",
    epoch: int | None = None,
    mode: str = "single_step",
    max_steps: int | None = None,
) -> dict[str, Any]

Evaluate the model on a dictionary of losses.

Args:

Name Type Description Default
loss_dict dict

each function takes as input (prediction, ground_truth) and returns the corresponding loss

data_loader DataLoader

data loader to evaluate on

log_prefix str

used as prefix in output dictionary

''
epoch int | None

current epoch for logging

None
mode str

'single_step' or 'autoregression'

'single_step'
max_steps int

max number of steps for autoregressive rollout

None

Returns:

Name Type Description
errors dict

dict[f'{log_prefix}_{loss_name}'] = loss value

on_epoch_start

on_epoch_start(epoch: int) -> None

Run at the beginning of each training epoch.

Args:

Name Type Description
epoch int

index of epoch

Returns:

Type Description
None

train_one_batch

train_one_batch(
    idx: int, sample: dict, training_loss: Any
) -> Any

Run one batch through model and return training loss.

Args:

Name Type Description
idx int

index of batch within train_loader

sample dict

data dictionary holding one batch

training_loss loss function

loss function to compute

Returns:

Name Type Description
loss float or array

training loss value

eval_one_batch

eval_one_batch(
    sample: dict,
    eval_losses: dict,
    return_output: bool = False,
) -> tuple[dict, Any]

Run inference on one batch and return eval losses.

Args:

Name Type Description Default
sample dict

data batch dictionary

eval_losses dict

dictionary of named eval metrics

return_output bool

whether to return model outputs for plotting

False

Returns:

Name Type Description
eval_step_losses dict

keyed "loss_name": step_loss_value for each loss

outputs array or None

optionally returns batch outputs

eval_one_batch_autoreg

eval_one_batch_autoreg(
    sample: dict,
    eval_losses: dict,
    return_output: bool = False,
    max_steps: int | None = None,
) -> tuple[dict, Any]

Run autoregressive inference on one batch.

Args:

Name Type Description Default
sample dict

data batch dictionary

eval_losses dict

dictionary of named eval metrics

return_output bool

whether to return model outputs for plotting

False
max_steps int

max number of timesteps to roll out

None

Returns:

Name Type Description
eval_step_losses dict

keyed "loss_name": step_loss_value for each loss

outputs array or None

optionally returns batch outputs

log_training

log_training(
    epoch: int,
    time: float,
    avg_loss: float,
    train_err: float,
    avg_lasso_loss: float | None = None,
    lr: float | None = None,
) -> None

Log results from a single training epoch.

Args:

Name Type Description Default
epoch int

epoch number

time float

training time of epoch

avg_loss float

average loss per sample

train_err float

training error for entire epoch

avg_lasso_loss float

average lasso loss from regularizer

None
lr float

learning rate at current epoch

None

log_eval

log_eval(epoch: int, eval_metrics: dict) -> None

Log evaluation metrics to stdout and wandb.

Args:

Name Type Description
epoch int

current training epoch

eval_metrics dict

metrics keyed f"{test_loader_name}_{metric}"

resume_state_from_dir

resume_state_from_dir(save_dir: str | Path) -> None

Resume training from a saved state directory.

Args:

Name Type Description
save_dir str | Path

directory in which training state is saved

checkpoint

checkpoint(save_dir: str | Path) -> None

Save current training state to a directory.

Args:

Name Type Description
save_dir str | Path

directory in which to save training state

SimpleDataLoader

SimpleDataLoader(batches: list[dict[str, Any]])

Wrap a list of batches so Trainer can use it as a data loader.

Iterating yields the batches in order, and len() is the number of batches. The dataset attribute only supports len() (the number of batches).

Args:

Name Type Description
batches list of dict

Pre-built batches, each a dict such as {"x": x, "y": y}.

save_training_state

save_training_state(
    save_dir: str | Path,
    save_name: str,
    model: Any = None,
    optimizer: Any = None,
    scheduler: Any = None,
    regularizer: Any = None,
    epoch: int | None = None,
) -> None

save_training_state saves model and optional other training modules for downstream use

Args:

Name Type Description Default
save_dir Union[str, Path]

directory to save training state (model, optional optimizer, scheduler, regularizer)

save_name str

name of model to save

model object

model object to save (Flax module or state dict), by default None

None
optimizer object

optimizer object to save, by default None

None
scheduler object

scheduler object to save, by default None

None
regularizer object

regularizer object to save, by default None

None
epoch int

epoch number to save, by default None

None

load_training_state

load_training_state(
    save_dir: str | Path,
    save_name: str,
    model: Any = None,
    optimizer: Any = None,
    scheduler: Any = None,
    regularizer: Any = None,
    map_location: dict | None = None,
) -> tuple[Any, Any, Any, Any, int | None]

load_training_state returns model and optional other training modules saved from prior training for downstream use

Args:

Name Type Description Default
save_dir Union[str, Path]

directory from which to load training state (model, optional optimizer, scheduler, regularizer)

save_name str

name of model to load

model object

model object to load (Flax module or similar), by default None

None
optimizer object

optimizer object to load, by default None

None
scheduler object

scheduler object to load, by default None

None
regularizer object

regularizer object to load, by default None

None
map_location dict

mapping dictionary (for API compatibility), by default None

None

Returns:

Type Description
tuple of training state

model, optimizer, scheduler, regularizer, epoch

Analysis

spectrum_2d

spectrum_2d(
    signal: ndarray,
    n_observations: int,
    normalize: bool = True,
) -> jnp.ndarray

This function computes the spectrum of a 2D signal using the Fast Fourier Transform (FFT).

Args:

Name Type Description Default
signal a tensor of shape (T * n_observations * n_observations)

A 2D discretized signal represented as a 1D tensor with shape (T * n_observations * n_observations), where T is the number of time steps and n_observations is the spatial size of the signal.

T can be any number of channels that we reshape into and n_observations * n_observations is the spatial resolution.

n_observations int

Number of discretized points. Basically the resolution of the signal.

normalize bool

whether to apply normalization to the output of the 2D FFT. If True, normalizes the outputs by 1/n_observations (actually 1/sqrt(n_observations * n_observations)).

True

Returns:

Name Type Description
spectrum a tensor

A 1D tensor of shape (s,) representing the computed spectrum. The spectrum is computed using a square approximation to radial binning, meaning that the wavenumber 'bin' into which a particular coefficient is the coefficient's location along the diagonal, indexed from the top-left corner of the 2D FFT output.

compute_rank

compute_rank(tensor: ndarray) -> jnp.ndarray

Return the matrix rank of tensor.

Args:

Name Type Description
tensor ndarray

A matrix.

Returns:

Type Description
ndarray

The number of singular values above the numerical tolerance.

compute_stable_rank

compute_stable_rank(tensor: ndarray) -> jnp.ndarray

Return the stable rank of tensor, the squared Frobenius norm over the squared spectral norm.

Args:

Name Type Description
tensor ndarray

A matrix.

Returns:

Type Description
ndarray

A scalar between 1 and the matrix rank.

compute_explained_variance

compute_explained_variance(
    frequency_max: int, s: ndarray
) -> jnp.ndarray

Return the variance explained by the first frequency_max singular values.

Args:

Name Type Description
frequency_max int

Number of leading singular values kept.

s ndarray

Singular values.

Returns:

Type Description
ndarray

A scalar, 1 minus the variance of the discarded part over the variance of s.