Skip to content

scirex.models

Neural-operator architectures, the get_model_jax factory and the BaseModel class they share.

from scirex.models import FNO, get_model_jax
Name Use it to
FNO learn maps between functions on regular grids (Fourier layers)
GINO learn on irregular meshes and geometries (graph and Fourier layers)
WNO learn with wavelet layers, good for sharp local features
Transolver learn on meshes of any layout with physics-aware attention
get_model_jax build a model from a configuration
BaseModel save and load checkpoints; subclass it to add a model

GIWO is experimental; see scirex.experimental.

Architectures

FNO

Bases: BaseModel

N-Dimensional Fourier Neural Operator. The FNO learns a mapping between spaces of functions discretized over regular grids using Fourier convolutions, as described in [1].

The key component of an FNO is its SpectralConv layer (see scirex.layers.SpectralConv), which is similar to a standard CNN conv layer but operates in the frequency domain.

For the theory, see the Fourier Neural Operator concept page.

Args:

Name Type Description
n_modes Tuple[int, ...]

Number of modes to keep in Fourier Layer, along each dimension. The dimensionality of the FNO is inferred from len(n_modes). n_modes must be larger enough but smaller than max_resolution//2 (Nyquist frequency)

in_channels int

Number of channels in input function. Determined by the problem.

out_channels int

Number of channels in output function. Determined by the problem.

hidden_channels int

Width of the FNO (i.e. number of channels). This significantly affects the number of parameters of the FNO. Good starting point can be 64, and then increased if more expressivity is needed. Update lifting_channel_ratio and projection_channel_ratio accordingly since they are proportional to hidden_channels.

n_layers int

Number of Fourier Layers. Default: 4

Other args:

Name Type Description
lifting_channel_ratio Number

Ratio of lifting channels to hidden_channels. The number of lifting channels in the lifting block of the FNO is lifting_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels).

projection_channel_ratio Number

Ratio of projection channels to hidden_channels. The number of projection channels in the projection block of the FNO is projection_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels).

positional_embedding Union[str, Module]

Positional embedding to apply to last channels of raw input before being passed through the FNO. Options:

  • "grid": Appends a grid positional embedding with default settings to the last channels of raw input. Assumes the inputs are discretized over a grid with entry [0,0,...] at the origin and side lengths of 1.
  • GridEmbeddingND: Uses this module directly (see scirex.layers.GridEmbeddingND for details).
  • GridEmbedding2D: Uses this module directly for 2D cases.
  • None: Does nothing. Default: "grid"
non_linearity Module

Non-Linear activation function module to use. Default: nn.gelu

norm Literal[ada_in, group_norm, instance_norm]

Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", None. Default: None

complex_data bool

Whether the data is complex-valued. If True, initializes complex-valued modules. Default: False

use_channel_mlp bool

Whether to use an MLP layer after each FNO block. Default: True

channel_mlp_dropout float

Dropout parameter for ChannelMLP in FNO Block. Default: 0

channel_mlp_expansion float

Expansion parameter for ChannelMLP in FNO Block. Default: 0.5

channel_mlp_skip Literal[linear, identity, soft - gating, None]

Type of skip connection to use in channel-mixing mlp. Options: "linear", "identity", "soft-gating", None. Default: "soft-gating"

fno_skip Literal[linear, identity, soft - gating, None]

Type of skip connection to use in FNO layers. Options: "linear", "identity", "soft-gating", None. Default: "linear"

resolution_scaling_factor Union[Number, List[Number]]

Layer-wise factor by which to scale the domain resolution of function. Options:

  • None: No scaling
  • Single number n: Scales resolution by n at each layer
  • List of numbers [n_0, n_1,...]: Scales layer i's resolution by n_i Default: None
domain_padding Union[Number, List[Number]]

Percentage of padding to use. Options:

  • None: No padding
  • Single number: Percentage of padding to use along all dimensions
  • List of numbers [p1, p2, ..., pN]: Percentage of padding along each dimension Default: None
fno_block_precision str

Precision mode in which to perform spectral convolution. Options: "full", "half", "mixed". Default: "full". Default: "full"

stabilizer str

