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 |
wno_size
|
tuple[int, ...]
|
Spatial shape of the fixed latent grid (e.g. |
wno_hidden_channels
|
see `WNO`
|
Sized the same empirical way GINO's |
wno_n_layers
|
see `WNO`
|
Sized the same empirical way GINO's |
wno_level
|
see `WNO`
|
Sized the same empirical way GINO's |
wno_wavelet
|
see `WNO`
|
Sized the same empirical way GINO's |
latent_embedding
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.
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 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 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
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 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 |
|
y
|
ndarray
|
tensor of patched ground-truth |
|
evaluation
|
bool
|
whether in evaluation mode, by default False.
If True, |
False
|
make_patches
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 |
|
p
|
int or list
|
number of pixels to use when padding |
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
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
The handle a training function uses to talk to the tuner.
The only required call is report, once per epoch/step.
report
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 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 additional parameters to this trial's MLflow run.
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 |
|
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'
|
residual
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.
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
|
|
'u'
|
velocity
|
str, Sequence[str], or None
|
the advecting velocity, by default None
|
None
|
scheme
|
str
|
|
'central'
|
order
|
int
|
derivative order applied along each axis, by default 1 (the usual
|
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]
|
|
|
axes
|
Sequence[AxisSpec]
|
one entry per component in |
|
order
|
int
|
derivative order applied to each component, by default 1 (the
usual |
1
|
scheme
|
str
|
finite-difference scheme applied to each component, one of
|
'central'
|
GradientTerm
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
|
|
'u'
|
order
|
int
|
derivative order, by default 1 ( |
1
|
scheme
|
str
|
finite-difference scheme, one of |
'central'
|
ReactionTerm
coeff * field.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
|
'u'
|
coeff
|
str or float
|
|
1.0
|
TransientTerm
d(field)/dt along a single (typically non-periodic) time axis.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
AxisSpec
|
the time axis |
|
field
|
str
|
|
'u'
|
order
|
int
|
how many times the field is differentiated in time, by default 1
( |
1
|
scheme
|
str
|
finite-difference scheme, one of |
'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
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 |
|
order
|
int
|
derivative order, by default 1. Any non-negative integer is
supported (unlike |
1
|
spacing
|
float
|
grid spacing |
1.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
derivative of |
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 |
|
spacing
|
float or Sequence[float]
|
grid spacing per axis in |
1.0
|
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
|
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:
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 |
|
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 ( |
1.0
|
enforce_dirichlet
|
bool
|
whether to hard-constrain |
True
|
pin_pressure
|
bool
|
whether to hard-constrain |
True
|
pressure_pin_value
|
float
|
the value |
0.0
|
weights
|
dict[str, float]
|
per-equation weight applied before summing the three residual norms
into one scalar, by default |
None
|
boundary_margin
|
int
|
number of outermost grid rings excluded from the residual norm, by
default 0 (use the whole field). See |
0
|
Configure the Navier-Stokes equation loss. See the class docstring for parameters.
residual
Pointwise residual for each of the three coupled equations.
Args:
| Name | Type | Description |
|---|---|---|
y_pred
|
ndarray
|
predicted |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
|
abs
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 |
|
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
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 |
y_pred_next
|
ndarray
|
predicted |
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]
|
|
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) viaoutput_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 targetyneeds 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]
|
|
|
data_loss
|
LpLoss or H1Loss
|
supervised data loss against the labeled pressure field, by default
None. Construct with |
None
|
data_weight
|
float
|
weight applied to |
0.0
|
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
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
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
d^order u / d(coords[..., dim])^order at every point.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[ndarray], ndarray]
|
maps |
|
coords
|
ndarray
|
query coordinates, shape |
|
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 |
1
|
Returns:
| Type | Description |
|---|---|
ndarray
|
derivative at each point, shape |
gradient
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 |
coords
|
ndarray
|
query coordinates, shape |
dims
|
Sequence[int]
|
coordinate dimensions to differentiate along |
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
|
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
|
|
'u_fn'
|
velocity
|
str, Sequence[str], float, or None
|
the advecting velocity, by default None
|
None
|
differentiator
|
ADDifferentiator
|
which AD backend to differentiate |
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
|
|
'u_fn'
|
coeff
|
str, float, or Callable[[jnp.ndarray], jnp.ndarray]
|
a diffusion coefficient -- a constant, a coordinate function, or a
|
1.0
|
differentiator
|
ADDifferentiator
|
which AD backend to differentiate |
None
|
ReactionTermAD
coeff * field -- direct evaluation of the callable field at
coords, no differentiation at all.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
|
'u_fn'
|
coeff
|
str or float
|
|
1.0
|
SourceTermAD
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
|
|
0.0
|
T3Galerkin
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
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
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
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
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.
T6Galerkin
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-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
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
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).
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
|
|
|
source_fn
|
callable
|
|
|
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
|
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
|
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 |
|
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. |
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 |
|
test_loaders
|
dict
|
keyed |
|
eval_modes
|
dict
|
keyed |
|
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
Run at the beginning of each training epoch.
Args:
| Name | Type | Description |
|---|---|---|
epoch
|
int
|
index of epoch |
Returns:
| Type | Description |
|---|---|
None
|
|
train_one_batch
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
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 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 training from a saved state directory.
Args:
| Name | Type | Description |
|---|---|---|
save_dir
|
str | Path
|
directory in which training state is saved |
SimpleDataLoader
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 |
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
|
|
Analysis
spectrum_2d
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 |
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
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
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
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 |