scirex.layers
The building blocks the models are made of. Use them to assemble your own operator.
| Group | Names |
|---|---|
| Convolution | BaseSpectralConv, SpectralConv, WaveletConv |
| Blocks | FNOBlocks, WNOBlock, GNOBlock |
| Neighbour search | build_neighbor_graph, precompute_neighbors, kdtree_neighbor_search, edge_index_to_neighbors, neighbors_to_segments |
| Embeddings and MLP | GridEmbedding2D, GridEmbeddingND, ChannelMLP |
| Activations | cgelu, cselu, ctanh (for complex-valued data) |
Spectral and wavelet convolution
BaseSpectralConv
Bases: Module
Base Class for Spectral Convolutions
Use it when you want to build your own FNO-type Neural Operators
transform
Transforms an input x for a skip connection, by default just an identity map
If your function transforms the input then you should also implement this transform method so the skip connection can also work.
Typical usecases are:
- Your upsample or downsample the input in the Spectral conv: the skip connection has to be similarly scaled. This allows you to deal with it however you want (e.g. avoid aliasing)
- You perform a change of basis in your Spectral Conv, again, this needs to be applied to the skip connection too.
SpectralConv
Bases: BaseSpectralConv
SpectralConv implements the Spectral Convolution component of a Fourier layer.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
in_channels
|
int
|
|
|
out_channels
|
int
|
|
|
n_modes
|
int or int tuple
|
|
|
complex_data
|
bool
|
|
|
max_n_modes
|
int tuple or None
|
|
|
bias
|
bool
|
|
|
separable
|
bool
|
|
|
resolution_scaling_factor
|
float, list of float, or None
|
|
|
fno_block_precision
|
str
|
|
|
rank
|
float
|
|
|
factorization
|
str or None
|
|
|
implementation
|
(factorized, reconstructed)
|
|
'factorized'
|
enforce_hermitian_symmetry
|
bool
|
|
|
fixed_rank_modes
|
bool
|
|
|
decomposition_kwargs
|
dict or None
|
|
|
init_std
|
float or auto
|
|
|
fft_norm
|
str
|
|
|
split_complex_params
|
bool
|
Store the dense spectral weight as two real parameters, Set this when training with a moment-based optimiser. optax shapes its
moment estimates like the parameters, so a complex parameter produces a
complex Adam state, and Leaving it at False keeps the original parameter names, so existing checkpoints load unchanged. Supported for the dense factorization only. |
WaveletConv
Bases: Module
N-dimensional Wavelet Convolution layer following the WNO architecture.
The decomposition and reconstruction are delegated to jaxwt. The input
is transposed to NCHW once on entry, all wavelet-domain operations run in
NCHW (jaxwt's native layout), and the result is transposed back to NHWC
once on exit. Subband weights are applied with jnp.einsum so XLA can
lower the operation to a cuBLAS batched GEMM.
Operator blocks
FNOBlocks
Bases: Module
FNOBlocks implements a sequence of Fourier layers.
The Fourier layers are first described in [1], and the exact implementation details of the Fourier layer architecture are discussed in [2].
Args:
| Name | Type | Description |
|---|---|---|
in_channels
|
int
|
Number of input channels to Fourier layers |
out_channels
|
int
|
Number of output channels after Fourier layers |
n_modes
|
int or List[int]
|
Number of modes to keep along each dimension in frequency space. Can either be specified as an int (for all dimensions) or an iterable with one number per dimension |
resolution_scaling_factor
|
Optional[Union[Number, List[Number]]]
|
Factor by which to scale outputs for super-resolution, by default None |
n_layers
|
int
|
Number of Fourier layers to apply in sequence, by default 1 |
max_n_modes
|
int or List[int]
|
Maximum number of modes to keep along each dimension, by default None |
fno_block_precision
|
str
|
Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full" |
use_channel_mlp
|
bool
|
Whether to use an MLP layer after each FNO block, by default True |
channel_mlp_dropout
|
float
|
Dropout parameter for self.channel_mlp, by default 0 |
channel_mlp_expansion
|
float
|
Expansion parameter for self.channel_mlp, by default 0.5 |
non_linearity
|
callable
|
Nonlinear activation function to use between layers, by default nn.gelu |
stabilizer
|
Literal[tanh]
|
Stabilizing module to use between certain layers. Options: "tanh", None, by default None |
norm
|
Literal[ada_in, group_norm, instance_norm, batch_norm]
|
Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None |
ada_in_features
|
int
|
Number of features for adaptive instance norm above, by default None |
preactivation
|
bool
|
Whether to call forward pass with pre-activation, by default False If True, call nonlinear activation and norm before Fourier convolution If False, call activation and norms after Fourier convolutions |
fno_skip
|
str
|
Module to use for FNO skip connections. Options: "linear", "soft-gating", "identity", None, by default "linear" If None, no skip connection is added. See layers.skip_connections for more details |
channel_mlp_skip
|
str
|
Module to use for ChannelMLP skip connections. Options: "linear", "soft-gating", "identity", None, by default "soft-gating" If None, no skip connection is added. See layers.skip_connections for more details |
Other args:
| Name | Type | Description |
|---|---|---|
complex_data |
bool
|
Whether the FNO's data takes on complex values in space, by default False |
separable |
bool
|
Separable parameter for SpectralConv, by default False |
factorization |
str
|
Factorization parameter for SpectralConv. Options: None or "dense", and "tucker"; "cp" and "tt" are not supported, by default None |
rank |
float
|
Rank parameter for SpectralConv, by default 1.0 |
conv_module |
BaseConv
|
Module to use for convolutions in FNO block, by default SpectralConv |
fixed_rank_modes |
bool
|
Fixed_rank_modes parameter for SpectralConv, by default False |
implementation |
str
|
Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized" |
decomposition_kwargs |
dict
|
Kwargs for tensor decomposition in SpectralConv, by default dict() |
split_complex_params |
bool
|
Store each spectral weight as a real/imaginary pair of real parameters
rather than one complex parameter, by default False. Needed when
training with a moment-based optimiser; see
|
enforce_hermitian_symmetry |
bool
|
Whether to enforce Hermitian symmetry conditions when performing inverse FFT
for real-valued data. Only used when |
References
[1] Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895. [2] Kossaifi, J., Kovachki, N., Azizzadenesheli, K., Anandkumar, A. "Multi-Grid Tensorized Fourier Neural Operator for High-Resolution PDEs" (2024). TMLR 2024, https://openreview.net/pdf?id=AWiDlO63bH.
n_modes
property
writable
Tuple[int, ...]: Number of Fourier modes kept along each dimension.
forward_with_postactivation
forward_with_postactivation(
x: ndarray,
index: int = 0,
output_shape: tuple[int, ...] | None = None,
ada_in_embeddings: Sequence[ndarray] | None = None,
) -> jnp.ndarray
Fourier-layer forward pass applying the nonlinearity after the convolution and channel MLP (standard FNO ordering).
Args:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
input activation of shape (batch, channels, d1, ..., dN) |
|
index
|
int
|
index of the Fourier layer to apply, by default 0 |
0
|
output_shape
|
tuple of int
|
explicit output spatial shape for this block, by default None |
None
|
ada_in_embeddings
|
list of jnp.ndarray
|
adaptive instance-norm embeddings, by default None |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
output activation of the Fourier layer |
forward_with_preactivation
forward_with_preactivation(
x: ndarray,
index: int = 0,
output_shape: tuple[int, ...] | None = None,
ada_in_embeddings: Sequence[ndarray] | None = None,
) -> jnp.ndarray
Fourier-layer forward pass applying the nonlinearity (and norm) before the convolution (resnet-style preactivation ordering).
Args:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
input activation of shape (batch, channels, d1, ..., dN) |
|
index
|
int
|
index of the Fourier layer to apply, by default 0 |
0
|
output_shape
|
tuple of int
|
explicit output spatial shape for this block, by default None |
None
|
ada_in_embeddings
|
list of jnp.ndarray
|
adaptive instance-norm embeddings, by default None |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
output activation of the Fourier layer |
WNOBlock
Bases: Module
Generic channels-last WNO block matching the upstream structure.
Each block computes a wavelet operator plus a pointwise channel mixing term, then applies the non-linearity except for the last block.
GNOBlock
Bases: Module
Graph Neural Operator layer
It is a resolution-invariant operator that maps a function defined over one coordinate mesh to another defined over another coordinate mesh using a pointwise kernel integral that takes contributions from neighbors of distance 1 within a graph constructed via neighbor search with a specified radius. The exact implementation details of the GNO layer architecture are discussed in [1].
Optionally, if provided, the input and output queries can have a positional embedding applied using the argument pos_embedding.
The kernel integral computed in IntegralTransform computes one of: (a) \int_{A(x)} k(x, y) dy (b) \int_{A(x)} k(x, y) * f(y) dy (c) \int_{A(x)} k(x, y, f(y)) dy (d) \int_{A(x)} k(x, y, f(y)) * f(y) dy
Args:
| Name | Type | Description |
|---|---|---|
in_channels
|
int
|
Number of channels in input function. Only used if transform_type is (c) "nonlinear" or (d) "nonlinear_kernelonly" |
out_channels
|
int
|
Number of channels in output function |
coord_dim
|
int
|
Dimension of domain on which x and y are defined |
radius
|
float
|
Radius in which to search for neighbors |
weighting_fn
|
Callable
|
Optional squared-norm weighting function to use for Mollified GNO layer by default None. See scirex.layers.gno_weighting_functions for more details. |
reduction
|
Literal['sum', 'mean']
|
Whether to aggregate information from each neighborhood in the integral transform by summing ('sum') or averaging ('mean'), by default 'sum' |
Other args:
| Name | Type | Description |
|---|---|---|
transform_type |
str
|
Which integral transform to compute. Options: 'linear_kernelonly', 'linear', 'nonlinear_kernelonly', 'nonlinear'. The mapping is: 'linear_kernelonly' -> (a) 'linear' -> (b) [DEFAULT] 'nonlinear_kernelonly' -> (c) 'nonlinear' -> (d) If the input f is not given then (a) is computed by default independently of this parameter, by default 'linear' |
pos_embedding_type |
Type of positional embedding to use during the kernel integral transform.
Options: 'transformer', 'nerf', None. See
|
|
pos_embedding_channels |
int
|
Per-channel dimension of optional positional embedding to use, by default 32 |
pos_embedding_max_positions |
|
|
channel_mlp_layers |
List[int]
|
List of layer widths to dynamically construct LinearChannelMLP network to parameterize kernel k, by default None |
channel_mlp_non_linearity |
callable
|
Activation function for ChannelMLPLinear above, by default nn.gelu |
channel_mlp |
Module
|
ChannelMLP parametrizing the kernel k. Input dimension should be dim x + dim y or dim x + dim y + dim f. ChannelMLP should not be pointwise and should only operate across channels to preserve the discretization-invariance of the kernel integral. If you have more specific needs than the LinearChannelMLP, this argument allows you to pass your own Module to parameterize the kernel k. Default None, by default None |
use_torch_scatter_reduce |
bool
|
Has no effect: the grouped reductions always use the JAX segment reduction of the package. Kept for compatibility, by default False. |
use_open3d_neighbor_search |
bool
|
Whether to use open3d for fast 3D neighbor search, by default True.
open3d works on 3D coordinates only: for any other coordinate
dimension set this to False, otherwise setup raises an
|
References
[1] Zongyi Li, Kamyar Azizzadenesheli, Burigede Liu, Kaushik Bhattacharya, Anima Anandkumar (2020). "Neural Operator: Graph Kernel Network for Partial Differential Equations." ArXiV, https://arxiv.org/pdf/2003.03485.
Neighbor search and graphs
Helpers that build the radius graphs consumed by GNOBlock.
build_neighbor_graph
build_neighbor_graph(
source_pos: ndarray,
query_pos: ndarray,
radius: float,
strategy: str,
k_neighbors: int = 1,
max_edges: int | None = None,
max_num_neighbors: int = 32,
) -> np.ndarray
Build a bipartite graph and return a padded edge_index array.
Edge direction: source → query (info flows from source to query). Padding uses query index = N_qry (one past the last valid node).
Args:
| Name | Type | Description | Default |
|---|---|---|---|
source_pos
|
(N_src, D) coordinates of source nodes
|
|
|
query_pos
|
ndarray
|
|
|
radius
|
float
|
|
|
strategy
|
str
|
|
|
k_neighbors
|
int
|
|
1
|
max_edges
|
int | None
|
|
None
|
max_num_neighbors
|
cap on the number of source neighbours returned per
|
|
32
|
Returns:
| Name | Type | Description |
|---|---|---|
edge_index |
(2, max_edges) int32 - row 0 = src, row 1 = qry
|
|
precompute_neighbors
precompute_neighbors(
data: ndarray | ndarray,
queries: ndarray | ndarray,
radius: float,
return_norm: bool = False,
) -> dict[str, jnp.ndarray]
One fixed-radius search, ready to hand to a GNO layer as neighbors.
kdtree_neighbor_search followed by neighbors_to_segments.
Use this when the geometry does not change between samples: the KD-tree is
built on the CPU once, and every subsequent forward pass reuses the result
rather than repeating an O(n m) search inside the training step.
Raises:
| Type | Description |
|---|---|
ValueError
|
If some query point has no neighbor within |
kdtree_neighbor_search
kdtree_neighbor_search(
data: ndarray,
queries: ndarray,
radius: float,
return_norm: bool = False,
) -> dict[str, np.ndarray]
Lightning-fast O(N log M) neighbor search using Scipy's C++ KD-Tree. Run this eagerly on the CPU inside your data loader.
edge_index_to_neighbors
Convert a padded edge_index to the dict expected by IntegralTransform.
Padding edges must have edge_index[1] == num_query (dummy segment).
Returns:
| Type | Description |
|---|---|
dict with keys:
|
neighbors_index : (max_edges,) int - source indices per edge segment_ids : (max_edges,) int - query indices per edge counts : (num_query,) int - valid edges per query node |
neighbors_to_segments
CRS neighbor-search output -> the segment format the GNO layers consume.
NeighborSearch, native_neighbor_search and
kdtree_neighbor_search all return compressed row storage
(neighbors_index plus neighbors_row_splits), while
IntegralTransform indexes
edges by segment_ids and counts.
__call__ performs exactly
this conversion when it runs the search itself; this function is the same
conversion, exposed so that a caller with a fixed geometry can run the
search once up front and pass the result in as neighbors on every step
instead of repeating it.
Args:
| Name | Type | Description |
|---|---|---|
raw
|
dict
|
Must contain |
Returns:
| Type | Description |
|---|---|
dict
|
|
Examples:
>>> import numpy as np
>>> from scirex.layers.blocks.neighbor_search import (
... kdtree_neighbor_search,
... neighbors_to_segments,
... )
>>> points = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]], dtype=np.float32)
>>> neighbors = neighbors_to_segments(
... kdtree_neighbor_search(data=points, queries=points, radius=1.5)
... )
>>> [int(c) for c in neighbors["counts"]]
[2, 3, 2]
>>> [int(s) for s in neighbors["segment_ids"]]
[0, 0, 1, 1, 1, 2, 2]
Embeddings and MLP
GridEmbedding2D
Bases: Embedding
GridEmbedding2D applies a simple positional embedding as a regular 2D grid.
It expects inputs of shape (batch, channels, d_1, d_2)
Args:
| Name | Type | Description |
|---|---|---|
in_channels
|
int
|
number of channels in input. Fixed for output channel interface |
grid_boundaries
|
list
|
coordinate boundaries of input grid, by default [[0, 1], [0, 1]] |
grid
Grid generates 2D grid needed for pos encoding and caches the grid associated with MRU resolution
Args:
| Name | Type | Description |
|---|---|---|
spatial_dims
|
tuple
|
sizes of spatial resolution |
dtype
|
dtype
|
dtype to encode data. |
Returns:
| Type | Description |
|---|---|
ndarray
|
output grids to concatenate |
GridEmbeddingND
Bases: Module
GridEmbeddingND applies a simple positional embedding as a regular ND grid.
It expects inputs of shape (batch, channels, d_1, ..., d_n)
Args:
| Name | Type | Description |
|---|---|---|
in_channels
|
int
|
number of channels in input |
dim
|
int
|
dimensions of positional encoding to apply |
grid_boundaries
|
list
|
coordinate boundaries of input grid along each dim, by default [[0, 1], [0, 1]] |
grid
Grid generates ND grid needed for pos encoding and caches the grid associated with MRU resolution
Args:
| Name | Type | Description |
|---|---|---|
spatial_dims
|
tuple
|
Sizes of spatial resolution. |
dtype
|
dtype
|
dtype to encode data. |
Returns:
| Type | Description |
|---|---|
ndarray
|
output grids to concatenate |
ChannelMLP
Bases: Module
Multi-layer perceptron applied channel-wise across spatial dimensions.
ChannelMLP applies a series of 1D convolutions and nonlinearities to the channel dimension of input tensors, making it invariant to spatial resolution.
Uses Conv with kernel_size=1 (equivalent to PyTorch Conv1d with kernel_size=1), which performs linear transformations on the channel dimension while preserving spatial structure.
Args:
| Name | Type | Description |
|---|---|---|
in_channels
|
int
|
Number of input channels |
out_channels
|
int
|
Number of output channels. If None, defaults to in_channels. |
hidden_channels
|
int
|
Number of hidden channels in intermediate layers. If None, defaults to in_channels. |
n_layers
|
int
|
Number of linear layers in the MLP, by default 2 |
n_dim
|
int
|
Spatial dimension of input (unused but kept for compatibility), by default 2 |
non_linearity
|
callable
|
Nonlinear activation function to apply between layers, by default nn.gelu |
dropout
|
float
|
Dropout probability applied after each layer (except the last). If 0, no dropout is applied, by default 0.0 |
Complex-valued activations
cgelu
Complex GELU activation function Follows the formulation of CReLU from [1]. Applies GELU to real and imaginary parts of the input separately, then combine as complex number
Args:
| Name | Type | Description |
|---|---|---|
x
|
ndarray(dtype=complex)
|
pre-activation inputs |
References
[1] :
Trabelsi, C., et al. (2018). "Deep Complex Networks". ICLR 2018, https://openreview.net/pdf?id=H1T2hmZAb.
cselu
Complex-valued SELU activation Apply SELU to real and imag part of the input separately, then combine as complex number Args: x: complex array