Whether to use a stabilizer in FNO block. Options: "tanh", None. Default: None. stabilizer greatly improves performance in the case fno_block_precision='mixed'.

max_n_modes Tuple[int, ...]

Maximum number of modes to use in Fourier domain during training. None means that all the n_modes are used. Tuple of integers: Incrementally increase the number of modes during training. This can be updated dynamically during training.

factorization str

Tensor factorization of the FNO layer weights to use. Options: None or "Dense" (the dense weights) and "Tucker". CP and TT are not supported and raise NotImplementedError. Default: None

rank float

Tensor rank to use in factorization. Default: 1.0 Set to float <1.0 when factorization is not None; rank 0.1 gives roughly 10% of the parameters of a dense FNO.

fixed_rank_modes bool

Whether to not factorize certain modes. Default: False

implementation str

Implementation method for factorized tensors. Options: "factorized", "reconstructed". Default: "factorized"

decomposition_kwargs dict

Extra kwargs for the tensor decomposition. Default: {}

separable bool

Whether to use a separable spectral convolution. Default: False

preactivation bool

Whether to compute FNO forward pass with resnet-style preactivation. Default: False

conv_module Module

Module to use for FNOBlock's convolutions. Default: SpectralConv

enforce_hermitian_symmetry bool

Whether to enforce Hermitian symmetry conditions when performing inverse FFT for real-valued data. Only used when conv_module is SpectralConv or a subclass; ignored otherwise. When True, explicitly enforces that the 0th frequency and Nyquist frequency are real-valued before calling irfft. When False, relies on cuFFT's irfftn to handle symmetry automatically, which may fail on certain GPUs or input sizes, causing line artifacts. By default True.

Examples:

>>> import jax, jax.numpy as jnp
>>> from scirex.models import FNO
>>> model = FNO(n_modes=(8, 8), in_channels=1, out_channels=1, hidden_channels=16, n_layers=2)
>>> x = jnp.ones((2, 1, 32, 32))  # (batch, channels, height, width)
>>> params = model.init(jax.random.PRNGKey(0), x)
>>> model.apply(params, x).shape
(2, 1, 32, 32)
References

[1] Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895.

n_modes property writable

n_modes: Any

Tuple[int, ...]: Number of Fourier modes kept along each dimension.

FNOClassic2d

Bases: BaseModel

The 2020/2021 FNO2d architecture, 2D and real-data only, with one deliberate deviation from the literal release -- see the module docstring.

Args:

Name Type Description
in_channels int

Number of input channels before the built-in grid positional embedding (which always adds 2 more: x and y coordinates).

out_channels int
n_modes1 int

Retained Fourier modes; see ClassicSpectralConv2d.

n_modes2 int

Retained Fourier modes; see ClassicSpectralConv2d.

hidden_channels int

Channel width of the spectral layers (the original design's width).

n_layers int

Number of spectral-conv blocks, by default 4 (the original design's fixed depth).

projection_hidden_channels int

Hidden width of the projection head's single hidden linear layer, by default 128 (the original design's fixed value).

split_complex_params bool

Passed through to ClassicSpectralConv2d. Set it when training this model with a moment-based optimizer such as Adam, whose state would otherwise be complex-valued; see that class for the full rationale. False by default, which keeps the original design's parameter layout.

GINO

Bases: BaseModel

GINO: Geometry-informed Neural Operator - learns a mapping between functions presented over arbitrary coordinate meshes. The model carries global integration through spectral convolution layers in an intermediate latent space, as described in [1]. Optionally enables a weighted output GNO.

Args:

Name Type Description
in_channels int

Feature dimension of input points. Determined by the problem.

out_channels int

Feature dimension of output points. Determined by the problem.

fno_n_modes tuple

Number of modes along each dimension to use in FNO. Default: (16, 16, 16)

fno_hidden_channels int

Hidden channels for use in FNO. Default: 64

fno_n_layers int

Number of layers in FNO. Default: 4

latent_feature_channels int

Number of channels in optional latent feature map. Default: None

projection_channel_ratio int

Ratio of pointwise projection channels to fno_hidden_channels. Default: 4

out_query_feature_channels int

Number of per-point features given at the output queries and concatenated to the output-GNO result before the projection, so the pointwise decoder sees each query's own features (e.g. its distance to a wall). Default: None (off)

gno_coord_dim int

Geometric dimension of input/output queries. Default: 3

in_gno_radius float

Radius in input space for GNO neighbor search. Default: 0.033

out_gno_radius float

Radius in output space for GNO neighbor search. Default: 0.033

fno_split_complex_params bool

Store the latent FNO's spectral weights as real/imaginary pairs rather than complex arrays. Default: False. Set this to train with Adam or another moment-based optimiser; see SpectralConv.

References

[1] : Li, Z., Kovachki, N., Choy, C., Li, B., Kossaifi, J., Otta, S., Nabian, M., Stadler, M., Hundt, C., Azizzadenesheli, K., Anandkumar, A. (2023) Geometry-Informed Neural Operator for Large-Scale 3D PDEs. NeurIPS 2023.

latent_embedding

latent_embedding(in_p: Any, ada_in: Any = None) -> Any

Lift the input onto the latent grid and apply the FNO blocks.

Args:

Name Type Description Default
in_p ndarray

latent-grid input of shape (batch, n_1, ..., n_k, in_channels + k)

ada_in ndarray

adaptive instance-normalization scalar of shape (fno_ada_in_dim,), used only when fno_norm == "ada_in", by default None

None

Returns:

Type Description
ndarray

latent embedding of shape (batch, fno_hidden_channels, n_1, ..., n_k)

encode

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

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

Split out of __call__ (which now just calls encode then decode) so a caller that needs to differentiate the decode step alone w.r.t. output_queries -- e.g. an AD-based physics-residual loss -- can call encode once and reuse its result across many decode calls, instead of recomputing the (comparatively expensive) encoder + latent FNO backbone for every derivative evaluation.

Args:

Name Type Description Default
input_geom ndarray

input domain coordinate mesh, shape (1, n_in, gno_coord_dim)

latent_queries ndarray

latent geometry on which to compute FNO latent embeddings, shape (1, n_gridpts_1, ..., n_gridpts_n, gno_coord_dim)

x ndarray

input function defined on the input domain, shape (batch, n_in, in_channels)

None
latent_features ndarray

optional feature map to concatenate onto latent embedding

None
ada_in ndarray

adaptive scalar instance parameter

None
neighbors_in dict

precomputed neighbor search result for the input GNO

None

Returns:

Name Type Description
latent_embed ndarray

shape (batch, n_1...n_k, fno_hidden_channels)

latent_queries ndarray

latent_queries with its leading singleton axis squeezed -- decode needs this same squeezed array (for its own y=...reshape(...) argument) and must not re-squeeze it.

decode

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

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

Args:

Name Type Description Default
latent_embed ndarray

first element of encode(...)'s return value.

latent_queries ndarray

second element of encode(...)'s return value -- already squeezed; do not pass the original (1, ...) array here.

output_queries ndarray | dict[ndarray]

points at which to query the final GNO layer to get output, shape (1, n_out, gno_coord_dim) per tensor.

neighbors_out dict

precomputed neighbor search result for the output GNO

None
output_query_features ndarray

per-query features of shape (1, n_out, out_query_feature_channels), concatenated to the output-GNO result before the projection; required exactly when out_query_feature_channels is set. Not supported with dict output_queries.

None

Returns:

Name Type Description
out ndarray | dict[ndarray]

Function over the output query coordinates

precompute_neighbors

precompute_neighbors(
    dataset: Any,
    output_n_points: int | None = None,
    log_dir: Any = None,
    split: str = "train",
) -> None

Precompute and cache neighbor search results for all samples.

Args:

Name Type Description Default
dataset DictDataset

The train or test dataset whose data_list will be updated in-place.

output_n_points int

Number of output query points. If None, all vertices are used.

None
log_dir str or Path

Directory to write per-sample neighbor count log files.

None
split str

Label for the dataset split. Default: "train".

'train'

WNO

Bases: BaseModel

N-dimensional Wavelet Neural Operator.

This keeps the original WNO2d recipe conceptually intact: lift once, apply repeated wavelet-plus-pointwise blocks, then project via hidden -> projection_hidden_channels -> out_channels.

The implementation remains dimension-agnostic by operating on channels-last tensors of shape (batch, spatial_1, ..., spatial_n, channels).

Args:

Name Type Description
in_channels int

Number of channels in the input function. When use_grid=True the model appends ndim positional grid channels internally, so the actual first Dense layer receives in_channels + ndim features.

out_channels int

Number of channels in the output function.

hidden_channels int

Width of each WNO block (number of channels throughout the operator).

n_layers int

Number of WNO blocks to stack.

level int

Number of wavelet decomposition levels per WNOBlock.

size int or Tuple[int, ...]

Spatial size(s) used by WaveletConv inside each block. Pass a single int for 1-D data or a tuple matching the spatial dimensions.

Other args:

Name Type Description
wavelet str

Wavelet name accepted by jaxwt (pywt-style, e.g. "db4"). Default: "db4"

mode str

Padding mode for the wavelet transform. Default: "symmetric"

wavelet_precision str

Precision mode for the wavelet convolution. Default: "fastest"

use_grid bool

When True, appends coordinate grid channels to the input before lifting. Set to False if the grid has already been appended externally. Default: True

grid_boundaries Tuple[Tuple[float, float], ...]

Per-dimension (start, end) for the coordinate grid. Default: ((0,1),)*ndim

padding int, float, or List

Spatial padding added before WNO blocks and removed after. Default: 0.0

padding_side str

Where to apply padding: "end" or "symmetric". Default: "end"

compute_dtype dtype

Dtype used for intermediate computations. Default: jnp.bfloat16

param_dtype dtype

Dtype used for model parameters, except WaveletConv's subband weights, which are always float32 regardless of this setting (see scirex.layers.blocks.wavelet_conv.WaveletConv for why). Default: jnp.float32

activation Callable

Non-linearity applied after each WNO block except the last. Default: mish

projection_activation Callable

Non-linearity applied between the two projection Dense layers. Default: nn.gelu

projection_hidden_channels int

Hidden width of the two-layer projection head. Default: 128

Examples:

>>> from scirex.models import WNO
>>> model = WNO(in_channels=1, out_channels=1, hidden_channels=64,
...             n_layers=4, level=3, size=128)

Transolver

Bases: BaseModel

Transolver: a Transformer solver built on physics attention.

Maps point-wise inputs on an irregular mesh or a structured 2D/3D grid to point-wise outputs. Every block attends over a small number of learned "slices" of the points (physics attention) instead of over all pairs of points, so the cost grows linearly with the number of points.

Input widths are inferred from the arrays passed to __call__; space_dim and fun_dim are accepted for parity with the reference implementation but are not used by the model.

Args:

Name Type Description
n_layers int

Number of Transolver blocks.

n_hidden int

Hidden width of the embedding and of every block.

n_head int

Number of attention heads; must divide n_hidden.

slice_num int

Number of slices (physical states) in the physics attention.

mlp_ratio int

Expansion factor of the hidden layer of each block's MLP.

out_dim int

Number of output channels, produced by the last block.

dropout_rate float

Dropout probability. It only acts when __call__ receives deterministic=False and a "dropout" RNG; otherwise __call__ warns that it has no effect.

act Callable

Activation function.

geometry str

"irregular" (point clouds), "structured_2d" (needs H and W) or "structured_3d" (needs H, W and D).

H int

Grid resolution for the structured geometries.

W int

Grid resolution for the structured geometries.

D int

Grid resolution for the structured geometries.

kernel int

Kernel size of the convolutions inside the physics attention on structured grids.

conv_init str

Initialisation of the structured-2D slice convolutions, "flax" or "torch" (PyTorch's default).

time_input bool

Whether __call__ takes a time T that is embedded and added to the hidden state.

unified_pos bool

Replace the input coordinates by their distance to a ref x ref (x ref in 3D) reference grid.

ref int

Number of reference points per axis when unified_pos is set.

concat_pos bool

With unified_pos, concatenate the distances to the input instead of replacing it.

grid_range tuple

(low, high) per spatial dimension of the reference grid; defaults to (0, 1) in every dimension.

layer_norm_epsilon float

Epsilon of every LayerNorm (Flax default 1e-6; PyTorch uses 1e-5).

Examples:

>>> import jax, jax.numpy as jnp
>>> from scirex.models import Transolver
>>> model = Transolver(space_dim=2, n_layers=2, n_hidden=16, n_head=2, slice_num=8)
>>> x = jnp.ones((2, 100, 2))  # (batch, points, coordinates)
>>> f = jnp.ones((2, 100, 1))  # (batch, points, input features)
>>> params = model.init(jax.random.PRNGKey(0), x, f)
>>> model.apply(params, x, f).shape
(2, 100, 1)
Notes

Based on Wu et al., "Transolver: A Fast Transformer Solver for PDEs on General Geometries" (ICML 2024), https://github.com/thuml/Transolver.

Factory and registry

get_model_jax builds a model from a config object whose model_arch names an architecture. available_models lists the accepted names.

get_model_jax

get_model_jax(
    config: Any, permissive: bool = False
) -> nn.Module

Returns an instantiated model for the given config

  • Reads the model to be used from config.model["model_arch"]
  • Passes the other keys of config.model to its constructor

Args:

Name Type Description Default
config Bunch or dict - like

configuration, must have config.model, a mapping with the key model_arch (a string, the name of the architecture) and the keyword arguments of the model

permissive bool, by default False

A config.model key the chosen architecture does not accept (a typo, or a key meant for a different architecture) raises ValueError. With permissive=True it instead warns and drops the key.

False

Returns:

Name Type Description
model Module

the instantiated module

available_models

available_models() -> list[str]

List the names accepted by get_model_jax, sorted.

Contains every built-in architecture (without importing it) plus any model registered by subclassing BaseModel.

Base class

Base class of every model. It provides checkpoint saving and loading (save_checkpoint, load_checkpoint, from_checkpoint). Subclass it to add an architecture.

BaseModel

Bases: Module

Base class for all models

This class has two main functionalities: * It monitors the creation of subclass, that are automatically registered for users to use by name using the library's config system * When a new instance of this class is created, the init call is intercepted so we can store the parameters used to create the instance. This makes it possible to save trained models along with their init parameters, and therefore load saved models easily.

Notes

Model can be versioned using the _version class attribute. This can be used for sanity check when loading models from checkpoints to verify the model hasn't been updated since.

get_state_dict

get_state_dict(params: Mapping[str, Any]) -> dict[str, Any]

Returns a state dict containing model params and version metadata.

Args:

Name Type Description
params dict

Flax parameter dict obtained from model.init(...)

Returns:

Type Description
dict

state dict with params bytes and metadata

load_state_dict

load_state_dict(
    params_target: Mapping[str, Any],
    state_dict: Mapping[str, Any],
) -> dict[str, Any]

Loads params from a state dict, with version checking.

Args:

Name Type Description
params_target dict

A reference param structure (e.g. from model.init) used to restore shape info

state_dict dict

state dictionary generated by get_state_dict

Returns:

Type Description
dict

restored Flax parameter dict

save_checkpoint

save_checkpoint(
    save_folder: str | Path,
    save_name: str,
    params: Mapping[str, Any],
) -> None

Saves the model params and init kwargs under the given folder and name.

Args:

Name Type Description
save_folder str or Path
save_name str
params dict

Flax parameter dict obtained from model.init(...)

load_checkpoint

load_checkpoint(
    save_folder: str | Path,
    save_name: str,
    params_target: Mapping[str, Any],
) -> dict[str, Any]

Loads and returns the model params from a checkpoint.

Args:

Name Type Description
save_folder str or Path
save_name str
params_target dict

A reference param structure used by flax.serialization.from_bytes

Returns:

Type Description
dict

restored Flax parameter dict, as JAX arrays ready for apply

from_checkpoint classmethod

from_checkpoint(
    save_folder: str | Path,
    save_name: str,
    params_target: Mapping[str, Any],
) -> tuple[BaseModel, dict[str, Any]]

Instantiates the model from a checkpoint and returns (instance, params).

Args:

Name Type Description
save_folder str or Path
save_name str
params_target dict

A reference param structure used by flax.serialization.from_bytes

Returns:

Type Description
tuple[BaseModel, dict]

(model instance, restored params dict)