diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d2_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d2_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..cf8d1fd43d21ba6244bbc099fe28cea20e53d3b9 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d2_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33a0ee1bb8a6a6b2229cca47d78d6dcafb189fec2c56fce1f9f5d768c52229b8 +size 1302 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d3_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d3_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..915fc3f67e3d6208c8c44c35be61e222666b66ca --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d3_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acb6b88051508ff82584b4d33726084120b44f0f705be6ef883120a3795e5ecb +size 1702 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d4_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d4_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..0dd1aa7bb327b763a2ae7647fd7e8982bb7ad3c9 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d4_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04da0d0714d27808b9cdefcada5290238b72a8e98c9f69442f7004ebe26a4c1f +size 2102 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d5_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d5_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..0218f4c12c4d97704978a48611c8b5a35e121b8e --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d5_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a60ec4ef444634164b236f68c0ddf57c566a362c774d4989a9f137241cb44786 +size 2502 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d6_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d6_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..74fced318792811a78b1ebf6c7a84176756936bc --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d6_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a98f20321763ffd92d5d1a6e28b9db12bf6a804848448727763f93c3cf39b306 +size 2902 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d7_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d7_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..3291b9d7e770d8c9c40cb64e7d4acfde5a236fd7 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d7_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c73487f13a2935f8d2749a9edaf9bc99a081510fc1b5aa93c3bb5b92234a694e +size 3302 diff --git a/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d8_c25.npz b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d8_c25.npz new file mode 100644 index 0000000000000000000000000000000000000000..b35c7add8adcb3b9fc0a779eb3fa18e9497e0993 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d8_c25.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7911eae1f4def9aea17937a0925749ef2743c75b9eff81e7f01fc0fac6586db3 +size 3702 diff --git a/sources/neuraloperator/neuralop/layers/fno_block.py b/sources/neuraloperator/neuralop/layers/fno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..2a92ecaceb71b773a88efdf32eb925ae1d67c5a0 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fno_block.py @@ -0,0 +1,498 @@ +from typing import List, Union + +import torch +from torch import nn +import torch.nn.functional as F + +from .channel_mlp import ChannelMLP +from .complex import CGELU, ctanh, ComplexValued +from .normalization_layers import AdaIN, InstanceNorm, BatchNorm +from .skip_connections import skip_connection +from .spectral_convolution import SpectralConv +from ..utils import validate_scaling_factor + + +Number = Union[int, float] + + +def _make_conv_bias(in_channels, out_channels, n_dim, kernel_size): + """Create the local convolutional bias term used alongside SpectralConv.""" + if kernel_size < 1: + raise ValueError(f"conv_bias_kernel must be >= 1, got {kernel_size}") + + if kernel_size == 1: + return skip_connection( + in_channels, + out_channels, + skip_type="linear", + n_dim=n_dim, + ) + + if n_dim > 3: + raise NotImplementedError( + "conv_bias_kernel > 1 is only implemented for 1D, 2D, and 3D FNO blocks." + ) + + conv_module = getattr(nn, f"Conv{n_dim}d") + return conv_module( + in_channels, + out_channels, + kernel_size=kernel_size, + padding="same", + bias=False, + ) + + +class FNOBlocks(nn.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]_. + + Parameters + ---------- + 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]]], optional + Factor by which to scale outputs for super-resolution, by default None + n_layers : int, optional + Number of Fourier layers to apply in sequence, by default 1 + max_n_modes : int or List[int], optional + Maximum number of modes to keep along each dimension, by default None + fno_block_precision : str, optional + Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full" + use_channel_mlp : bool, optional + Whether to use an MLP layer after each FNO block, by default True + channel_mlp_dropout : float, optional + Dropout parameter for self.channel_mlp, by default 0 + channel_mlp_expansion : float, optional + Expansion parameter for self.channel_mlp, by default 0.5 + non_linearity : torch.nn.F module, optional + Nonlinear activation function to use between layers, by default F.gelu + stabilizer : Literal["tanh"], optional + Stabilizing module to use between certain layers. Options: "tanh", None, by default None + norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + ada_in_features : int, optional + Number of features for adaptive instance norm above, by default None + preactivation : bool, optional + 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, optional + 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 + conv_bias_kernel : int, optional + Kernel size for the local convolutional bias term used when ``fno_skip="linear"``. + ``1`` preserves the default pointwise bias term, while larger kernels add a + local convolution alongside the global spectral convolution. Default: 1 + channel_mlp_skip : str, optional + 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 Parameters + ---------------- + complex_data : bool, optional + Whether the FNO's data takes on complex values in space, by default False + separable : bool, optional + Separable parameter for SpectralConv, by default False + factorization : str, optional + Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None + rank : float, optional + Rank parameter for SpectralConv, by default 1.0 + conv_module : BaseConv, optional + Module to use for convolutions in FNO block, by default SpectralConv + joint_factorization : bool, optional + Whether to factorize all spectralConv weights as one tensor, by default False + fixed_rank_modes : bool, optional + Fixed_rank_modes parameter for SpectralConv, by default False + implementation : str, optional + Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized" + decomposition_kwargs : dict, optional + Kwargs for tensor decomposition in SpectralConv, by default dict() + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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. + + 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. + """ + + def __init__( + self, + in_channels, + out_channels, + n_modes, + resolution_scaling_factor=None, + n_layers=1, + max_n_modes=None, + fno_block_precision="full", + use_channel_mlp=True, + channel_mlp_dropout=0, + channel_mlp_expansion=0.5, + non_linearity=F.gelu, + stabilizer=None, + norm=None, + norm_groups=1, + ada_in_features=None, + preactivation=False, + fno_skip="linear", + conv_bias_kernel=1, + channel_mlp_skip="soft-gating", + complex_data=False, + separable=False, + factorization=None, + rank=1.0, + conv_module=SpectralConv, + fixed_rank_modes=False, + implementation="factorized", + decomposition_kwargs=dict(), + enforce_hermitian_symmetry=True, + ): + super().__init__() + if isinstance(n_modes, int): + n_modes = [n_modes] + self._n_modes = n_modes + self.n_dim = len(n_modes) + + self.resolution_scaling_factor: Union[ + None, List[List[float]] + ] = validate_scaling_factor(resolution_scaling_factor, self.n_dim, n_layers) + + self.max_n_modes = max_n_modes + self.fno_block_precision = fno_block_precision + self.in_channels = in_channels + self.out_channels = out_channels + self.n_layers = n_layers + self.stabilizer = stabilizer + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.fno_skip = fno_skip + self.conv_bias_kernel = conv_bias_kernel + self.channel_mlp_skip = channel_mlp_skip + self.complex_data = complex_data + + self.use_channel_mlp = use_channel_mlp + self.channel_mlp_expansion = channel_mlp_expansion + self.channel_mlp_dropout = channel_mlp_dropout + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + self.ada_in_features = ada_in_features + self.enforce_hermitian_symmetry = enforce_hermitian_symmetry + + # apply real nonlin if data is real, otherwise CGELU + if self.complex_data: + self.non_linearity = CGELU + else: + self.non_linearity = non_linearity + + # One conv per layer. Only resolution_scaling_factor varies by layer index + self.convs = nn.ModuleList( + [ + conv_module( + self.in_channels, + self.out_channels, + self.n_modes, + # Per-layer scaling for super-resolution, or None if disabled + resolution_scaling_factor=( + self.resolution_scaling_factor[i] + if resolution_scaling_factor is not None + else None + ), + max_n_modes=max_n_modes, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + fno_block_precision=fno_block_precision, + decomposition_kwargs=decomposition_kwargs, + complex_data=complex_data, + # Only SpectralConv (and subclasses) accept enforce_hermitian_symmetry. Others ignore it + **( + {"enforce_hermitian_symmetry": enforce_hermitian_symmetry} + if issubclass(conv_module, SpectralConv) + else {} + ), + ) + for i in range(n_layers) + ] + ) + + if fno_skip is not None: + if fno_skip.lower() == "linear": + # FourCastNet v3-like local + global convolutions: the spectral + # path is global, while larger kernels give this bias term locality. + fno_skip_modules = [ + _make_conv_bias( + self.in_channels, + self.out_channels, + self.n_dim, + conv_bias_kernel, + ) + for _ in range(n_layers) + ] + else: + if conv_bias_kernel != 1: + raise ValueError( + "conv_bias_kernel can only differ from 1 when fno_skip='linear'." + ) + fno_skip_modules = [ + skip_connection( + self.in_channels, + self.out_channels, + skip_type=fno_skip, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + self.fno_skips = nn.ModuleList(fno_skip_modules) + else: + if conv_bias_kernel != 1: + raise ValueError( + "conv_bias_kernel can only differ from 1 when fno_skip='linear'." + ) + self.fno_skips = None + if self.complex_data and self.fno_skips is not None: + self.fno_skips = nn.ModuleList([ComplexValued(x) for x in self.fno_skips]) + + if self.use_channel_mlp: + self.channel_mlp = nn.ModuleList( + [ + ChannelMLP( + in_channels=self.out_channels, + hidden_channels=round(self.out_channels * channel_mlp_expansion), + dropout=channel_mlp_dropout, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + ) + if self.complex_data: + self.channel_mlp = nn.ModuleList( + [ComplexValued(x) for x in self.channel_mlp] + ) + if channel_mlp_skip is not None: + self.channel_mlp_skips = nn.ModuleList( + [ + skip_connection( + self.in_channels, + self.out_channels, + skip_type=channel_mlp_skip, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + ) + else: + self.channel_mlp_skips = None + if self.complex_data and self.channel_mlp_skips is not None: + self.channel_mlp_skips = nn.ModuleList( + [ComplexValued(x) for x in self.channel_mlp_skips] + ) + + # Each block will have 2 norms if we also use a ChannelMLP + self.n_norms = 2 + if norm is None: + self.norm = None + elif norm == "instance_norm": + self.norm = nn.ModuleList( + [InstanceNorm() for _ in range(n_layers * self.n_norms)] + ) + elif norm == "group_norm": + self.norm = nn.ModuleList( + [ + nn.GroupNorm(num_groups=norm_groups, num_channels=self.out_channels) + for _ in range(n_layers * self.n_norms) + ] + ) + + elif norm == "batch_norm": + self.norm = nn.ModuleList( + [ + BatchNorm(n_dim=self.n_dim, num_features=self.out_channels) + for _ in range(n_layers * self.n_norms) + ] + ) + + elif norm == "ada_in": + self.norm = nn.ModuleList( + [ + AdaIN(ada_in_features, out_channels) + for _ in range(n_layers * self.n_norms) + ] + ) + else: + raise ValueError( + f"Got norm={norm} but expected None or one of " + "[instance_norm, group_norm, batch_norm, ada_in]" + ) + + if self.complex_data and self.norm is not None: + self.norm = nn.ModuleList([ComplexValued(x) for x in self.norm]) + + def set_ada_in_embeddings(self, *embeddings): + """Sets the embeddings of each Ada-IN norm layers + + Parameters + ---------- + embeddings : tensor or list of tensor + if a single embedding is given, it will be used for each norm layer + otherwise, each embedding will be used for the corresponding norm layer + """ + if self.norm is not None: + if len(embeddings) == 1: + for norm in self.norm: + norm.set_embedding(embeddings[0]) + else: + for norm, embedding in zip(self.norm, embeddings): + norm.set_embedding(embedding) + + def forward(self, x, index=0, output_shape=None): + if self.preactivation: + return self.forward_with_preactivation(x, index, output_shape) + else: + return self.forward_with_postactivation(x, index, output_shape) + + def forward_with_postactivation(self, x, index=0, output_shape=None): + if self.fno_skips is not None: + x_skip_fno = self.fno_skips[index](x) + x_skip_fno = self.convs[index].transform(x_skip_fno, output_shape=output_shape) + + if self.use_channel_mlp and self.channel_mlp_skips is not None: + x_skip_channel_mlp = self.channel_mlp_skips[index](x) + x_skip_channel_mlp = self.convs[index].transform(x_skip_channel_mlp, output_shape=output_shape) + + if self.stabilizer == "tanh": + if self.complex_data: + x = ctanh(x) + else: + x = torch.tanh(x) + + x_fno = self.convs[index](x, output_shape=output_shape) + + if self.norm is not None: + x_fno = self.norm[self.n_norms * index](x_fno) + + x = x_fno + x_skip_fno if self.fno_skips is not None else x_fno + + if index < (self.n_layers - 1): + x = self.non_linearity(x) + + if self.use_channel_mlp: + if self.channel_mlp_skips is not None: + x = self.channel_mlp[index](x) + x_skip_channel_mlp + else: + x = self.channel_mlp[index](x) + + if self.norm is not None: + x = self.norm[self.n_norms * index + 1](x) + + if index < (self.n_layers - 1): + x = self.non_linearity(x) + + return x + + def forward_with_preactivation(self, x, index=0, output_shape=None): + # Apply non-linear activation (and norm) + # before this block's convolution/forward pass: + x = self.non_linearity(x) + + if self.norm is not None: + x = self.norm[self.n_norms * index](x) + + if self.fno_skips is not None: + x_skip_fno = self.fno_skips[index](x) + x_skip_fno = self.convs[index].transform(x_skip_fno, output_shape=output_shape) + + if self.use_channel_mlp and self.channel_mlp_skips is not None: + x_skip_channel_mlp = self.channel_mlp_skips[index](x) + x_skip_channel_mlp = self.convs[index].transform(x_skip_channel_mlp, output_shape=output_shape) + + if self.stabilizer == "tanh": + if self.complex_data: + x = ctanh(x) + else: + x = torch.tanh(x) + + x_fno = self.convs[index](x, output_shape=output_shape) + + x = x_fno + x_skip_fno if self.fno_skips is not None else x_fno + + if index < (self.n_layers - 1): + x = self.non_linearity(x) + + if self.norm is not None: + x = self.norm[self.n_norms * index + 1](x) + + if self.use_channel_mlp: + if self.channel_mlp_skips is not None: + x = self.channel_mlp[index](x) + x_skip_channel_mlp + else: + x = self.channel_mlp[index](x) + + return x + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + for i in range(self.n_layers): + self.convs[i].n_modes = n_modes + self._n_modes = n_modes + + def get_block(self, indices): + """Returns a sub-FNO Block layer from the jointly parametrized main block + + The parametrization of an FNOBlock layer is shared with the main one. + """ + if self.n_layers == 1: + raise ValueError( + "A single layer is parametrized, directly use the main class." + ) + + return SubModule(self, indices) + + def __getitem__(self, indices): + return self.get_block(indices) + + +class SubModule(nn.Module): + """Class representing one of the sub_module from the mother joint module + + Notes + ----- + This relies on the fact that nn.Parameters are not duplicated: + if the same nn.Parameter is assigned to multiple modules, + they all point to the same data, which is shared. + """ + + def __init__(self, main_module, indices): + super().__init__() + self.main_module = main_module + self.indices = indices + + def forward(self, x): + return self.main_module.forward(x, self.indices) diff --git a/sources/neuraloperator/neuralop/layers/fourier_continuation.py b/sources/neuraloperator/neuralop/layers/fourier_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..2309f1f310cbdcde2249cd1c5209eec5d9e9e1b8 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/fourier_continuation.py @@ -0,0 +1,453 @@ +import torch +import torch.nn as nn +import numpy as np +from numpy.polynomial.legendre import Legendre +import warnings +from pathlib import Path +import tensorly as tl + + +class FourierContinuation(nn.Module): + """Base class for Fourier Continuation implementations. + + Fourier Continuation is a technique for extending non-periodic functions to periodic + ones on larger domains, enabling the use of spectral methods for differentiation + and solving PDEs. This base class provides the common interface and methods for + different Fourier Continuation approaches (Legendre polynomials, Gram matrices, etc.). + + This allows spectral methods such as spectral differentiation to be applied to + non-periodic functions by working on the extended periodic domain. + """ + + def __init__(self, d=5, n_additional_pts=50): + """ + Initialize FourierContinuation with specified parameters. + + Parameters + ---------- + d : int, optional + Number of matching points on the left and right boundaries, by default 5 + n_additional_pts : int, optional + Number of additional points to add for continuation, by default 50 + """ + super().__init__() + + self.d = d + self.n_additional_pts = n_additional_pts + + def extend(self, x, dim): + """ + Extend tensor along specified dimensions using Fourier Continuation. + + This method extends non-periodic functions to periodic ones by adding + continuation points on both sides of the specified dimensions using + TensorLy's multi_mode_dot for efficient multi-dimensional extension. + + Parameters + ---------- + x : torch.Tensor + Input tensor to extend. Must have at least 2*d points along each + dimension to be extended (for boundary value extraction). + dim : int or tuple of ints, + Dimensions along which to extend: + - If int: extend along the last dim axes (e.g. dim=2 extends along the last 2 axes) + - If tuple: extend along the specified axes (supports negative indexing) + + Returns + ------- + torch.Tensor + Extended tensor with additional points added along specified dimensions. + Each extended dimension will have n_additional_pts more points than the input. + """ + + # Convert input dimension(s) to list of axes to extend along: + if isinstance(dim, int): + # If dim is an integer n, extend along the last n dimensions + axes = list(range(-dim, 0)) + else: + # If dim is a tuple, extend along those specific dimensions + axes = list(dim) + + # Convert negative axes to positive indices + axes = [a if a >= 0 else x.ndim + a for a in axes] + + # Create extension matrices for each axis + # Each matrix maps input tensor along one axis to extended tensor + extension_matrices = [] # List of torch tensors, each shape: (extended_size, original_size) + modes = [] # List of axis indices to extend along + + for axis in axes: + # Get the extension matrix for this axis + ext_mat = self._get_extension_matrix_for_axis(x, axis) + extension_matrices.append(ext_mat) + modes.append(axis) + + # Use TensorLy's multi_mode_dot to apply all extensions simultaneously + # Input: x (original shape), matrices (list of extension matrices), modes (axis indices) + # Output: extended tensor with shape modified along specified axes + return tl.tenalg.multi_mode_dot(x, extension_matrices, modes=modes) + + def _get_extension_matrix_for_axis(self, x, axis): + """ + Get the extension matrix for a specific axis using Fourier continuation. + + This method creates a matrix that maps the input tensor along one axis + to the extended tensor using the Fourier continuation approach. + + Parameters + ---------- + x : torch.Tensor + Input tensor + axis : int + Axis for which to get the extension matrix + + Returns + ------- + torch.Tensor + Extension matrix for the specified axis + """ + + axis_size = x.shape[axis] # Original size along the axis to extend + extended_size = axis_size + self.n_additional_pts # Final size after extension + c = self.n_additional_pts // 2 # Number of continuation points on each side + + # Create the extension matrix, which maps the input to the extended output + # Shape: (extended_size, axis_size) where extended_size = axis_size + n_additional_pts + ext_mat = torch.zeros((extended_size, axis_size), dtype=x.dtype, device=x.device) + + # Place identity matrix in the middle (original values) + ext_mat[c:c+axis_size, :] = torch.eye(axis_size, dtype=x.dtype, device=x.device) + + # Get the extension matrix for boundary points + ext_mat_boundary = self.ext_mat.to(dtype=x.dtype, device=x.device) + + # Fill in the continuation regions + if c > 0: + # The extension matrix maps [right_bnd, left_bnd] to continuation values + # where ext_mat_boundary has shape (n_additional_pts, 2*d) + # and maps [right_bnd, left_bnd] to [left_cont, right_cont] + + # Left continuation: use the last c rows of the extension matrix + # These map [right_bnd, left_bnd] to left continuation values + ext_mat[:c, :self.d] = ext_mat_boundary[-c:, self.d:] # right_bnd -> left_cont + ext_mat[:c, axis_size-self.d:] = ext_mat_boundary[-c:, :self.d] # left_bnd -> left_cont + + # Right continuation: use the first c rows of the extension matrix + # These map [right_bnd, left_bnd] to right continuation values + ext_mat[-c:, :self.d] = ext_mat_boundary[:c, self.d:] # right_bnd -> right_cont + ext_mat[-c:, axis_size-self.d:] = ext_mat_boundary[:c, :self.d] # left_bnd -> right_cont + + return ext_mat + + def forward(self, x, dim): + """ + Forward pass that calls the extend method. + + This method extends non-periodic functions to periodic ones by adding + continuation points on both sides of the specified dimensions. + + Parameters + ---------- + x : torch.Tensor + Input tensor to extend. Must have at least 2*d points along each + dimension to be extended (for boundary value extraction). + dim : int or tuple of ints, + Dimensions along which to extend: + - If int: extend along the last dim axes (e.g. dim=2 extends along the last 2 axes) + - If tuple: extend along the specified axes (supports negative indexing) + + Returns + ------- + torch.Tensor + Extended tensor with additional points added along specified dimensions. + Each extended dimension will have n_additional_pts more points than the input. + """ + return self.extend(x, dim) + + def restrict(self, x, dim): + """ + Remove Fourier continuation extension points to restore original domain size. + + This method reverses the extension process by removing the continuation points + that were added during Fourier continuation. + + It removes n_additional_pts//2 points from each side of the specified dimensions. + + Parameters + ---------- + x : torch.Tensor + Extended tensor from Fourier continuation. Must have been extended using + the same n_additional_pts parameter as this instance. + dim : int or tuple of ints + Dimensions along which to restrict: + - If int: restrict along the last dim axes (e.g. dim=2 restricts along the last 2 axes) + - If tuple: restrict along the specified axes (supports negative indexing) + + Returns + ------- + torch.Tensor + Tensor with original domain size. Each restricted dimension will have + n_additional_pts fewer points than the input (n_additional_pts//2 removed + from each side). + """ + + # Convert input dimension(s) to list of axes to restrict along: + if isinstance(dim, int): + # If dim is an integer n, restrict along the last n dimensions + axes = list(range(-dim, 0)) + else: + # If dim is a tuple, restrict along those specific dimensions + axes = list(dim) + + # Convert negative axes to positive for easier handling + axes = [a if a >= 0 else x.ndim + a for a in axes] + + # Create slices to restrict along each axis + c = self.n_additional_pts // 2 # Number of points to remove from each side + slices = [slice(None)] * x.ndim + + for axis in axes: + # For each axis to restrict, remove c points from each side + slices[axis] = slice(c, -c) + + # Return restricted tensor with reduced size along specified axes + return x[tuple(slices)] + + +class FCLegendre(FourierContinuation): + """Fourier Continuation using Legendre polynomials. + + This class implements Fourier Continuation using Legendre polynomial basis functions + to extend non-periodic functions to periodic ones on larger domains. The method works + by fitting Legendre polynomials to boundary values and using them to compute + continuation values that make the extended function periodic. + + Legendre polynomials P_n(x) are orthogonal polynomials with weight w=1 on [-1, 1]: + ∫_{-1}^{1} P_j(x) P_k(x) dx = 2/(2j+1) δ_{jk} + + The extension process: + 1. Extract d boundary points from each end of the input signal + 2. Fit a linear combination of Legendre polynomials to these boundary values + 3. Use the fitted polynomials to compute continuation values + 4. Concatenate the continuation with the original signal + + """ + + def __init__(self, d=5, n_additional_pts=50, rcond=1e-15): + """ + Initialize FCLegendre with specified parameters. + + Parameters + ---------- + d : int + Number of matching points on the left and right boundaries + Related to the degree of the Legendre polynomial basis used for extension (degree 2d-1). + By default 6 + n_additional_pts : int + Number of additional points to add for continuation, by default 50 + Lower values of d typically require more n_additional_pts points + rcond : float, optional + Cutoff for small singular values for the pseudoinverse of the extension matrix + Singular values less than or equal to rcond * largest_singular_value are set to zero + This can be adjusted for numerical stability, especially for larger values of d. + A smaller value can lead to more stable results, but may also introduce numerical errors. + By default 1e-15 (same as numpy default for np.linalg.pinv) + """ + super().__init__(d, n_additional_pts) + + self.rcond = rcond + self.compute_extension_matrix() + + def compute_extension_matrix(self): + """ + Compute the extension matrix using Legendre polynomials. + + This method constructs the matrix that maps boundary values to continuation + values using Legendre polynomial basis functions. + """ + + total_points = 2 * self.d + self.n_additional_pts + + # Use [-1,1] interval where Legendre polynomials are orthogonal + a, b = -1.0, 1.0 + + # Generate uniform grid on [-1,1] with total_points points + h = (b - a) / (total_points - 1) + full_grid = a + h * np.arange(total_points, dtype=np.float64) + + # Extract points for fitting (d points from each end) + fit_grid = np.concatenate((full_grid[0 : self.d], full_grid[-self.d :]), 0) + + # Extract points for extension (middle points) + extension_grid = full_grid[self.d : -self.d] + + # Construct normalized Legendre polynomials + # numpy.polynomial.legendre.Legendre are orthogonal but not normalized on [-1,1]: + # ∫_{-1}^{1} P_j(x) P_k(x) dx = 2/(2j+1) δ_{jk} + # Normalization can improve numerical stability for larger values of d + I = np.eye(2 * self.d, dtype=np.float64) + polynomials = [ + np.sqrt((2 * j + 1) / 2) * Legendre(I[j, :]) for j in range(2 * self.d) + ] + + # Evaluate normalized polynomials on the fit and extension grids + X = np.stack([P(fit_grid) for P in polynomials], axis=1) # Fit grid evaluations + Q = np.stack([P(extension_grid) for P in polynomials], axis=1) # Extension grid evaluations + + # Compute extension matrix using pseudoinverse + ext_mat = Q @ np.linalg.pinv(X, rcond=self.rcond) + + # Register matrices as persistent buffers for the module + self.register_buffer("ext_mat", torch.from_numpy(ext_mat)) + self.register_buffer("ext_mat_T", self.ext_mat.T.clone()) + + return self.ext_mat + + +class FCGram(FourierContinuation): + """Fourier Continuation using Gram matrices. + + This class implements the FC-Gram algorithm described in Section 3.1 of: + Amlani, F., & Bruno, O. P. (2016). An FC-based spectral solver for + elastodynamic problems in general three-dimensional domains. + Journal of Computational Physics, 307, 333-354. + + The algorithm uses pre-computed Gram matrices (ArQr, AlQl) to perform + Fourier Continuation of discretized functions. + + If the required pre-computed FCGram matrices are not available, they + can be computed using the MATLAB code from the FCGram repository + https://github.com/neuraloperator/FCGram/ + and then saved to the appropriate matrices_path directory in .npz format. + + The matrices are: + - ArQr: Right boundary continuation matrix + - AlQl: Left boundary continuation matrix + + The matrices are saved in the .npz format. + + """ + + def __init__(self, d=5, n_additional_pts=50, matrices_path=None): + """ + Initialize FCGram with specified parameters. + + Parameters + ---------- + d : int + Number of matching points on the left and right boundaries + Degree of the Gram polynomial d + Typically between 3 and 8 (precomputed matrices available for d in {2,3,4,5,6,7,8}). + d=3,4,5,6 are typically good choices, by default 6. + n_additional_pts : int + Number of continuation points. By default 50. + Adds n_additional_pts//2 points on each side of the input signal. + Precomputed matrices available only for n_additional_pts = 50. + Unlike for FCLegendre, it is usually not necessary to change this parameter. + matrices_path : str or Path, optional + Path to directory containing FCGram matrices. + If None, uses the directory containing this file, by default None + """ + super().__init__(d, n_additional_pts) + + if self.n_additional_pts % 2 == 1: + warnings.warn("n_additional_pts must be even, rounding down.", UserWarning) + self.n_additional_pts -= 1 + + self.c = int(self.n_additional_pts // 2) + + if matrices_path is None: + self.matrices_path = Path(__file__).parent / "fcgram_matrices" + else: + self.matrices_path = Path(matrices_path) + + # Load pre-computed FCGram matrices + self.load_matrices() + + def _get_extension_matrix_for_axis(self, x, axis): + """ + Get the extension matrix for a specific axis using FC-Gram algorithm. + + This method creates a matrix that maps the input tensor along one axis + to the extended tensor using pre-computed Gram matrices. + + Parameters + ---------- + x : torch.Tensor + Input tensor + axis : int + Axis for which to get the extension matrix + + Returns + ------- + torch.Tensor + Extension matrix for the specified axis + """ + axis_size = x.shape[axis] + extended_size = axis_size + self.n_additional_pts + c = self.n_additional_pts // 2 + + # Create the extension matrix + ext_mat = torch.zeros((extended_size, axis_size), dtype=x.dtype, device=x.device) + + # Place identity matrix in the middle (original values) + ext_mat[c:c+axis_size, :] = torch.eye(axis_size, dtype=x.dtype, device=x.device) + + # Get pre-computed Gram matrices + AlQl = self.AlQl.to(dtype=x.dtype, device=x.device) + ArQr = self.ArQr.to(dtype=x.dtype, device=x.device) + + # Fill in the continuation regions + if c > 0: + # Left continuation: map left boundary to left continuation + ext_mat[:c, : self.d] = AlQl[:c, :] + + # Right continuation: map right boundary to right continuation + ext_mat[-c:, axis_size - self.d :] = ArQr[:c, :] + + return ext_mat + + def load_matrices(self): + """ + Load the pre-computed FCGram matrices from .npz files. + + This method loads the pre-computed Gram matrices required for the FC-Gram + algorithm. The matrices are stored in .npz format and contain the optimized + continuation matrices for the specified (d, c) parameter combination. + + The loaded matrices are: + - ArQr: Right boundary continuation matrix + - AlQl: Left boundary continuation matrix + + These matrices are registered as PyTorch buffers so they are automatically + moved to the correct device (CPU/GPU) when the module is moved. + + Raises + ------ + FileNotFoundError + If the required .npz file is not found in the matrices_path directory. + The file should be named 'FCGram_data_d{d}_c{c}.npz' where c = n_additional_pts // 2. + + Note + ---- + If the required matrices are not available, they can be computed using the + MATLAB code from the FCGram repository: + https://github.com/neuraloperator/FCGram/ + + The computed matrices should be saved in .npz format in the matrices_path + directory with the correct naming convention. + """ + filepath = self.matrices_path / f"FCGram_data_d{self.d}_c{self.c}.npz" + + if not filepath.exists(): + raise FileNotFoundError( + f"FCGram matrices not found at {filepath}. \n" + f"Please ensure the .npz file exists with d={self.d}, c={self.c}." + ) + + # Load matrices from .npz file + npz_data = np.load(str(filepath)) + + # Extract matrices, convert to torch tensors, and register as buffers so they are moved to GPU + self.register_buffer("ArQr", torch.from_numpy(npz_data["ArQr"])) + self.register_buffer("AlQl", torch.from_numpy(npz_data["AlQl"])) diff --git a/sources/neuraloperator/neuralop/layers/gno_block.py b/sources/neuraloperator/neuralop/layers/gno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..254b100598cca74b71e1d730acf0cde1419acceb --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/gno_block.py @@ -0,0 +1,250 @@ +from typing import List, Literal, Optional, Callable + +import torch +from torch import nn +import torch.nn.functional as F + +from .channel_mlp import LinearChannelMLP +from .integral_transform import IntegralTransform +from .neighbor_search import NeighborSearch +from .embeddings import SinusoidalEmbedding + + +class GNOBlock(nn.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 + + Parameters + ---------- + 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 + Optional squared-norm weighting function to use for Mollified GNO layer + by default None. See neuralop.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 Parameters + ---------------- + transform_type : str, optional + 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: literal {'transformer', 'nerf'} | None, optional + Type of positional embedding to use during the kernel integral transform. + Options: 'transformer', 'nerf', None. See `neuralop.layers.embeddings.SinusoidalEmbedding` for more details, by default 'transformer' + pos_embedding_channels : int, optional + Per-channel dimension of optional positional embedding to use, by default 32 + pos_embedding_max_positions: int, optional + `max_positions` parameter for SinusoidalEmbedding of type `'transformer'`. If + `pos_embedding_type != 'transformer'`, this value is not used, by default 10000 + channel_mlp_layers : List[int], optional + List of layer widths to dynamically construct + LinearChannelMLP network to parameterize kernel k, by default None + channel_mlp_non_linearity : torch.nn function, optional + Activation function for ChannelMLPLinear above, by default F.gelu + channel_mlp : nn.Module, optional + 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, optional + Whether to use torch-scatter to perform grouped reductions in the IntegralTransform. + If False, uses native Python reduction in neuralop.layers.segment_csr, by default True + + .. warning:: + + torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch, + so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency` + for more information. + use_open3d_neighbor_search : bool, optional + Whether to use open3d for fast 3d neighbor search, by default True. + + .. note :: + If the coordinates provided are not 3D, the GNOBlock automatically + uses PyTorch native fallback neighbor search. + + Examples + -------- + ``` + >>> gno = GNOBlock(in_channels=2, out_channels=12, coord_dim=3, radius=0.035) + + >>> gno + GNOBlock( + (pos_embedding): SinusoidalEmbedding() + (neighbor_search): NeighborSearch() + (integral_transform): IntegralTransform( + (channel_mlp): LinearChannelMLP( + (fcs): ModuleList( + (0): Linear(in_features=384, out_features=128, bias=True) + (1): Linear(in_features=128, out_features=256, bias=True) + (2): Linear(in_features=256, out_features=128, bias=True) + (3): Linear(in_features=128, out_features=12, bias=True) + ) + ) + ) + ) + ``` + + 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. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + coord_dim: int, + radius: float, + transform_type="linear", + weighting_fn: Optional[Callable] = None, + reduction: Literal["sum", "mean"] = "sum", + pos_embedding_type: str = "transformer", + pos_embedding_channels: int = 32, + pos_embedding_max_positions: int = 10000, + channel_mlp_layers: List[int] = [128, 256, 128], + channel_mlp_non_linearity=F.gelu, + channel_mlp: nn.Module = None, + use_torch_scatter_reduce: bool = True, + use_open3d_neighbor_search: bool = True, + ): + super().__init__() + + self.in_channels = in_channels + self.out_channels = out_channels + self.coord_dim = coord_dim + + self.radius = radius + + # Apply sinusoidal positional embedding + self.pos_embedding_type = pos_embedding_type + if self.pos_embedding_type in ["nerf", "transformer"]: + self.pos_embedding = SinusoidalEmbedding( + in_channels=coord_dim, + num_frequencies=pos_embedding_channels, + embedding_type=pos_embedding_type, + max_positions=pos_embedding_max_positions, + ) + else: + self.pos_embedding = None + + # Create in-to-out nb search module + if use_open3d_neighbor_search: + assert self.coord_dim == 3, f"Error: open3d is only designed for 3d data, \ + GNO instantiated for dim={coord_dim}" + self.neighbor_search = NeighborSearch( + use_open3d=use_open3d_neighbor_search, return_norm=weighting_fn is not None + ) + + # create proper kernel input channel dim + if self.pos_embedding is None: + # x and y dim will be coordinate dim if no pos embedding is applied + kernel_in_dim = self.coord_dim * 2 + kernel_in_dim_str = "dim(y) + dim(x)" + else: + # x and y dim will be embedding dim if pos embedding is applied + kernel_in_dim = self.pos_embedding.out_channels * 2 + kernel_in_dim_str = "dim(y_embed) + dim(x_embed)" + + if transform_type == "nonlinear" or transform_type == "nonlinear_kernelonly": + kernel_in_dim += self.in_channels + kernel_in_dim_str += " + dim(f_y)" + + if channel_mlp is not None: + assert channel_mlp.in_channels == kernel_in_dim, f"Error: expected ChannelMLP to take\ + input with {kernel_in_dim} channels (feature channels={kernel_in_dim_str}),\ + got {channel_mlp.in_channels}." + assert channel_mlp.out_channels == out_channels, f"Error: expected ChannelMLP to have\ + {out_channels=} but got {channel_mlp.in_channels=}." + channel_mlp = channel_mlp + + elif channel_mlp_layers is not None: + if channel_mlp_layers[0] != kernel_in_dim: + channel_mlp_layers = [kernel_in_dim] + channel_mlp_layers + if channel_mlp_layers[-1] != self.out_channels: + channel_mlp_layers.append(self.out_channels) + channel_mlp = LinearChannelMLP(layers=channel_mlp_layers, non_linearity=channel_mlp_non_linearity) + + # Create integral transform module + self.integral_transform = IntegralTransform( + channel_mlp=channel_mlp, + transform_type=transform_type, + use_torch_scatter=use_torch_scatter_reduce, + weighting_fn=weighting_fn, + reduction=reduction, + ) + + def forward(self, y, x, f_y=None): + """Compute a GNO neighbor search and kernel integral transform. + + Parameters + ---------- + y : torch.Tensor of shape [n, d1] + n points of dimension d1 specifying + the space to integrate over. + If batched, these must remain constant + over the whole batch so no batch dim is needed. + x : torch.Tensor of shape [m, d1], default None + m points of dimension d1 over which the + output function is defined. Must share domain + with y + f_y : torch.Tensor of shape [batch, n, d2] or [n, d2], default None + Function to integrate the kernel against defined + on the points y. The kernel is assumed diagonal + hence its output shape must be d3 for the transforms + (b) or (d). If None, (a) is computed. + + Returns + ------- + out_features : torch.Tensor of shape [batch, m, d3] or [m, d3] + Output function given on the points x. + d4 is the output size of the kernel k. + """ + + neighbors_dict = self.neighbor_search(data=y, queries=x, radius=self.radius) + + if self.pos_embedding is not None: + y_embed = self.pos_embedding(y) + x_embed = self.pos_embedding(x) + else: + y_embed = y + x_embed = x + + out_features = self.integral_transform( + y=y_embed, x=x_embed, neighbors=neighbors_dict, f_y=f_y + ) + + return out_features diff --git a/sources/neuraloperator/neuralop/layers/gno_weighting_functions.py b/sources/neuraloperator/neuralop/layers/gno_weighting_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f69fa920608a1914c572c8e3ebdfb18a059dfa --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/gno_weighting_functions.py @@ -0,0 +1,93 @@ +from functools import partial +import torch + + +def bump_cutoff(x, radius=1.0, scale=1.0, eps=1e-7): + """ + Bump cutoff function with exponential decay. + + Formula: w(x) = scale * e * exp(-1/(1-d² + ε)) + where d = x/radius, x ∈ [0, radius], and ε is a small constant for numerical stability. + """ + out = x.clip(0.0, radius) / radius + out = -1 / ((1 - out**2) + eps) + return out.exp() * torch.e * scale + + +def half_cos_cutoff(x, radius=1.0, scale=1.0): + """ + Half-cosine cutoff function with smooth decay. + + Formula: w(x) = scale * (0.5 * cos(π * d) + 0.5) + where d = x/radius, x ∈ [0, radius]. + """ + x = x / radius + return scale * (0.5 * torch.cos(torch.pi * x) + 0.5) + + +def quadr_cutoff(x, radius=1.0, scale=1.0): + """ + Quadratic cutoff function with piecewise definition. + + Formula: w(x) = scale * {1 - 2d², if d < 0.5 + {2(1 - d)², if d ≥ 0.5 + where d = x/radius, x ∈ [0, radius]. + """ + x = x / radius + left = 1 - 2 * x**2 + right = 2 * (1 - x) ** 2 + return scale * torch.where(x < 0.5, left, right) + + +def quartic_cutoff(x, radius=1.0, scale=1.0): + """ + Quartic cutoff function with fourth-order polynomial. + + Formula: w(x) = (scale/radius⁴) * x⁴ - (2*scale/radius²) * x² + scale + where d = x/radius, x ∈ [0, radius]. + """ + a = scale / radius**4 + c = -2 * scale / radius**2 + return a * x**4 + c * x**2 + scale + + +def octic_cutoff(x, radius=1.0, scale=1.0): + """ + Octic cutoff function with eighth-order polynomial. + + Formula: w(x) = scale * (-3d⁸ + 8d⁶ - 6d⁴ + 1) + where d = x/radius, x ∈ [0, radius]. + """ + x = x / radius + return scale * (-3 * x**8 + 8 * x**6 - 6 * x**4 + 1) + + +WEIGHTING_FN_REGISTRY = { + "bump": bump_cutoff, + "half_cos": half_cos_cutoff, + "quadr": quadr_cutoff, + "quartic": quartic_cutoff, + "octic": octic_cutoff, +} + + +def dispatch_weighting_fn(weight_function_name: str, sq_radius: float, scale: float): + """ + Select a GNO weighting function for use in output GNO + of a Mollified Graph Neural Operator-based model. See [1]_ (add later) + + Parameters + ---------- + weight_function_name : str Literal + name of weighting function to use, keyed to ``WEIGHTING_FN_REGISTRY`` above + sq_radius : float + squared radius of GNO neighborhoods for Nyström approximation + scale : float + factor by which to scale all weights + """ + base_func = WEIGHTING_FN_REGISTRY.get(weight_function_name) + if base_func is None: + raise NotImplementedError( + f"weighting function should be one of {list(WEIGHTING_FN_REGISTRY.keys())}, got {weight_function_name}" + ) + return partial(base_func, radius=sq_radius, scale=scale) diff --git a/sources/neuraloperator/neuralop/layers/integral_transform.py b/sources/neuraloperator/neuralop/layers/integral_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..2db8488213c5a1791f29d9dd297809982bb2b463 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/integral_transform.py @@ -0,0 +1,227 @@ +import torch +from torch import nn +import torch.nn.functional as F + +from .channel_mlp import LinearChannelMLP +from .segment_csr import segment_csr + + +class IntegralTransform(nn.Module): + """Integral Kernel Transform (GNO). + + It computes one of the following: + (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 + + x : Points for which the output is defined + + y : Points for which the input is defined + A(x) : A subset of all points y (depending on\ + each x) over which to integrate + + k : A kernel parametrized as a MLP (LinearChannelMLP) + + f : Input function to integrate against given\ + on the points y + + If f is not given, a transform of type (a) + is computed. Otherwise transforms (b), (c), + or (d) are computed. The sets A(x) are specified + as a graph in CRS format. + + Parameters + ---------- + channel_mlp : torch.nn.Module, optional + MLP parametrizing the kernel k. Input dimension + should be dim x + dim y or dim x + dim y + dim f. + MLP should not be pointwise and should only operate across + channels to preserve the discretization-invariance of the + kernel integral, by default None + channel_mlp_layers : list, optional + List of layers sizes speficing a MLP which + parametrizes the kernel k. The MLP will be + instansiated by the LinearChannelMLP class, by default None + channel_mlp_non_linearity : callable, optional + Non-linear function used to be used by the + LinearChannelMLP class, by default F.gelu. Only used if channel_mlp_layers is + given and channel_mlp is None, by default torch.nn.functional.gelu + transform_type : str, optional + Which integral transform to compute. Options: 'linear_kernelonly', 'linear', 'nonlinear_kernelonly', 'nonlinear'. + The mapping is: + 'linear_kernelonly' -> (a) + 'linear' -> (b) + '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' + use_torch_scatter : bool, optional + Whether to use torch-scatter to perform grouped reductions in the IntegralTransform. + If False, uses native Python reduction in neuralop.layers.segment_csr, by default True + + .. warning:: + + torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch, + so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency` + for more information. + """ + + def __init__( + self, + channel_mlp=None, + channel_mlp_layers=None, + channel_mlp_non_linearity=F.gelu, + transform_type="linear", + weighting_fn=None, + reduction="sum", + use_torch_scatter=True, + ): + super().__init__() + + assert channel_mlp is not None or channel_mlp_layers is not None + + self.reduction = reduction + self.transform_type = transform_type + self.use_torch_scatter = use_torch_scatter + if ( + self.transform_type != "linear_kernelonly" + and self.transform_type != "linear" + and self.transform_type != "nonlinear_kernelonly" + and self.transform_type != "nonlinear" + ): + raise ValueError( + f"Got transform_type={transform_type} but expected one of " + "[linear_kernelonly, linear, nonlinear_kernelonly, nonlinear]" + ) + + if channel_mlp is None: + self.channel_mlp = LinearChannelMLP( + layers=channel_mlp_layers, non_linearity=channel_mlp_non_linearity + ) + else: + self.channel_mlp = channel_mlp + + self.weighting_fn = weighting_fn + + def forward(self, y, neighbors, x=None, f_y=None, weights=None): + """Compute a kernel integral transform. Assumes x=y if not specified. + + Integral is taken w.r.t. the neighbors. + + If no weights are given, a Monte-Carlo approximation is made. + + .. note :: For transforms of type 0 or 2, out channels must be + the same as the channels of f + + Parameters + ---------- + y : torch.Tensor of shape [n, d1] + n points of dimension d1 specifying + the space to integrate over. + If batched, these must remain constant + over the whole batch so no batch dim is needed. + neighbors : dict + The sets :math:`A(x)` given in CRS format. The + dict must contain the keys "neighbors_index" + and "neighbors_row_splits." For descriptions + of the two, see NeighborSearch. + If batch > 1, the neighbors must be constant + across the entire batch. + x : torch.Tensor of shape [m, d2], default None + m points of dimension d2 over which the + output function is defined. If None, + x = y. + f_y : torch.Tensor of shape [batch, n, d3] or [n, d3], default None + Function to integrate the kernel against defined + on the points y. The kernel is assumed diagonal + hence its output shape must be d3 for the transforms + (b) or (d). If None, (a) is computed. + weights : torch.Tensor of shape [n,], default None + Weights for each point y proprtional to the + volume around f(y) being integrated. For example, + suppose d1=1 and let y_1 < y_2 < ... < y_{n+1} + be some points. Then, for a Riemann sum, + the weights are y_{j+1} - y_j. If None, + :math:`1/|A(x)|` is used. + + Returns + ------- + out_features : torch.Tensor of shape [batch, m, d4] or [m, d4] + Output function given on the points x. + d4 is the output size of the kernel k. + """ + + if x is None: + x = y + + rep_features = y[neighbors["neighbors_index"]] + + # batching only matters if f_y (latent embedding) values are provided + batched = False + # f_y has a batch dim IFF batched=True + if f_y is not None: + if f_y.ndim == 3: + batched = True + batch_size = f_y.shape[0] + in_features = f_y[:, neighbors["neighbors_index"], :] + elif f_y.ndim == 2: + batched = False + in_features = f_y[neighbors["neighbors_index"]] + + num_reps = ( + neighbors["neighbors_row_splits"][1:] + - neighbors["neighbors_row_splits"][:-1] + ) + + self_features = torch.repeat_interleave(x, num_reps, dim=0) + + agg_features = torch.cat([rep_features, self_features], dim=-1) + if f_y is not None and ( + self.transform_type == "nonlinear_kernelonly" + or self.transform_type == "nonlinear" + ): + if batched: + # repeat agg features for every example in the batch + agg_features = agg_features.repeat( + [batch_size] + [1] * agg_features.ndim + ) + agg_features = torch.cat([agg_features, in_features], dim=-1) + + rep_features = self.channel_mlp(agg_features) + + if f_y is not None and self.transform_type != "nonlinear_kernelonly": + # if we have a batch of outputs (3d incl. batch dim) and unbatched inputs, + # create an identical batch dim in rep_features + if rep_features.ndim == 2 and batched: + rep_features = rep_features.unsqueeze(0).repeat([batch_size] + [1] * rep_features.ndim) + rep_features.mul_(in_features) + + # Weight neighbors in each neighborhood, first according to the neighbor search (mollified GNO) + # and second according to individually-provided weights. + nbr_weights = neighbors.get("weights") + if nbr_weights is None: + nbr_weights = weights + if nbr_weights is None and self.weighting_fn is not None: + raise KeyError("if a weighting function is provided, your neighborhoods must contain weights.") + if nbr_weights is not None: + nbr_weights = nbr_weights.unsqueeze(-1).unsqueeze(0) + if self.weighting_fn is not None: + nbr_weights = self.weighting_fn(nbr_weights) + rep_features.mul_(nbr_weights) + reduction = "sum" # Force sum reduction for weighted GNO layers + + else: + reduction = self.reduction + + splits = neighbors["neighbors_row_splits"] + if batched: + splits = splits.unsqueeze(0).repeat([batch_size] + [1] * (splits.ndim)) + + out_features = segment_csr( + rep_features, + splits, + reduction=reduction, + use_scatter=self.use_torch_scatter, + ) + return out_features diff --git a/sources/neuraloperator/neuralop/layers/legacy_spectral_convolution.py b/sources/neuraloperator/neuralop/layers/legacy_spectral_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6259c5371588db6998a714c2670b36669bbd43 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/legacy_spectral_convolution.py @@ -0,0 +1,742 @@ +import itertools + +from typing import List, Optional, Tuple, Union + +from ..utils import validate_scaling_factor + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal + +import torch +from torch import nn + +import tensorly as tl +from tensorly.plugins import use_opt_einsum +from tltorch.factorized_tensors.core import FactorizedTensor + +from .einsum_utils import einsum_complexhalf +from .base_spectral_conv import BaseSpectralConv +from .resample import resample + +tl.set_backend("pytorch") +use_opt_einsum("optimal") +einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + + +def _contract_dense(x, weight, separable=False): + order = tl.ndim(x) + # batch-size, in_channels, x, y... + x_syms = list(einsum_symbols[:order]) + + # in_channels, out_channels, x, y... + weight_syms = list(x_syms[1:]) # no batch-size + + # batch-size, out_channels, x, y... + if separable: + out_syms = [x_syms[0]] + list(weight_syms) + else: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + + eq = f'{"".join(x_syms)},{"".join(weight_syms)}->{"".join(out_syms)}' + + if not torch.is_tensor(weight): + weight = weight.to_tensor() + + if x.dtype == torch.complex32: + # if x is half precision, run a specialized einsum + return einsum_complexhalf(eq, x, weight) + else: + return tl.einsum(eq, x, weight) + + +def _contract_dense_separable(x, weight, separable=True): + if not separable: + raise ValueError("This function is only for separable=True") + return x * weight + + +def _contract_cp(x, cp_weight, separable=False): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + rank_sym = einsum_symbols[order] + out_sym = einsum_symbols[order + 1] + out_syms = list(x_syms) + if separable: + factor_syms = [einsum_symbols[1] + rank_sym] # in only + else: + out_syms[1] = out_sym + factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out + factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ... + eq = f'{x_syms},{rank_sym},{",".join(factor_syms)}->{"".join(out_syms)}' + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, cp_weight.weights, *cp_weight.factors) + else: + return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors) + + +def _contract_tucker(x, tucker_weight, separable=False): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + out_sym = einsum_symbols[order] + out_syms = list(x_syms) + if separable: + core_syms = einsum_symbols[order + 1 : 2 * order] + # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only + # x, y, ... + factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)] + + else: + core_syms = einsum_symbols[order + 1 : 2 * order + 1] + out_syms[1] = out_sym + factor_syms = [ + einsum_symbols[1] + core_syms[0], + out_sym + core_syms[1], + ] # out, in + # x, y, ... + factor_syms += [xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])] + + eq = f'{x_syms},{core_syms},{",".join(factor_syms)}->{"".join(out_syms)}' + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, tucker_weight.core, *tucker_weight.factors) + else: + return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors) + + +def _contract_tt(x, tt_weight, separable=False): + order = tl.ndim(x) + + x_syms = list(einsum_symbols[:order]) + weight_syms = list(x_syms[1:]) # no batch-size + if not separable: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + else: + out_syms = list(x_syms) + rank_syms = list(einsum_symbols[order + 1 :]) + tt_syms = [] + for i, s in enumerate(weight_syms): + tt_syms.append([rank_syms[i], s, rank_syms[i + 1]]) + eq = ( + "".join(x_syms) + + "," + + ",".join("".join(f) for f in tt_syms) + + "->" + + "".join(out_syms) + ) + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, *tt_weight.factors) + else: + return tl.einsum(eq, x, *tt_weight.factors) + + +def get_contract_fun(weight, implementation="reconstructed", separable=False): + """Generic ND implementation of Fourier Spectral Conv contraction + + Parameters + ---------- + weight : tensorly-torch's FactorizedTensor + implementation : {'reconstructed', 'factorized'}, default is 'reconstructed' + whether to reconstruct the weight and do a forward pass (reconstructed) + or contract directly the factors of the factorized weight with the input (factorized) + separable : bool + whether to use the separable implementation of contraction. This arg is + only checked when `implementation=reconstructed`. + + Returns + ------- + function : (x, weight) -> x * weight in Fourier space + """ + if implementation == "reconstructed": + if separable: + return _contract_dense_separable + else: + return _contract_dense + elif implementation == "factorized": + if torch.is_tensor(weight): + return _contract_dense + elif isinstance(weight, FactorizedTensor): + if weight.name.lower().endswith("dense"): + return _contract_dense + elif weight.name.lower().endswith("tucker"): + return _contract_tucker + elif weight.name.lower().endswith("tt"): + return _contract_tt + elif weight.name.lower().endswith("cp"): + return _contract_cp + else: + raise ValueError(f"Got unexpected factorized weight type {weight.name}") + else: + raise ValueError( + f"Got unexpected weight type of class {weight.__class__.__name__}" + ) + else: + raise ValueError( + f'Got implementation={implementation}, expected "reconstructed" or "factorized"' + ) + + +Number = Union[int, float] + + +class SpectralConv(BaseSpectralConv): + """Old implementation of the Spectral Convolution layer. + + This implementation is deprecated and might be removed in future versions. + + Parameters + ---------- + in_channels : int, optional + Number of input channels + out_channels : int, optional + Number of output channels + n_modes : int tuple + total number of modes to keep in Fourier Layer, along each dim + separable : bool, default is True + init_std : float or 'auto', default is 'auto' + std to use for the init + n_layers : int, optional + Number of Fourier Layers, by default 4 + incremental_n_modes : None or int tuple, default is None + * If not None, this allows to incrementally increase the number of modes + in Fourier domain during training. Has to verify n <= N for (n, m) in + zip(incremental_n_modes, n_modes). + + * If None, all the n_modes are used. + + This can be updated dynamically during training. + factorization : str or None, {'tucker', 'cp', 'tt'}, default is None + If None, a single dense weight is learned for the FNO. + Otherwise, that weight, used for the contraction in the Fourier domain + is learned in factorized form. In that case, `factorization` is the + tensor factorization of the parameters weight used. + joint_factorization : bool, optional + Whether all the Fourier Layers should be parametrized by a single tensor + (vs one per layer), by default False Ignored if ``factorization is None`` + rank : float or rank, optional + Rank of the tensor factorization of the Fourier weights, by default 1.0 + Ignored if ``factorization is None`` + fixed_rank_modes : bool, optional + Modes to not factorize, by default False + Ignored if ``factorization is None`` + fft_norm : str, optional + by default 'forward' + implementation : {'factorized', 'reconstructed'}, optional, default is 'factorized' + If factorization is not None, forward mode to use:: + * `reconstructed` : the full weight tensor is reconstructed from the + factorization and used for the forward pass + * `factorized` : the input is directly contracted with the factors of + the decomposition + Ignored if ``factorization is None`` + decomposition_kwargs : dict, optional, default is {} + Optionaly additional parameters to pass to the tensor decomposition + Ignored if ``factorization is None`` + """ + + def __init__( + self, + in_channels, + out_channels, + n_modes, + incremental_n_modes=None, + bias=True, + n_layers=1, + separable=False, + resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None, + fno_block_precision="full", + rank=0.5, + factorization=None, + implementation="reconstructed", + fixed_rank_modes=False, + joint_factorization=False, + decomposition_kwargs: Optional[dict] = None, + init_std="auto", + fft_norm="backward", + device=None, + dtype=None, + ): + super().__init__(dtype=dtype, device=device) + + self.in_channels = in_channels + self.out_channels = out_channels + self.joint_factorization = joint_factorization + + # We index quadrands only + # n_modes is the total number of modes kept along each dimension + # half_n_modes is half of that except in the last mode, correponding to + # the number of modes to keep in *each* quadrant for each dim + if isinstance(n_modes, int): + n_modes = [n_modes] + self.n_modes = n_modes + self.order = len(n_modes) + + half_total_n_modes = [m // 2 for m in n_modes] + self.half_total_n_modes = half_total_n_modes + + # We use half_total_n_modes to build the full weights + # During training we can adjust incremental_n_modes which will also + # update half_n_modes + # So that we can train on a smaller part of the Fourier modes and total + # weights + self.incremental_n_modes = incremental_n_modes + + self.fno_block_precision = fno_block_precision + self.rank = rank + self.factorization = factorization + self.n_layers = n_layers + self.implementation = implementation + + self.resolution_scaling_factor: Union[ + None, List[List[float]] + ] = validate_scaling_factor(resolution_scaling_factor, self.order, n_layers) + + if init_std == "auto": + init_std = (2 / (in_channels + out_channels)) ** 0.5 + + if isinstance(fixed_rank_modes, bool): + if fixed_rank_modes: + # If bool, keep the number of layers fixed + fixed_rank_modes = [0] + else: + fixed_rank_modes = None + self.fft_norm = fft_norm + + # Make sure we are using a Complex Factorized Tensor to parametrize the + # conv + if factorization is None: + factorization = "Dense" # No factorization + if not factorization.lower().startswith("complex"): + factorization = f"Complex{factorization}" + + if separable: + if in_channels != out_channels: + raise ValueError( + "To use separable Fourier Conv, in_channels must be equal " + f"to out_channels, but got in_channels={in_channels} and " + f"out_channels={out_channels}", + ) + weight_shape = (in_channels, *half_total_n_modes) + else: + weight_shape = (in_channels, out_channels, *half_total_n_modes) + self.separable = separable + + self.n_weights_per_layer = 2 ** (self.order - 1) + tensor_kwargs = decomposition_kwargs if decomposition_kwargs is not None else {} + if joint_factorization: + self.weight = FactorizedTensor.new( + (self.n_weights_per_layer * n_layers, *weight_shape), + rank=self.rank, + factorization=factorization, + fixed_rank_modes=fixed_rank_modes, + **tensor_kwargs, + ) + self.weight.normal_(0, init_std) + else: + self.weight = nn.ModuleList( + [ + FactorizedTensor.new( + weight_shape, + rank=self.rank, + factorization=factorization, + fixed_rank_modes=fixed_rank_modes, + **tensor_kwargs, + ) + for _ in range(self.n_weights_per_layer * n_layers) + ] + ) + for w in self.weight: + w.normal_(0, init_std) + self._contract = get_contract_fun( + self.weight[0], implementation=implementation, separable=separable + ) + + if bias: + self.bias = nn.Parameter( + init_std + * torch.randn(*((n_layers, self.out_channels) + (1,) * self.order)) + ) + else: + self.bias = None + + def _get_weight(self, index): + if self.incremental_n_modes is not None: + return self.weight[index][self.weight_slices] + else: + return self.weight[index] + + @property + def incremental_n_modes(self): + return self._incremental_n_modes + + @incremental_n_modes.setter + def incremental_n_modes(self, incremental_n_modes): + if incremental_n_modes is None: + self._incremental_n_modes = None + self.half_n_modes = [m // 2 for m in self.n_modes] + + else: + if isinstance(incremental_n_modes, int): + self._incremental_n_modes = [incremental_n_modes] * len(self.n_modes) + else: + if len(incremental_n_modes) == len(self.n_modes): + self._incremental_n_modes = incremental_n_modes + else: + raise ValueError( + f"Provided {incremental_n_modes} for actual " + f"n_modes={self.n_modes}." + ) + self.weight_slices = [slice(None)] * 2 + [ + slice(None, n // 2) for n in self._incremental_n_modes + ] + self.half_n_modes = [m // 2 for m in self._incremental_n_modes] + + def transform(self, x, layer_index=0, output_shape=None): + in_shape = list(x.shape[2:]) + + if self.resolution_scaling_factor is not None and output_shape is None: + out_shape = tuple( + [ + round(s * r) + for (s, r) in zip(in_shape, self.resolution_scaling_factor[layer_index]) + ] + ) + elif output_shape is not None: + out_shape = output_shape + else: + out_shape = in_shape + + if in_shape == out_shape: + return x + else: + return resample( + x, + 1.0, + list(range(2, x.ndim)), + output_shape=out_shape, + ) + + def forward( + self, x: torch.Tensor, indices=0, output_shape: Optional[Tuple[int]] = None + ): + """Generic forward pass for the Factorized Spectral Conv + + Parameters + ---------- + x : torch.Tensor + input activation of size (batch_size, channels, d1, ..., dN) + indices : int, default is 0 + if joint_factorization, index of the layers for n_layers > 1 + + Returns + ------- + tensorized_spectral_conv(x) + """ + batchsize, channels, *mode_sizes = x.shape + + fft_size = list(mode_sizes) + fft_size[-1] = fft_size[-1] // 2 + 1 # Redundant last coefficient + + # Compute Fourier coeffcients + fft_dims = list(range(-self.order, 0)) + + if self.fno_block_precision == "half": + x = x.half() + + x = torch.fft.rfftn(x, norm=self.fft_norm, dim=fft_dims) + + if self.fno_block_precision == "mixed": + # if 'mixed', the above fft runs in full precision, but the + # following operations run at half precision + x = x.chalf() + + if self.fno_block_precision in ["half", "mixed"]: + out_fft = torch.zeros( + [batchsize, self.out_channels, *fft_size], + device=x.device, + dtype=torch.chalf, + ) + else: + out_fft = torch.zeros( + [batchsize, self.out_channels, *fft_size], + device=x.device, + dtype=torch.cfloat, + ) + + # We contract all corners of the Fourier coefs + # Except for the last mode: there, we take all coefs as redundant modes + # were already removed + mode_indexing = [((None, m), (-m, None)) for m in self.half_n_modes[:-1]] + [ + ((None, self.half_n_modes[-1]),) + ] + + for i, boundaries in enumerate(itertools.product(*mode_indexing)): + # Keep all modes for first 2 modes (batch-size and channels) + idx_tuple = [slice(None), slice(None)] + [slice(*b) for b in boundaries] + + # For 2D: [:, :, :height, :width] and [:, :, -height:, width] + out_fft[idx_tuple] = self._contract( + x[idx_tuple], + self._get_weight(self.n_weights_per_layer * indices + i), + separable=self.separable, + ) + + if self.resolution_scaling_factor is not None and output_shape is None: + mode_sizes = tuple( + [ + round(s * r) + for (s, r) in zip(mode_sizes, self.resolution_scaling_factor[indices]) + ] + ) + + if output_shape is not None: + mode_sizes = output_shape + + x = torch.fft.irfftn(out_fft, s=mode_sizes, norm=self.fft_norm) + + if self.bias is not None: + x = x + self.bias[indices, ...] + + return x + + def get_conv(self, indices): + """Returns a sub-convolutional layer from the joint parametrize main-convolution + + The parametrization of sub-convolutional layers is shared with the main one. + """ + if self.n_layers == 1: + Warning("A single convolution is parametrized, directly use the main class.") + # raise ValueError( + # "A single convolution is parametrized, directly use the main class." + # ) + + return SubConv(self, indices) + + def __getitem__(self, indices): + return self.get_conv(indices) + + +class SubConv(nn.Module): + """Class representing one of the convolutions from the mother joint + factorized convolution. + + Notes + ----- + This relies on the fact that nn.Parameters are not duplicated: + if the same nn.Parameter is assigned to multiple modules, they all point to + the same data, which is shared. + """ + + def __init__(self, main_conv, indices): + super().__init__() + self.main_conv = main_conv + self.indices = indices + + def forward(self, x, **kwargs): + if kwargs: + warnings.warn( + f"SpectralConvWrapper.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + return self.main_conv.forward(x, self.indices, **kwargs) + + def transform(self, x, **kwargs): + if kwargs: + warnings.warn( + f"SpectralConvWrapper.transform() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + return self.main_conv.transform(x, self.indices, **kwargs) + + @property + def weight(self): + return self.main_conv.get_weight(indices=self.indices) + + +class SpectralConv1d(SpectralConv): + """1D Spectral Conv + + This is provided for reference only, + see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation + """ + + def forward(self, x, indices=0): + batchsize, channels, width = x.shape + + x = torch.fft.rfft(x, norm=self.fft_norm) + + out_fft = torch.zeros( + [batchsize, self.out_channels, width // 2 + 1], + device=x.device, + dtype=torch.cfloat, + ) + slices = ( + slice(None), # Equivalent to: [:, + slice(None), # ............... :, + slice(self.half_n_modes[0]), # :half_n_modes[0]] + ) + out_fft[slices] = self._contract( + x[slices], self._get_weight(indices), separable=self.separable + ) + + if self.resolution_scaling_factor is not None: + width = round(width * self.resolution_scaling_factor[0]) + + x = torch.fft.irfft(out_fft, n=width, norm=self.fft_norm) + + if self.bias is not None: + x = x + self.bias[indices, ...] + + return x + + +class SpectralConv2d(SpectralConv): + """2D Spectral Conv, see :class:`neuralop.layers.SpectraConv` for the general case + + This is provided for reference only, + see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation + """ + + def forward(self, x, indices=0): + batchsize, channels, height, width = x.shape + + x = torch.fft.rfft2(x.float(), norm=self.fft_norm) + + # The output will be of size (batch_size, self.out_channels, + # x.size(-2), x.size(-1)//2 + 1) + out_fft = torch.zeros( + [batchsize, self.out_channels, height, width // 2 + 1], + dtype=x.dtype, + device=x.device, + ) + + slices0 = ( + slice(None), # Equivalent to: [:, + slice(None), # ............... :, + slice(self.half_n_modes[0]), # :half_n_modes[0], + slice(self.half_n_modes[1]), # :half_n_modes[1]] + ) + """Upper block (truncate high frequencies).""" + out_fft[slices0] = self._contract( + x[slices0], self._get_weight(2 * indices), separable=self.separable + ) + + slices1 = ( + slice(None), # Equivalent to: [:, + slice(None), # ...................... :, + slice(-self.half_n_modes[0], None), # -half_n_modes[0]:, + slice(self.half_n_modes[1]), # ...... :half_n_modes[1]] + ) + """Lower block""" + out_fft[slices1] = self._contract( + x[slices1], self._get_weight(2 * indices + 1), separable=self.separable + ) + + if self.resolution_scaling_factor is not None: + width = round(width * self.resolution_scaling_factor[indices][0]) + height = round(height * self.resolution_scaling_factor[indices][1]) + + x = torch.fft.irfft2( + out_fft, s=(height, width), dim=(-2, -1), norm=self.fft_norm + ) + + if self.bias is not None: + x = x + self.bias[indices, ...] + + return x + + +class SpectralConv3d(SpectralConv): + """3D Spectral Conv, see :class:`neuralop.layers.SpectraConv` for the general case + + This is provided for reference only, + see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation + """ + + def forward(self, x, indices=0): + batchsize, channels, height, width, depth = x.shape + + x = torch.fft.rfftn(x.float(), norm=self.fft_norm, dim=[-3, -2, -1]) + + out_fft = torch.zeros( + [batchsize, self.out_channels, height, width, depth // 2 + 1], + device=x.device, + dtype=torch.cfloat, + ) + + slices0 = ( + slice(None), # Equivalent to: [:, + slice(None), # ............... :, + slice(self.half_n_modes[0]), # :half_n_modes[0], + slice(self.half_n_modes[1]), # :half_n_modes[1], + slice(self.half_n_modes[2]), # :half_n_modes[2]] + ) + """Upper block -- truncate high frequencies.""" + out_fft[slices0] = self._contract( + x[slices0], self._get_weight(4 * indices + 0), separable=self.separable + ) + + slices1 = ( + slice(None), # Equivalent to: [:, + slice(None), # ...................... :, + slice(self.half_n_modes[0]), # ...... :half_n_modes[0], + slice(-self.half_n_modes[1], None), # -half_n_modes[1]:, + slice(self.half_n_modes[2]), # ...... :half_n_modes[0]] + ) + """Low-pass filter for indices 2 & 4, and high-pass filter for index 3.""" + out_fft[slices1] = self._contract( + x[slices1], self._get_weight(4 * indices + 1), separable=self.separable + ) + + slices2 = ( + slice(None), # Equivalent to: [:, + slice(None), # ...................... :, + slice(-self.half_n_modes[0], None), # -half_n_modes[0]:, + slice(self.half_n_modes[1]), # ...... :half_n_modes[1], + slice(self.half_n_modes[2]), # ...... :half_n_modes[2]] + ) + """Low-pass filter for indices 3 & 4, and high-pass filter for index 2.""" + out_fft[slices2] = self._contract( + x[slices2], self._get_weight(4 * indices + 2), separable=self.separable + ) + + slices3 = ( + slice(None), # Equivalent to: [:, + slice(None), # ...................... :, + slice(-self.half_n_modes[0], None), # -half_n_modes[0], + slice(-self.half_n_modes[1], None), # -half_n_modes[1], + slice(self.half_n_modes[2]), # ...... :half_n_modes[2]] + ) + """Lower block -- low-cut filter in indices 2 & 3 + and high-cut filter in index 4.""" + out_fft[slices3] = self._contract( + x[slices3], self._get_weight(4 * indices + 3), separable=self.separable + ) + + if self.resolution_scaling_factor is not None: + width = round(width * self.resolution_scaling_factor[0]) + height = round(height * self.resolution_scaling_factor[1]) + depth = round(depth * self.resolution_scaling_factor[2]) + + x = torch.fft.irfftn(out_fft, s=(height, width, depth), norm=self.fft_norm) + + if self.bias is not None: + x = x + self.bias[indices, ...] + return x diff --git a/sources/neuraloperator/neuralop/layers/local_no_block.py b/sources/neuraloperator/neuralop/layers/local_no_block.py new file mode 100644 index 0000000000000000000000000000000000000000..aaadbba84d1c4c16c5919ad5164fe4b6d2eaf90e --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/local_no_block.py @@ -0,0 +1,587 @@ +from typing import List, Optional, Union +import warnings + +import torch +from torch import nn +import torch.nn.functional as F + +from .channel_mlp import ChannelMLP +from .fno_block import SubModule +from .differential_conv import FiniteDifferenceConvolution +from .discrete_continuous_convolution import EquidistantDiscreteContinuousConv2d +from .normalization_layers import AdaIN, InstanceNorm +from .skip_connections import skip_connection +from .spectral_convolution import SpectralConv +from ..utils import validate_scaling_factor + + +Number = Union[int, float] + + +class LocalNOBlocks(nn.Module): + """Local Neural Operator blocks with localized integral and differential kernels. + + It is implemented as described in [3]_. + + This class implements neural operator blocks that combine Fourier neural operators + with localized integral and differential kernels to capture both global and local + features in PDE solutions [3]_. The architecture addresses the over-smoothing limitations + of purely global FNOs while maintaining resolution-independence through principled + local operations. + + The key innovation is the integration of two types of local operations: + 1. Differential kernels: Learn finite difference stencils that converge to + differential operators under appropriate scaling. + 2. Local integral kernels: Use discrete-continuous convolutions with locally + supported kernels to capture local interactions. + + Parameters + ---------- + in_channels : int + Number of input channels to Fourier layers + out_channels : int + Number of output channels after Fourier layers + n_modes : int, 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 + default_in_shape : Tuple[int] + Default input shape for spatiotemporal dimensions + resolution_scaling_factor : Optional[Union[Number, List[Number]]], optional + Factor by which to scale outputs for super-resolution, by default None + n_layers : int, optional + Number of neural operator layers to apply in sequence, by default 1 + disco_layers : bool or List[bool], optional + Whether to include local integral kernel connections at each layer. + If a single bool, applies to all layers. If a list, must match n_layers. + disco_kernel_shape : Union[int, List[int]], optional + Kernel shape for local integral operations. Single int for isotropic kernels, + two ints for anisotropic kernels, by default [2,4] + domain_length : torch.Tensor, optional + Physical domain extent/length. Assumes square domain [-1, 1]^2 by default + disco_groups : int, optional + Number of groups in local integral convolution, by default 1 + disco_bias : bool, optional + Whether to use bias for integral kernel, by default True + radius_cutoff : float, optional + Cutoff radius (relative to domain_length) for local integral kernel, by default None + diff_layers : bool or List[bool], optional + Whether to include differential kernel connections at each layer. + If a single bool, applies to all layers. If a list, must match n_layers. + conv_padding_mode : str, optional + Padding mode for spatial convolution kernels. + Options: 'periodic', 'circular', 'replicate', 'reflect', 'zeros'. By default 'periodic' + fin_diff_kernel_size : int, optional + Kernel size for finite difference convolution (must be odd), by default 3 + mix_derivatives : bool, optional + Whether to mix derivatives across channels, by default True + max_n_modes : int or List[int], optional + Maximum number of modes to keep along each dimension, by default None + local_no_block_precision : str, optional + Floating point precision for computations, by default "full" + use_channel_mlp : bool, optional + Whether to use MLP layer after each block, by default False + channel_mlp_dropout : int, optional + Dropout parameter for channel MLP, by default 0 + channel_mlp_expansion : float, optional + Expansion factor for channel MLP, by default 0.5 + non_linearity : torch.nn.F module, optional + Nonlinear activation function between layers, by default F.gelu + stabilizer : Literal["tanh"], optional + Stabilizing module between layers. Options: "tanh". By default None + norm : Literal["ada_in", "group_norm", "instance_norm"], optional + Normalization layer to use, by default None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + ada_in_features : int, optional + Number of features for adaptive instance normalization, by default None + preactivation : bool, optional + 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 + local_no_skip : str, optional + Module to use for Local NO skip connections, by default "linear" + Options: "linear", "identity", "soft-gating", None. + If None, no skip connection is added. See layers.skip_connections for more details + channel_mlp_skip : str, optional + Module to use for ChannelMLP skip connections, by default "soft-gating" + Options: "linear", "identity", "soft-gating", None. + If None, no skip connection is added. See layers.skip_connections for more details + + Other Parameters + ---------------- + complex_data : bool, optional + Whether the data takes complex values in space, by default False + separable : bool, optional + Separable parameter for SpectralConv, by default False + factorization : str, optional + Factorization method for SpectralConv, by default None + Options: "factorized", "reconstructed". + rank : float, optional + Rank parameter for SpectralConv, by default 1.0 + conv_module : BaseConv, optional + Convolution module for Local NO block, by default SpectralConv + joint_factorization : bool, optional + Whether to factorize all SpectralConv weights as one tensor, by default False + fixed_rank_modes : bool, optional + Fixed rank modes parameter for SpectralConv, by default False + implementation : str, optional + Implementation method for SpectralConv, by default "factorized" + decomposition_kwargs : dict, optional + Keyword arguments for tensor decomposition in SpectralConv, by default dict() + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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. + + Notes + ----- + - Differential kernels are only implemented for dimensions ≤ 3 + - Local integral kernels are only implemented for 2D domains + + 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. + .. [3] Liu-Schiaffini M., Berner J., Bonev B., Kurth T., Azizzadenesheli K., Anandkumar A.; + "Neural Operators with Localized Integral and Differential Kernels" (2024). + ICML 2024, https://arxiv.org/pdf/2402.16845. + """ + + def __init__( + self, + in_channels, + out_channels, + n_modes, + default_in_shape, + resolution_scaling_factor=None, + n_layers=1, + disco_layers=True, + disco_kernel_shape=[2, 4], + radius_cutoff=None, + domain_length=[2, 2], + disco_groups=1, + disco_bias=True, + diff_layers=True, + conv_padding_mode="periodic", + fin_diff_kernel_size=3, + mix_derivatives=True, + max_n_modes=None, + local_no_block_precision="full", + use_channel_mlp=False, + channel_mlp_dropout=0, + channel_mlp_expansion=0.5, + non_linearity=F.gelu, + stabilizer=None, + norm=None, + norm_groups=1, + ada_in_features=None, + preactivation=False, + local_no_skip="linear", + channel_mlp_skip="soft-gating", + separable=False, + factorization=None, + rank=1.0, + conv_module=SpectralConv, + fixed_rank_modes=False, + implementation="factorized", + decomposition_kwargs=dict(), + fft_norm="forward", + enforce_hermitian_symmetry=True, + ): + super().__init__() + if isinstance(n_modes, int): + n_modes = [n_modes] + self._n_modes = n_modes + + assert len(n_modes) == len(default_in_shape), "Spatiotemporal dimensions must be consistent" + + # If a single bool is passed for disco_layers or diff_layers, set values for all layers + if isinstance(disco_layers, bool): + disco_layers = [disco_layers] * n_layers + if isinstance(diff_layers, bool): + diff_layers = [diff_layers] * n_layers + + if len(n_modes) > 3 and True in diff_layers: + raise NotImplementedError("Differential convs not implemented for dimensions higher than 3.") + + if len(n_modes) != 2 and True in disco_layers: + raise NotImplementedError("Local conv layers only implemented for dimension 2.") + + if conv_padding_mode not in ['circular', 'periodic', 'zeros'] and True in disco_layers: + warnings.warn("Local conv layers only support periodic or zero padding, defaulting to zero padding for local convs.") + + self.n_dim = len(n_modes) + + self.resolution_scaling_factor: Union[ + None, List[List[float]] + ] = validate_scaling_factor(resolution_scaling_factor, self.n_dim, n_layers) + + self.max_n_modes = max_n_modes + self.local_no_block_precision = local_no_block_precision + self.in_channels = in_channels + self.out_channels = out_channels + self.n_layers = n_layers + self.non_linearity = non_linearity + self.stabilizer = stabilizer + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.local_no_skip = local_no_skip + self.channel_mlp_skip = channel_mlp_skip + self.use_channel_mlp = use_channel_mlp + self.channel_mlp_expansion = channel_mlp_expansion + self.channel_mlp_dropout = channel_mlp_dropout + self.fft_norm = fft_norm + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + self.ada_in_features = ada_in_features + self.enforce_hermitian_symmetry = enforce_hermitian_symmetry + + self.diff_layers = diff_layers + self.conv_padding_mode = conv_padding_mode + self.default_in_shape = default_in_shape + self.fin_diff_kernel_size = fin_diff_kernel_size + self.mix_derivatives = mix_derivatives + + self.disco_layers = disco_layers + self.disco_kernel_shape = disco_kernel_shape + self.radius_cutoff = radius_cutoff + self.domain_length = domain_length + self.disco_groups = disco_groups + self.disco_bias = disco_bias + self.periodic = self.conv_padding_mode in ["circular", "periodic"] + + assert ( + len(diff_layers) == n_layers + ), f"diff_layers must either provide a single bool value or a list of booleans of length n_layers,\ + got {len(diff_layers)=}" + assert ( + len(disco_layers) == n_layers + ), f"disco_layers must either provide a single bool value or a list of booleans of length n_layers,\ + got {len(disco_layers)=}" + + # One conv per layer. Only resolution_scaling_factor varies by layer index + self.convs = nn.ModuleList( + [ + conv_module( + self.in_channels, + self.out_channels, + self.n_modes, + # Per-layer scaling for super-resolution, or None if disabled + resolution_scaling_factor=( + self.resolution_scaling_factor[i] + if resolution_scaling_factor is not None + else None + ), + max_n_modes=max_n_modes, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + decomposition_kwargs=decomposition_kwargs, + # Only SpectralConv (and subclasses) accept enforce_hermitian_symmetry. Others ignore it + **( + {"enforce_hermitian_symmetry": enforce_hermitian_symmetry} + if issubclass(conv_module, SpectralConv) + else {} + ), + ) + for i in range(n_layers) + ] + ) + + if local_no_skip is not None: + self.local_no_skips = nn.ModuleList( + [ + skip_connection( + self.in_channels, + self.out_channels, + skip_type=local_no_skip, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + ) + else: + self.local_no_skips = None + + self.diff_groups = 1 if mix_derivatives else in_channels + self.differential = nn.ModuleList( + [ + FiniteDifferenceConvolution( + self.in_channels, + self.out_channels, + self.n_dim, + self.fin_diff_kernel_size, + self.diff_groups, + self.conv_padding_mode, + ) + for _ in range(sum(self.diff_layers)) + ] + ) + + self.local_convs = nn.ModuleList( + [ + EquidistantDiscreteContinuousConv2d( + self.in_channels, + self.out_channels, + in_shape=self.default_in_shape, + out_shape=self.default_in_shape, + kernel_shape=self.disco_kernel_shape, + domain_length=self.domain_length, + radius_cutoff=self.radius_cutoff, + periodic=self.periodic, + groups=self.disco_groups, + bias=self.disco_bias, + ) + for _ in range(sum(self.disco_layers)) + ] + ) + + # Helper for calling differential layers + self.differential_idx_list = [] + j = 0 + for i in range(n_layers): + if self.diff_layers[i]: + self.differential_idx_list.append(j) + j += 1 + else: + self.differential_idx_list.append(-1) + + assert max(self.differential_idx_list) == sum(self.diff_layers) - 1 + + # Helper for calling local conv layers + self.disco_idx_list = [] + j = 0 + for i in range(n_layers): + if self.disco_layers[i]: + self.disco_idx_list.append(j) + j += 1 + else: + self.disco_idx_list.append(-1) + + assert max(self.disco_idx_list) == sum(self.disco_layers) - 1 + + if use_channel_mlp: + self.mlp = nn.ModuleList( + [ + ChannelMLP( + in_channels=self.out_channels, + hidden_channels=round(self.out_channels * channel_mlp_expansion), + dropout=channel_mlp_dropout, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + ) + if channel_mlp_skip is not None: + self.channel_mlp_skips = nn.ModuleList( + [ + skip_connection( + self.in_channels, + self.out_channels, + skip_type=channel_mlp_skip, + n_dim=self.n_dim, + ) + for _ in range(n_layers) + ] + ) + else: + self.channel_mlp_skips = None + else: + self.mlp = None + + # Each block will have 2 norms if we also use an MLP + self.n_norms = 1 if self.mlp is None else 2 + if norm is None: + self.norm = None + elif norm == "instance_norm": + self.norm = nn.ModuleList( + [InstanceNorm() for _ in range(n_layers * self.n_norms)] + ) + elif norm == "group_norm": + self.norm = nn.ModuleList( + [ + nn.GroupNorm(num_groups=norm_groups, num_channels=self.out_channels) + for _ in range(n_layers * self.n_norms) + ] + ) + elif norm == "ada_in": + self.norm = nn.ModuleList( + [ + AdaIN(ada_in_features, out_channels) + for _ in range(n_layers * self.n_norms) + ] + ) + else: + raise ValueError( + f"Got norm={norm} but expected None or one of " + "[instance_norm, group_norm, ada_in]" + ) + + def set_ada_in_embeddings(self, *embeddings): + """Sets the embeddings of each Ada-IN norm layers + + Parameters + ---------- + embeddings : tensor or list of tensor + if a single embedding is given, it will be used for each norm layer + otherwise, each embedding will be used for the corresponding norm layer + """ + if len(embeddings) == 1: + for norm in self.norm: + norm.set_embedding(embeddings[0]) + else: + for norm, embedding in zip(self.norm, embeddings): + norm.set_embedding(embedding) + + def forward(self, x, index=0, output_shape=None): + if self.preactivation: + return self.forward_with_preactivation(x, index, output_shape) + else: + return self.forward_with_postactivation(x, index, output_shape) + + def forward_with_postactivation(self, x, index=0, output_shape=None): + if self.local_no_skips is not None: + x_skip_local_no = self.local_no_skips[index](x) + x_skip_local_no = self.convs[index].transform(x_skip_local_no, output_shape=output_shape) + + if self.mlp is not None and self.channel_mlp_skips is not None: + x_skip_mlp = self.channel_mlp_skips[index](x) + x_skip_mlp = self.convs[index].transform(x_skip_mlp, output_shape=output_shape) + + if self.stabilizer == "tanh": + x = torch.tanh(x) + + x_local_no = self.convs[index](x, output_shape=output_shape) + + if self.differential_idx_list[index] != -1: + grid_width_scaling_factor = 1 / (x.shape[-1] / self.default_in_shape[0]) + x_differential = self.differential[self.differential_idx_list[index]](x, grid_width_scaling_factor) + x_differential = self.convs[index].transform(x_differential, output_shape=output_shape) + else: + x_differential = 0 + + if self.disco_idx_list[index] != -1: + x_localconv = self.local_convs[self.disco_idx_list[index]](x) + x_localconv = self.convs[index].transform(x_localconv, output_shape=output_shape) + else: + x_localconv = 0 + + x_local_no_diff_disco = x_local_no + x_differential + x_localconv + + if self.norm is not None: + x_local_no_diff_disco = self.norm[self.n_norms * index](x_local_no_diff_disco) + + x = ( + x_local_no_diff_disco + x_skip_local_no + if self.local_no_skips is not None + else x_local_no_diff_disco + ) + + if (self.mlp is not None) or (index < (self.n_layers - 1)): + x = self.non_linearity(x) + + if self.mlp is not None: + if self.channel_mlp_skips is not None: + x = self.mlp[index](x) + x_skip_mlp + else: + x = self.mlp[index](x) + + if self.norm is not None: + x = self.norm[self.n_norms * index + 1](x) + + if index < (self.n_layers - 1): + x = self.non_linearity(x) + + return x + + def forward_with_preactivation(self, x, index=0, output_shape=None): + # Apply non-linear activation (and norm) + # before this block's convolution/forward pass: + x = self.non_linearity(x) + + if self.norm is not None: + x = self.norm[self.n_norms * index](x) + + if self.differential_idx_list[index] != -1: + grid_width_scaling_factor = 1 / (x.shape[-1] / self.default_grid_res) + x_differential = self.differential[self.differential_idx_list[index]](x, grid_width_scaling_factor) + else: + x_differential = 0 + + if self.disco_idx_list[index] != -1: + x_localconv = self.local_convs[self.disco_idx_list[index]](x) + else: + x_localconv = 0 + + if self.local_no_skips is not None: + x_skip_local_no = self.local_no_skips[index](x) + x_skip_local_local_no = self.convs[index].transform(x_skip_local_no + x_differential + x_localconv, output_shape=output_shape) + else: + x_skip_local_local_no = self.convs[index].transform(x_differential + x_localconv, output_shape=output_shape) + + if self.mlp is not None: + if self.channel_mlp_skips is not None: + x_skip_mlp = self.channel_mlp_skips[index](x) + x_skip_mlp = self.convs[index].transform(x_skip_mlp, output_shape=output_shape) + + if self.stabilizer == "tanh": + x = torch.tanh(x) + + x_local_no = self.convs[index](x, output_shape=output_shape) + + x = ( + x_local_no + x_skip_local_local_no + if self.local_no_skips is not None + else x_local_no + ) + + if self.mlp is not None: + if index < (self.n_layers - 1): + x = self.non_linearity(x) + + if self.norm is not None: + x = self.norm[self.n_norms * index + 1](x) + + if self.channel_mlp_skips is not None: + x = self.mlp[index](x) + x_skip_mlp + else: + x = self.mlp[index](x) + + return x + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + for i in range(self.n_layers): + self.convs[i].n_modes = n_modes + self._n_modes = n_modes + + def get_block(self, indices): + """Returns a sub-NO Block layer from the jointly parametrized main block + + The parametrization of an LocalNOBlock layer is shared with the main one. + """ + if self.n_layers == 1: + raise ValueError( + "A single layer is parametrized, directly use the main class." + ) + + return SubModule(self, indices) + + def __getitem__(self, indices): + return self.get_block(indices) diff --git a/sources/neuraloperator/neuralop/layers/neighbor_search.py b/sources/neuraloperator/neuralop/layers/neighbor_search.py new file mode 100644 index 0000000000000000000000000000000000000000..b63d0fcaec5574d08086ded01471a6ee730f09f4 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/neighbor_search.py @@ -0,0 +1,119 @@ +import torch +from torch import nn + +# only import open3d if built +open3d_built = False +try: + from open3d.ml.torch.layers import FixedRadiusSearch + + open3d_built = True +except: + pass + + +# Uses open3d by default which, as of October 2024, requires torch 2.0 and cuda11.* +class NeighborSearch(nn.Module): + """Neighborhood search between two arbitrary coordinate meshes. + + For each point `x` in `queries`, returns a set of the indices of all points `y` in `data` + within the ball of radius r `B_r(x)` + + Parameters + ---------- + use_open3d : bool, optional + Whether to use open3d or native PyTorch implementation, by default True + NOTE: open3d implementation requires 3d data + return_norm : bool, optional + Whether to return normalized distances, by default False + """ + + def __init__(self, use_open3d=True, return_norm=False): + super().__init__() + if use_open3d and open3d_built: # slightly faster, works on GPU in 3d only + self.search_fn = FixedRadiusSearch() + self.use_open3d = use_open3d + else: # slower fallback, works on GPU and CPU + self.search_fn = native_neighbor_search + self.use_open3d = False + self.return_norm = return_norm + + def forward(self, data, queries, radius): + """ + Find the neighbors, in data, of each point in queries + within a ball of radius. Returns in CRS format. + + Parameters + ---------- + data : torch.Tensor of shape [n, d] + Search space of possible neighbors + NOTE: open3d requires d=3 + queries : torch.Tensor of shape [m, d] + Points for which to find neighbors + NOTE: open3d requires d=3 + radius : float + Radius of each ball: B(queries[j], radius) + + Returns + ------- + return_dict : dict + Dictionary with keys: neighbors_index, neighbors_row_splits + neighbors_index: torch.Tensor with dtype=torch.int64 + Index of each neighbor in data for every point + in queries. Neighbors are ordered in the same orderings + as the points in queries. Open3d and torch_cluster + implementations can differ by a permutation of the + neighbors for every point. + neighbors_row_splits: torch.Tensor of shape [m+1] with dtype=torch.int64 + The value at index j is the sum of the number of + neighbors up to query point j-1. First element is 0 + and last element is the total number of neighbors. + """ + return_dict = {} + + if self.use_open3d: + search_return = self.search_fn(data, queries, radius) + return_dict["neighbors_index"] = search_return.neighbors_index.long() + return_dict["neighbors_row_splits"] = search_return.neighbors_row_splits.long() + + else: + return_dict = self.search_fn(data, queries, radius, self.return_norm) + + return return_dict + + +def native_neighbor_search( + data: torch.Tensor, queries: torch.Tensor, radius: float, return_norm: bool = False +): + """ + Native PyTorch implementation of a neighborhood search + between two arbitrary coordinate meshes. + + Parameters + ---------- + data : torch.Tensor + vector of data points from which to find neighbors + queries : torch.Tensor + centers of neighborhoods + radius : float + size of each neighborhood + """ + nbr_dict = {} + + # compute pairwise distances + all_dists = torch.cdist(queries, data).to(queries.device) # shaped num query points x num data points + # keep zero-distance points + eps = 1e-7 + all_dists = torch.where(all_dists == 0., eps, all_dists) + dists = torch.where(all_dists <= radius, all_dists, 0.) # i,j is 1 if j is i's neighbor + nbr_indices = dists.nonzero()[:,1:].reshape(-1,) # only keep the column indices + if return_norm: + weights = dists[dists.nonzero(as_tuple=True)] + nbr_dict["weights"] = weights **2 # weighting function computed on squared norms + in_nbr = torch.where(dists > 0, 1., 0.,) + nbrhd_sizes = torch.cumsum(torch.sum(in_nbr, dim=1), dim=0) # num points in each neighborhood, summed cumulatively + splits = torch.cat((torch.tensor([0.]).to(queries.device), nbrhd_sizes)) + + nbr_dict["neighbors_index"] = nbr_indices.long().to(queries.device) + nbr_dict["neighbors_row_splits"] = splits.long() + + return nbr_dict diff --git a/sources/neuraloperator/neuralop/layers/normalization_layers.py b/sources/neuraloperator/neuralop/layers/normalization_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..73b895dd7efde4cfab6b0dd69490554ed6ee27a5 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/normalization_layers.py @@ -0,0 +1,165 @@ +import torch +import torch.nn as nn + + +class AdaIN(nn.Module): + """Adaptive Instance Normalization (AdaIN) layer for style transfer in neural operators. + + AdaIN performs instance normalization followed by adaptive scaling and shifting + based on an external embedding vector. This allows for style transfer by + modulating the output characteristics based on a conditioning signal. + + The layer first normalizes the input using instance normalization, then applies + learned scaling (weight) and shifting (bias) parameters derived from an embedding + vector through a multi-layer perceptron. + + Parameters + ---------- + embed_dim : int + Dimension of the embedding vector used for style conditioning + in_channels : int + Number of input channels to normalize + mlp : nn.Module, optional + Multi-layer perceptron that maps embedding to (weight, bias) parameters. + Should output 2*in_channels values. If None, a default MLP is created + with architecture: Linear(embed_dim, 512) -> GELU -> Linear(512, 2*in_channels) + eps : float, optional + Small value added to the denominator for numerical stability in normalization. + Default is 1e-5. + """ + + def __init__(self, embed_dim, in_channels, mlp=None, eps=1e-5): + super().__init__() + self.in_channels = in_channels + self.embed_dim = embed_dim + self.eps = eps + + if mlp is None: + mlp = nn.Sequential( + nn.Linear(embed_dim, 512), + nn.GELU(), + nn.Linear(512, 2*in_channels) + ) + self.mlp = mlp + + self.embedding = None + + def set_embedding(self, x): + """Set the embedding vector for style conditioning.""" + self.embedding = x.reshape(self.embed_dim,) + + def forward(self, x): + """Apply adaptive instance normalization to the input tensor.""" + assert self.embedding is not None, "AdaIN: update embeddding before running forward" + + weight, bias = torch.split(self.mlp(self.embedding), self.in_channels, dim=0) + + return nn.functional.group_norm(x, self.in_channels, weight, bias, eps=self.eps) + + +class InstanceNorm(nn.Module): + """Dimension-agnostic instance normalization layer for neural operators. + + InstanceNorm normalizes each sample in the batch independently, computing + mean and variance across spatial dimensions for each sample and channel + separately. This is useful when the statistical properties of each sample + are distinct and should be treated separately. + + Parameters + ---------- + **kwargs : dict, optional + Additional parameters to pass to torch.nn.functional.instance_norm(). + Common parameters include: + - eps : float, optional + Small value added to the denominator for numerical stability. + Default is 1e-5. + - momentum : float, optional + Value used for the running_mean and running_var computation. + Default is 0.1. + - use_input_stats : bool, optional + If True, use input statistics. Default is True. + - weight : torch.Tensor, optional + Weight tensor for affine transformation. If None, no scaling applied. + - bias : torch.Tensor, optional + Bias tensor for affine transformation. If None, no bias applied. + """ + + def __init__(self, **kwargs): + super().__init__() + self.kwargs = kwargs + + def forward(self, x): + """Apply instance normalization to the input tensor.""" + size = x.shape + x = torch.nn.functional.instance_norm(x, **self.kwargs) + assert x.shape == size + return x + + +class BatchNorm(nn.Module): + """Dimension-agnostic batch normalization layer for neural operators. + + BatchNorm normalizes data across the entire batch, computing a single mean + and standard deviation for all samples combined. This is the most common + form of normalization and is effective when batch statistics are a good + approximation of the overall data distribution. + + For dimensions > 3, the layer automatically flattens spatial dimensions + and uses BatchNorm1d, as PyTorch doesn't implement batch norm for 4D+ tensors. + + Parameters + ---------- + n_dim : int + Spatial dimension of input data (e.g., 1 for 1D, 2 for 2D, 3 for 3D). + Determined by FNOBlocks.n_dim. If n_dim > 3, spatial dimensions are + flattened and BatchNorm1d is used. + num_features : int + Number of channels in the input tensor to be normalized + **kwargs : dict, optional + Additional parameters to pass to the underlying batch normalization layer. + Common parameters include: + - eps : float, optional + Small value added to the denominator for numerical stability. + Default is 1e-5. + - momentum : float, optional + Value used for the running_mean and running_var computation. + Default is 0.1. + - affine : bool, optional + If True, apply learnable affine transformation. Default is True. + - track_running_stats : bool, optional + If True, track running statistics. Default is True. + """ + + def __init__(self, n_dim: int, num_features: int, **kwargs): + super().__init__() + self.n_dim = n_dim + self.num_features = num_features + self.kwargs = kwargs + + if self.n_dim <= 3: + self.norm = getattr(torch.nn, f"BatchNorm{n_dim}d")( + num_features=num_features, **kwargs + ) + else: + print( + "Warning: torch does not implement batch norm for dimensions higher than 3.\ + We manually flatten the spatial dimension of 4+D tensors to apply batch norm. " + ) + self.norm = torch.nn.BatchNorm1d(num_features=num_features, **kwargs) + + def forward(self, x): + """Apply batch normalization to the input tensor.""" + size = x.shape + num_channels = size[1] + + # in 4+D, we flatten and use batchnorm1d. + if self.n_dim >= 4: + x = x.reshape(size[0], size[1], -1) + x = self.norm(x) + + # if flattening occurred, unflatten + if self.n_dim >= 4: + x = x.reshape(size) + + assert x.shape == size + return x diff --git a/sources/neuraloperator/neuralop/layers/padding.py b/sources/neuraloperator/neuralop/layers/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..369d2be87e8a07785017b7a2a61e5b71d8172191 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/padding.py @@ -0,0 +1,133 @@ +from typing import List, Union + +from torch import nn +from torch.nn import functional as F + +from neuralop.utils import validate_scaling_factor + + +class DomainPadding(nn.Module): + """Applies domain padding scaled automatically to the input's resolution. + + Parameters + ---------- + domain_padding : float or list + Typically, between zero and one, percentage of padding to use + if a list, make sure if matches the dim of (d1, ..., dN) + resolution_scaling_factor : int, optional + Resolution scaling factor, by default 1 + + Notes + ----- + This class works for any input resolution. Expects inputs of shape + (batch-size, channels, d1, ...., dN) + """ + + def __init__( + self, + domain_padding: Union[float, list], + resolution_scaling_factor: Union[int, List[int]] = 1, + ): + super().__init__() + self.domain_padding = domain_padding + if resolution_scaling_factor is None: + resolution_scaling_factor = 1 + self.resolution_scaling_factor: Union[int, List[int]] = resolution_scaling_factor + + # dict(f'{resolution}'=padding) such that padded = F.pad(x, indices) + self._padding = dict() + + # dict(f'{resolution}'=indices_to_unpad) such that unpadded = x[indices] + self._unpad_indices = dict() + + def forward(self, x): + """ + forward pass: pad the input + """ + self.pad(x) + + def pad(self, x, verbose=False): + """Take an input and pad it by the desired fraction + + The amount of padding will be automatically scaled with the resolution + """ + resolution = x.shape[2:] + + # if domain_padding is list, then to pass on + if isinstance(self.domain_padding, (float, int)): + self.domain_padding = [float(self.domain_padding)] * len(resolution) + + assert len(self.domain_padding) == len(resolution), ( + "domain_padding length must match the number of spatial/time dimensions " + "(excluding batch, ch)" + ) + + resolution_scaling_factor = self.resolution_scaling_factor + if not isinstance(self.resolution_scaling_factor, list): + # if unset by the user, scaling_factor will be 1 be default, + # so `resolution_scaling_factor` should never be None. + resolution_scaling_factor: List[float] = validate_scaling_factor( + self.resolution_scaling_factor, len(resolution), n_layers=None + ) + + try: + padding = self._padding[f"{resolution}"] + return F.pad(x, padding, mode="constant") + + except KeyError: + padding = [round(p * r) for (p, r) in zip(self.domain_padding, resolution)] + + if verbose: + print( + f"Padding inputs of resolution={resolution} with " + f"padding={padding}, symmetric" + ) + + output_pad = padding + + output_pad = [ + round(i * j) for (i, j) in zip(resolution_scaling_factor, output_pad) + ] + + # padding is being applied in reverse order + # (so we must reverse the padding list) + padding = padding[::-1] + + # the F.pad(x, padding) funtion pads the tensor 'x' in reverse order + # of the "padding" list i.e. the last axis of tensor 'x' will be + # padded by the amount mention at the first position of the + # 'padding' vector. The details about F.pad can be found here: + # https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + + # Pad both sides (symmetric mode) + unpad_list = list() + for p in output_pad: + if p == 0: + padding_end = None + padding_start = None + else: + padding_end = p + padding_start = -p + unpad_list.append(slice(padding_end, padding_start, None)) + unpad_indices = (Ellipsis,) + tuple(unpad_list) + + padding = [i for p in padding for i in (p, p)] + + self._padding[f"{resolution}"] = padding + + padded = F.pad(x, padding, mode="constant") + + output_shape = padded.shape[2:] + + output_shape = [ + round(i * j) for (i, j) in zip(resolution_scaling_factor, output_shape) + ] + + self._unpad_indices[f"{[i for i in output_shape]}"] = unpad_indices + + return padded + + def unpad(self, x): + """Remove the padding from padding inputs""" + unpad_indices = self._unpad_indices[f"{list(x.shape[2:])}"] + return x[unpad_indices] diff --git a/sources/neuraloperator/neuralop/layers/resample.py b/sources/neuraloperator/neuralop/layers/resample.py new file mode 100644 index 0000000000000000000000000000000000000000..d840ec4ccca0cb8615f58533666803b6a4876e2d --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/resample.py @@ -0,0 +1,102 @@ +import numpy as np +import itertools +import torch +import torch.nn.functional as F + + +def resample(x, res_scale, axis, output_shape=None): + """A module for generic n-dimentional interpolation. + + For 1D and 2D inputs, the ``resample`` function uses PyTorch’s built-in spatial interpolators + for efficiency, applying linear interpolation for 1D data and bicubic interpolation for 2D data + directly in the spatial domain. + + For 3D or higher-dimensional inputs, the ``resample`` function switches to a spectral interpolation + method based on the Fourier transform. The input is transformed into the frequency domain using a + real n-dimensional FFT, which decomposes the signal into its frequency components. By resizing + this frequency representation and then applying an inverse FFT, the function achieves smooth, + alias-free interpolation that preserves the signal’s overall structure. + + Parameters + ---------- + x : torch.Tensor + input activation of size (batch_size, channels, d1, ..., dN) + res_scale: int or tuple + Scaling factor along each of the dimensions in 'axis' parameter. If res_scale is scaler, then isotropic + scaling is performed + axis: axis or dimensions along which interpolation will be performed. + output_shape : None or tuple[int] + """ + + if isinstance(res_scale, (float, int)): + if axis is None: + axis = list(range(2, x.ndim)) + res_scale = [res_scale] * len(axis) + elif isinstance(axis, int): + axis = [axis] + res_scale = [res_scale] + else: + res_scale = [res_scale] * len(axis) + else: + assert len(res_scale) == len(axis), "leght of res_scale and axis are not same" + + old_size = x.shape[-len(axis) :] + if output_shape is None: + new_size = tuple([int(round(s * r)) for (s, r) in zip(old_size, res_scale)]) + else: + new_size = output_shape + + if len(axis) == 1: + return F.interpolate(x, size=new_size[0], mode="linear", align_corners=True) + if len(axis) == 2: + return F.interpolate(x, size=new_size, mode="bicubic", align_corners=True) + + X = torch.fft.rfftn(x.float(), norm="forward", dim=axis) + + new_fft_size = list(new_size) + new_fft_size[-1] = new_fft_size[-1] // 2 + 1 # Redundant last coefficient + new_fft_size_c = [min(i, j) for (i, j) in zip(new_fft_size, X.shape[-len(axis) :])] + out_fft = torch.zeros( + [x.shape[0], x.shape[1], *new_fft_size], device=x.device, dtype=torch.cfloat + ) + + mode_indexing = [((None, m//2), (-m//2, None)) for m in new_fft_size_c[:-1]] + [((None, new_fft_size_c[-1]), )] + for i, boundaries in enumerate(itertools.product(*mode_indexing)): + idx_tuple = [slice(None), slice(None)] + [slice(*b) for b in boundaries] + + idx_tuple = tuple(idx_tuple) + out_fft[idx_tuple] = X[idx_tuple] + y = torch.fft.irfftn(out_fft, s=new_size, norm="forward", dim=axis) + + return y + + +def iterative_resample(x, res_scale, axis): + if isinstance(axis, list) and isinstance(res_scale, (float, int)): + res_scale = [res_scale] * len(axis) + if not isinstance(axis, list) and isinstance(res_scale,list): + raise Exception("Axis is not a list but Scale factors are") + if isinstance(axis, list) and isinstance(res_scale,list) and len(res_scale) != len(axis): + raise Exception("Axis and Scal factor are in different sizes") + + if isinstance(axis, list): + for i in range(len(res_scale)): + rs = res_scale[i] + a = axis[i] + x = resample(x, rs, a) + return x + + old_res = x.shape[axis] + X = torch.fft.rfft(x, dim=axis, norm="forward") + newshape = list(x.shape) + new_res = int(round(res_scale * newshape[axis])) + newshape[axis] = new_res // 2 + 1 + + Y = torch.zeros(newshape, dtype=X.dtype, device=x.device) + + modes = min(new_res, old_res) + sl = [slice(None)] * x.ndim + sl[axis] = slice(0, modes // 2 + 1) + Y[tuple(sl)] = X[tuple(sl)] + y = torch.fft.irfft(Y, n=new_res, dim=axis, norm="forward") + return y diff --git a/sources/neuraloperator/neuralop/layers/rno_block.py b/sources/neuraloperator/neuralop/layers/rno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..155df63499b2130e095fab29674ec01ab8136bea --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/rno_block.py @@ -0,0 +1,432 @@ +import torch +import numpy as np +import torch.nn as nn +import torch.nn.functional as F + +from ..layers.spectral_convolution import SpectralConv +from ..layers.fno_block import FNOBlocks +from ..layers.complex import cselu + + +class RNOCell(nn.Module): + """N-Dimensional Recurrent Neural Operator cell. The RNO cell takes in an + input and history function, and it outputs the next step of the hidden function. + + The RNO cell implements the GRU-like recurrence relation with Fourier layers: + z_t = σ(f1(x_t) + f2(h_{t-1}) + b1) [update gate] + r_t = σ(f3(x_t) + f4(h_{t-1}) + b2) [reset gate] + h̃_t = selu(f5(x_t) + f6(r_t ⊙ h_{t-1}) + b3) [candidate state] + h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ h̃_t [next state] + + where σ is the sigmoid function, ⊙ is element-wise multiplication, + and f1-f6 are FNO blocks (Fourier neural operators). + + Parameters + ---------- + n_modes : int tuple + number of modes to keep in Fourier Layer, along each dimension + The dimensionality of the RNO is inferred from ``len(n_modes)`` + hidden_channels : int + number of hidden channels in the RNO + + Other Parameters + ---------------- + resolution_scaling_factor : Union[Number, List[Number]], optional + Factor by which to scale outputs for super-resolution, by default None + max_n_modes : int or List[int], optional + Maximum number of modes to keep along each dimension, by default None + fno_block_precision : str, optional + Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full" + use_channel_mlp : bool, optional + Whether to use an MLP layer after each FNO block, by default True + channel_mlp_dropout : float, optional + Dropout parameter for self.channel_mlp, by default 0 + channel_mlp_expansion : float, optional + Expansion parameter for self.channel_mlp, by default 0.5 + non_linearity : torch.nn.F module, optional + Nonlinear activation function to use between layers, by default F.gelu + stabilizer : Literal["tanh"], optional + Stabilizing module to use between certain layers. Options: "tanh", None, by default None + norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + ada_in_features : int, optional + Number of features for adaptive instance norm above, by default None + preactivation : bool, optional + 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, optional + 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, optional + 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 + complex_data : bool, optional + Whether the FNO's data takes on complex values in space, by default False + separable : bool, optional + Separable parameter for SpectralConv, by default False + factorization : str, optional + Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None + rank : float, optional + Rank parameter for SpectralConv, by default 1.0 + conv_module : BaseConv, optional + Module to use for convolutions in FNO block, by default SpectralConv + joint_factorization : bool, optional + Whether to factorize all spectralConv weights as one tensor, by default False + fixed_rank_modes : bool, optional + Fixed_rank_modes parameter for SpectralConv, by default False + implementation : str, optional + Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized" + decomposition_kwargs : dict, optional + Kwargs for tensor decomposition in SpectralConv, by default dict() + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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. + + References + ---------- + .. [1] Paper: https://arxiv.org/abs/2308.08794 + """ + + def __init__( + self, + n_modes, + hidden_channels, + resolution_scaling_factor=None, + max_n_modes=None, + fno_block_precision="full", + use_channel_mlp=True, + channel_mlp_dropout=0, + channel_mlp_expansion=0.5, + non_linearity=F.gelu, + stabilizer=None, + norm=None, + norm_groups=1, + ada_in_features=None, + preactivation=False, + fno_skip="linear", + channel_mlp_skip="soft-gating", + complex_data=False, + separable=False, + factorization=None, + rank=1.0, + conv_module=SpectralConv, + fixed_rank_modes=False, + implementation="factorized", + decomposition_kwargs=dict(), + enforce_hermitian_symmetry=True, + ): + super().__init__() + self.hidden_channels = hidden_channels + scaling_factor = ( + None if not resolution_scaling_factor else [resolution_scaling_factor] + ) + fno_kwargs = { + "n_layers": 1, + "max_n_modes": max_n_modes, + "fno_block_precision": fno_block_precision, + "use_channel_mlp": use_channel_mlp, + "channel_mlp_dropout": channel_mlp_dropout, + "channel_mlp_expansion": channel_mlp_expansion, + "non_linearity": non_linearity, + "stabilizer": stabilizer, + "norm": norm, + "norm_groups": norm_groups, + "preactivation": preactivation, + "fno_skip": fno_skip, + "channel_mlp_skip": channel_mlp_skip, + "complex_data": complex_data, + "separable": separable, + "factorization": factorization, + "rank": rank, + "conv_module": conv_module, + "fixed_rank_modes": fixed_rank_modes, + "implementation": implementation, + "decomposition_kwargs": decomposition_kwargs, + "enforce_hermitian_symmetry": enforce_hermitian_symmetry, + } + + # For super-resolution: the hidden state h is always stored at the scaled resolution, + # while input x remains at the original resolution. Therefore, only f1, f3, and f5 + # (which process x) need resolution scaling, while f2, f4, and f6 (which process h) + # operate at the already-scaled resolution. + + self.input_gates = nn.ModuleList() + self.hidden_gates = nn.ModuleList() + self.biases = nn.ParameterList() + + # 3 gates: Update (z), Reset (r), Candidate (h_tilde) + # Each gate involves one FNOBlock processing x (input_gate) + # and one FNOBlock processing h (hidden_gate) + for _ in range(3): + self.input_gates.append( + FNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=n_modes, + resolution_scaling_factor=scaling_factor, + **fno_kwargs, + ) + ) + self.hidden_gates.append( + FNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=n_modes, + resolution_scaling_factor=None, + **fno_kwargs, + ) + ) + if complex_data: + self.biases.append(nn.Parameter(torch.randn(()) + 1j * torch.randn(()))) + else: + self.biases.append(nn.Parameter(torch.randn(()))) + + def forward(self, x, h): + """Forward pass for RNO cell. + + Parameters + ---------- + x : torch.Tensor + Input function at current timestep with shape (batch, hidden_channels, *spatial_dims) + h : torch.Tensor + Hidden state from previous timestep with shape (batch, hidden_channels, *spatial_dims_h) + where spatial_dims_h may differ from spatial_dims if resolution_scaling_factor is set + + Returns + ------- + torch.Tensor + Updated hidden state with shape (batch, hidden_channels, *spatial_dims_h) + """ + # Update gate + update_gate = torch.sigmoid( + self.input_gates[0](x) + self.hidden_gates[0](h) + self.biases[0] + ) + + # Reset gate + reset_gate = torch.sigmoid( + self.input_gates[1](x) + self.hidden_gates[1](h) + self.biases[1] + ) + + # Candidate state + h_combined = self.input_gates[2](x) + self.hidden_gates[2](reset_gate * h) + self.biases[2] + + if x.dtype == torch.cfloat: + candidate_state = cselu(h_combined) # complex SELU for complex data + else: + candidate_state = F.selu(h_combined) # regular SELU for real data + + h_next = (1.0 - update_gate) * h + update_gate * candidate_state + + return h_next + + +class RNOBlock(nn.Module): + """N-Dimensional Recurrent Neural Operator layer. The RNO layer extends the + action of the RNO cell to take in some sequence of time-steps as input + and output the next output function. + + The layer applies the RNO cell recurrently over a sequence of inputs: + For t = 1 to T: + h_t = RNOCell(x_t, h_{t-1}) + + where the cell implements: + z_t = σ(f1(x_t) + f2(h_{t-1}) + b1) [update gate] + r_t = σ(f3(x_t) + f4(h_{t-1}) + b2) [reset gate] + h̃_t = selu(f5(x_t) + f6(r_t ⊙ h_{t-1}) + b3) [candidate state] + h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ h̃_t [next state] + + Parameters + ---------- + n_modes : int tuple + number of modes to keep in Fourier Layer, along each dimension + The dimensionality of the RNO is inferred from ``len(n_modes)`` + hidden_channels : int + number of hidden channels in the RNO + return_sequences : boolean, optional + Whether to return the sequence of hidden states associated with processing + the inputs sequence of functions. Default: False + + Other Parameters + ---------------- + resolution_scaling_factor : Union[Number, List[Number]], optional + Factor by which to scale outputs for super-resolution, by default None + max_n_modes : int or List[int], optional + Maximum number of modes to keep along each dimension, by default None + fno_block_precision : str, optional + Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full" + use_channel_mlp : bool, optional + Whether to use an MLP layer after each FNO block, by default True + channel_mlp_dropout : float, optional + Dropout parameter for self.channel_mlp, by default 0 + channel_mlp_expansion : float, optional + Expansion parameter for self.channel_mlp, by default 0.5 + non_linearity : torch.nn.F module, optional + Nonlinear activation function to use between layers, by default F.gelu + stabilizer : Literal["tanh"], optional + Stabilizing module to use between certain layers. Options: "tanh", None, by default None + norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + ada_in_features : int, optional + Number of features for adaptive instance norm above, by default None + preactivation : bool, optional + 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, optional + 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, optional + 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 + complex_data : bool, optional + Whether the FNO's data takes on complex values in space, by default False + separable : bool, optional + Separable parameter for SpectralConv, by default False + factorization : str, optional + Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None + rank : float, optional + Rank parameter for SpectralConv, by default 1.0 + conv_module : BaseConv, optional + Module to use for convolutions in FNO block, by default SpectralConv + joint_factorization : bool, optional + Whether to factorize all spectralConv weights as one tensor, by default False + fixed_rank_modes : bool, optional + Fixed_rank_modes parameter for SpectralConv, by default False + implementation : str, optional + Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized" + decomposition_kwargs : dict, optional + Kwargs for tensor decomposition in SpectralConv, by default dict() + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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. + + References + ---------- + .. [1] Paper: https://arxiv.org/abs/2308.08794 + """ + + def __init__( + self, + n_modes, + hidden_channels, + return_sequences=False, + resolution_scaling_factor=None, + max_n_modes=None, + fno_block_precision="full", + use_channel_mlp=True, + channel_mlp_dropout=0, + channel_mlp_expansion=0.5, + non_linearity=F.gelu, + stabilizer=None, + norm=None, + norm_groups=1, + ada_in_features=None, + preactivation=False, + fno_skip="linear", + channel_mlp_skip="soft-gating", + complex_data=False, + separable=False, + factorization=None, + rank=1.0, + conv_module=SpectralConv, + fixed_rank_modes=False, + implementation="factorized", + decomposition_kwargs=dict(), + enforce_hermitian_symmetry=True, + ): + super().__init__() + + self.hidden_channels = hidden_channels + self.return_sequences = return_sequences + self.resolution_scaling_factor = resolution_scaling_factor + + self.cell = RNOCell( + n_modes, + hidden_channels, + resolution_scaling_factor=resolution_scaling_factor, + max_n_modes=max_n_modes, + fno_block_precision=fno_block_precision, + use_channel_mlp=use_channel_mlp, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + stabilizer=stabilizer, + norm=norm, + norm_groups=norm_groups, + preactivation=preactivation, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + complex_data=complex_data, + separable=separable, + factorization=factorization, + rank=rank, + conv_module=conv_module, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + decomposition_kwargs=decomposition_kwargs, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ) + if complex_data: + self.bias_h = nn.Parameter(torch.randn(()) + 1j * torch.randn(())) + else: + self.bias_h = nn.Parameter(torch.randn(())) + + def forward(self, x, h=None): + """Forward pass for RNO layer. + + Parameters + ---------- + x : torch.Tensor + Input sequence with shape (batch, timesteps, hidden_channels, *spatial_dims) + h : torch.Tensor, optional + Initial hidden state with shape (batch, hidden_channels, *spatial_dims_h). + If None, initialized to zeros with added bias. Default: None + + Returns + ------- + torch.Tensor + If return_sequences=True: hidden states for all timesteps with shape + (batch, timesteps, hidden_channels, *spatial_dims_h) + If return_sequences=False: final hidden state with shape + (batch, hidden_channels, *spatial_dims_h) + """ + batch_size, timesteps, dim = x.shape[:3] + dom_sizes = x.shape[3:] + + # Initialize hidden state if not provided + if h is None: + # Compute the spatial dimensions for h (scaled if resolution_scaling_factor is set) + if not self.resolution_scaling_factor: + h_shape = (batch_size, self.hidden_channels, *dom_sizes) + else: + scaled_sizes = tuple( + [int(round(self.resolution_scaling_factor * s)) for s in dom_sizes] + ) + h_shape = (batch_size, self.hidden_channels, *scaled_sizes) + h = torch.zeros(h_shape, dtype=x.dtype).to(x.device) + h += self.bias_h + + outputs = [] + # Process each timestep sequentially through the RNO cell + for i in range(timesteps): + h = self.cell(x[:, i], h) # Update hidden state with current input + if self.return_sequences: + outputs.append(h) + + if self.return_sequences: + return torch.stack(outputs, dim=1) + else: + return h diff --git a/sources/neuraloperator/neuralop/layers/segment_csr.py b/sources/neuraloperator/neuralop/layers/segment_csr.py new file mode 100644 index 0000000000000000000000000000000000000000..775e3e57964ebda20c2c7a7ea9c582015c7b9ad2 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/segment_csr.py @@ -0,0 +1,98 @@ +from typing import Literal +import importlib + +import torch +from torch import einsum + + +def segment_csr( + src: torch.Tensor, + indptr: torch.Tensor, + reduction: Literal["mean", "sum"], + use_scatter=True, +): + """segment_csr reduces all entries of a CSR-formatted + matrix by summing or averaging over neighbors. + + Used to reduce features over neighborhoods + in neuralop.layers.IntegralTransform + + If use_scatter is set to False or torch_scatter is not + properly built, segment_csr falls back to a naive PyTorch implementation + + Note: the native version is mainly intended for running tests on + CPU-only GitHub CI runners to get around a versioning issue. + torch_scatter should be installed and built if possible. + + Parameters + ---------- + src : torch.Tensor + tensor of features for each point + indptr : torch.Tensor + splits representing start and end indices + of each neighborhood in src + reduction : Literal['mean', 'sum'] + How to reduce a neighborhood. Options: 'mean', 'sum'. If mean, + reduce by taking the average of all neighbors. Otherwise take the sum. + use_scatter : bool, optional + Whether to use torch-scatter.segment_csr. If False, uses native Python reduction, by default True + + .. warning:: + + torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch, + so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency` + for more information. + """ + if reduction not in ["mean", "sum"]: + raise ValueError("reduce must be one of 'mean', 'sum'") + + if importlib.util.find_spec("torch_scatter") is not None and use_scatter: + """only import torch_scatter when cuda is available""" + import torch_scatter.segment_csr as scatter_segment_csr + + return scatter_segment_csr(src, indptr, reduce=reduction) + + else: + if use_scatter: + print( + "Warning: use_scatter is True but torch_scatter is not properly built. \ + Defaulting to naive PyTorch implementation" + ) + # if batched, shape [b, n_reps, channels] + # otherwise shape [n_reps, channels] + if src.ndim == 3: + batched = True + point_dim = 1 + else: + batched = False + point_dim = 0 + + # if batched, shape [b, n_out, channels] + # otherwise shape [n_out, channels] + output_shape = list(src.shape) + n_out = indptr.shape[point_dim] - 1 + output_shape[point_dim] = n_out + + out = torch.zeros(output_shape, device=src.device) + + for i in range(n_out): + # reduce all indices pointed to in indptr from src into out + if batched: + from_idx = (slice(None), slice(indptr[0, i], indptr[0, i + 1])) + ein_str = "bio->bo" + start = indptr[0, i] + n_nbrs = indptr[0, i + 1] - start + to_idx = (slice(None), i) + else: + from_idx = slice(indptr[i], indptr[i + 1]) + ein_str = "io->o" + start = indptr[i] + n_nbrs = indptr[i + 1] - start + to_idx = i + src_from = src[from_idx] + if n_nbrs > 0: + to_reduce = einsum(ein_str, src_from) + if reduction == "mean": + to_reduce /= n_nbrs + out[to_idx] += to_reduce + return out diff --git a/sources/neuraloperator/neuralop/layers/skip_connections.py b/sources/neuraloperator/neuralop/layers/skip_connections.py new file mode 100644 index 0000000000000000000000000000000000000000..815de272feef20debafb94fbd4f697f0b7848ea0 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/skip_connections.py @@ -0,0 +1,130 @@ +import torch +from torch import nn + + +def skip_connection( + in_features, out_features, n_dim=2, bias=False, skip_type="soft-gating" +): + """A wrapper for several types of skip connections. + Returns an nn.Module skip connections, one of {'identity', 'linear', soft-gating'} + + Parameters + ---------- + in_features : int + Number of input features + out_features : int + Number of output features + n_dim : int, optional + Dimensionality of the input (excluding batch-size and channels). + n_dim=2 corresponds to having Module2D, by default 2 + bias : bool, optional + Whether to use a bias, by default False + skip_type : {'identity', 'linear', 'soft-gating'}, optional + Kind of skip connection to use. Options: 'identity', 'linear', 'soft-gating', by default "soft-gating" + + Returns + ------- + nn.Module + module that takes in x and returns skip(x) + """ + if skip_type.lower() == "soft-gating": + return SoftGating( + in_features=in_features, + out_features=out_features, + bias=bias, + n_dim=n_dim, + ) + elif skip_type.lower() == "linear": + return Flattened1dConv( + in_channels=in_features, + out_channels=out_features, + kernel_size=1, + bias=bias, + ) + elif skip_type.lower() == "identity": + return nn.Identity() + else: + raise ValueError( + f"Got skip-connection type={skip_type}, expected one of" + f" {'soft-gating', 'linear', 'id'}." + ) + + +class SoftGating(nn.Module): + """Applies soft-gating by weighting the channels of the given input. + + Given an input x of size `(batch-size, channels, height, width)`, + this returns `x * w ` + where w is of shape `(1, channels, 1, 1)` + + Parameters + ---------- + in_features : int + Number of input features + out_features : None + This is provided for API compatibility with nn.Linear only + n_dim : int, optional + Dimensionality of the input (excluding batch-size and channels). + n_dim=2 corresponds to having Module2D, by default 2 + bias : bool, optional + Whether to use a bias, by default False + """ + + def __init__(self, in_features, out_features=None, n_dim=2, bias=False): + super().__init__() + if out_features is not None and in_features != out_features: + raise ValueError( + f"Got in_features={in_features} and out_features={out_features}, " + "but these two must be the same for soft-gating" + ) + self.in_features = in_features + self.out_features = out_features + self.weight = nn.Parameter(torch.ones(1, self.in_features, *(1,) * n_dim)) + if bias: + self.bias = nn.Parameter(torch.ones(1, self.in_features, *(1,) * n_dim)) + else: + self.bias = None + + def forward(self, x): + """Applies soft-gating to a batch of activations""" + if self.bias is not None: + return self.weight * x + self.bias + else: + return self.weight * x + + +class Flattened1dConv(nn.Module): + def __init__(self, in_channels: int, out_channels: int, kernel_size, bias=False): + """Flattened1dConv is a Conv-based skip layer for + input tensors of ndim > 3 (batch, channels, d1, ...) that flattens all dimensions + past the batch and channel dims into one dimension, applies the Conv1d, + and un-flattens. + + Parameters + ---------- + in_channels : int + in_channels of Conv1d + out_channels : int + out_channels of Conv1d + kernel_size : int + kernel_size of Conv1d + bias : bool, optional + bias of Conv1d, by default False + """ + super().__init__() + self.conv = nn.Conv1d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + bias=bias, + ) + + def forward(self, x): + # x.shape: b, c, x1, ..., xn x_ndim > 1 + size = list(x.shape) + # flatten everything past 1st data dim + x = x.view(*size[:2], -1) + x = self.conv(x) + # reshape x into an Nd tensor b, c, x1, x2, ... + x = x.view(size[0], self.conv.out_channels, *size[2:]) + return x diff --git a/sources/neuraloperator/neuralop/layers/spectral_convolution.py b/sources/neuraloperator/neuralop/layers/spectral_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..7e50258f208f33202677c272eabd97716d4512b4 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/spectral_convolution.py @@ -0,0 +1,570 @@ +from typing import List, Optional, Tuple, Union + +from ..utils import validate_scaling_factor + +import torch +from torch import nn + +import tensorly as tl +from tensorly.plugins import use_opt_einsum +from tltorch.factorized_tensors.core import FactorizedTensor + +from .einsum_utils import einsum_complexhalf +from .base_spectral_conv import BaseSpectralConv +from .resample import resample + +tl.set_backend("pytorch") +use_opt_einsum("optimal") +einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + + +def _contract_dense(x, weight, separable=False): + order = tl.ndim(x) + # batch-size, in_channels, x, y... + x_syms = list(einsum_symbols[:order]) + + # in_channels, out_channels, x, y... + weight_syms = list(x_syms[1:]) # no batch-size + + # batch-size, out_channels, x, y... + if separable: + out_syms = [x_syms[0]] + list(weight_syms) + else: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + + eq = f'{"".join(x_syms)},{"".join(weight_syms)}->{"".join(out_syms)}' + + if not torch.is_tensor(weight): + weight = weight.to_tensor() + + if x.dtype == torch.complex32: + # if x is half precision, run a specialized einsum + return einsum_complexhalf(eq, x, weight) + else: + return tl.einsum(eq, x, weight) + + +def _contract_dense_separable(x, weight, separable): + if not torch.is_tensor(weight): + weight = weight.to_tensor() + return x * weight + + +def _contract_cp(x, cp_weight, separable=False): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + rank_sym = einsum_symbols[order] + out_sym = einsum_symbols[order + 1] + out_syms = list(x_syms) + if separable: + factor_syms = [einsum_symbols[1] + rank_sym] # in only + else: + out_syms[1] = out_sym + factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out + factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ... + eq = f'{x_syms},{rank_sym},{",".join(factor_syms)}->{"".join(out_syms)}' + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, cp_weight.weights, *cp_weight.factors) + else: + return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors) + + +def _contract_tucker(x, tucker_weight, separable=False): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + out_sym = einsum_symbols[order] + out_syms = list(x_syms) + if separable: + core_syms = einsum_symbols[order + 1 : 2 * order] + # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only + # x, y, ... + factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)] + + else: + core_syms = einsum_symbols[order + 1 : 2 * order + 1] + out_syms[1] = out_sym + factor_syms = [ + einsum_symbols[1] + core_syms[0], + out_sym + core_syms[1], + ] # out, in + # x, y, ... + factor_syms += [xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])] + + eq = f'{x_syms},{core_syms},{",".join(factor_syms)}->{"".join(out_syms)}' + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, tucker_weight.core, *tucker_weight.factors) + else: + return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors) + + +def _contract_tt(x, tt_weight, separable=False): + order = tl.ndim(x) + + x_syms = list(einsum_symbols[:order]) + weight_syms = list(x_syms[1:]) # no batch-size + if not separable: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + else: + out_syms = list(x_syms) + rank_syms = list(einsum_symbols[order + 1 :]) + tt_syms = [] + for i, s in enumerate(weight_syms): + tt_syms.append([rank_syms[i], s, rank_syms[i + 1]]) + eq = ( + "".join(x_syms) + + "," + + ",".join("".join(f) for f in tt_syms) + + "->" + + "".join(out_syms) + ) + + if x.dtype == torch.complex32: + return einsum_complexhalf(eq, x, *tt_weight.factors) + else: + return tl.einsum(eq, x, *tt_weight.factors) + + +def get_contract_fun(weight, implementation="reconstructed", separable=False): + """Generic ND implementation of Fourier Spectral Conv contraction + + Parameters + ---------- + weight : tensorly-torch's FactorizedTensor + implementation : {'reconstructed', 'factorized'}, default is 'reconstructed' + whether to reconstruct the weight and do a forward pass (reconstructed) + or contract directly the factors of the factorized weight with the input (factorized) + separable: bool + if True, performs contraction with individual tensor factors. + if False, + Returns + ------- + function : (x, weight) -> x * weight in Fourier space + """ + if implementation == "reconstructed": + if separable: + return _contract_dense_separable + else: + return _contract_dense + elif implementation == "factorized": + if torch.is_tensor(weight): + return _contract_dense + elif isinstance(weight, FactorizedTensor): + if weight.name.lower().endswith("dense"): + return _contract_dense + elif weight.name.lower().endswith("tucker"): + return _contract_tucker + elif weight.name.lower().endswith("tt"): + return _contract_tt + elif weight.name.lower().endswith("cp"): + return _contract_cp + else: + raise ValueError(f"Got unexpected factorized weight type {weight.name}") + else: + raise ValueError( + f"Got unexpected weight type of class {weight.__class__.__name__}" + ) + else: + raise ValueError( + f'Got implementation={implementation}, expected "reconstructed" or "factorized"' + ) + + +Number = Union[int, float] + + +class SpectralConv(BaseSpectralConv): + """SpectralConv implements the Spectral Convolution component of a Fourier layer + described. + + It is implemented as described in [1]_ and [2]_. + + Parameters + ---------- + in_channels : int + Number of input channels + out_channels : int + Number of output channels + n_modes : int or int tuple + Number of modes to use for contraction in Fourier domain during training. + + .. warning:: + + We take care of the redundancy in the Fourier modes, therefore, for an input + of size I_1, ..., I_N, please provide modes M_K that are I_1 < M_K <= I_N + We will automatically keep the right amount of modes: specifically, for the + last mode only, if you specify M_N modes we will use M_N // 2 + 1 modes + as the real FFT is redundant along that last dimension. See the theory guide for mode truncation details. + + + .. note:: + + Provided modes should be even integers. odd numbers will be rounded to the closest even number. + + This can be updated dynamically during training. + + complex_data : bool, optional + Whether data takes on complex values in the spatial domain, by default False. + If True, uses different logic for FFT contraction and uses full FFT instead of real-valued. + max_n_modes : int tuple or None, optional + If not None, maximum number of modes to keep in Fourier Layer along each dim + (n_modes cannot be increased beyond that). If None, all n_modes are used. + By default None. + bias : bool, optional + Whether to add a learnable bias to the output, by default True. + separable : bool, optional + Whether to use separable implementation of contraction. + If True, contracts factors of factorized tensor weight individually. + By default False. + resolution_scaling_factor : float, list of float, or None, optional + Scaling factor(s) for resolution scaling. If provided, the output resolution + will be scaled by this factor along each spatial dimension. + By default None. + fno_block_precision : str, optional + Precision mode for FNO block operations. Options: 'full', 'half', 'mixed'. + By default 'full'. + rank : float, optional + Rank of the tensor factorization of the Fourier weights, by default 1.0. + Ignored if ``factorization is None``. + factorization : str or None, optional + Tensor factorization type. Options: {'tucker', 'cp', 'tt'}. + If None, a single dense weight is learned for the FNO. + Otherwise, that weight, used for the contraction in the Fourier domain + is learned in factorized form. In that case, `factorization` is the + tensor factorization of the parameters weight used. + By default None. + implementation : {'factorized', 'reconstructed'}, optional + If factorization is not None, forward mode to use: + * `reconstructed` : the full weight tensor is reconstructed from the + factorization and used for the forward pass + * `factorized` : the input is directly contracted with the factors of + the decomposition + Ignored if ``factorization is None``. + By default 'reconstructed'. + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. 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. + Setting to True splits the inverse FFT into ifftn along (n-1) dimensions + followed by irfft on the last dimension, with a small computational overhead. + By default True. + fixed_rank_modes : bool, optional + Modes to not factorize, by default False. + Ignored if ``factorization is None``. + decomposition_kwargs : dict or None, optional + Optional additional parameters to pass to the tensor decomposition. + Ignored if ``factorization is None``. + By default None. + init_std : float or 'auto', optional + Standard deviation to use for weight initialization, by default 'auto'. + If 'auto', uses (2 / (in_channels + out_channels)) ** 0.5. + fft_norm : str, optional + FFT normalization parameter, by default 'forward'. + device : torch.device or None, optional + Device to place the layer on, by default None. + + 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. + """ + + def __init__( + self, + in_channels, + out_channels, + n_modes, + complex_data=False, + max_n_modes=None, + bias=True, + separable=False, + resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None, + fno_block_precision="full", + rank=1.0, + factorization=None, + implementation="reconstructed", + enforce_hermitian_symmetry=True, + fixed_rank_modes=False, + decomposition_kwargs: Optional[dict] = None, + init_std="auto", + fft_norm="forward", + device=None, + ): + super().__init__(device=device) + + self.in_channels = in_channels + self.out_channels = out_channels + + self.complex_data = complex_data + + # n_modes is the total number of modes kept along each dimension + self.n_modes = n_modes + self.order = len(self.n_modes) + + if max_n_modes is None: + max_n_modes = self.n_modes + elif isinstance(max_n_modes, int): + max_n_modes = [max_n_modes] + self.max_n_modes = max_n_modes + + self.fno_block_precision = fno_block_precision + self.rank = rank + self.factorization = factorization + self.implementation = implementation + self.enforce_hermitian_symmetry = enforce_hermitian_symmetry + + self.resolution_scaling_factor: Union[ + None, List[List[float]] + ] = validate_scaling_factor(resolution_scaling_factor, self.order) + + if init_std == "auto": + init_std = (2 / (in_channels + out_channels)) ** 0.5 + + if isinstance(fixed_rank_modes, bool): + if fixed_rank_modes: + # If bool, keep the number of layers fixed + fixed_rank_modes = [0] + else: + fixed_rank_modes = None + self.fft_norm = fft_norm + + if factorization is None: + factorization = "Dense" # No factorization + + if separable: + if in_channels != out_channels: + raise ValueError( + "To use separable Fourier Conv, in_channels must be equal " + f"to out_channels, but got in_channels={in_channels} and " + f"out_channels={out_channels}", + ) + weight_shape = (in_channels, *max_n_modes) + else: + weight_shape = (in_channels, out_channels, *max_n_modes) + self.separable = separable + + tensor_kwargs = decomposition_kwargs if decomposition_kwargs is not None else {} + + # Create/init spectral weight tensor + self.weight = FactorizedTensor.new( + weight_shape, + rank=self.rank, + factorization=factorization, + fixed_rank_modes=fixed_rank_modes, + **tensor_kwargs, + dtype=torch.cfloat, + ) + self.weight.normal_(0, init_std) + + self._contract = get_contract_fun( + self.weight, implementation=implementation, separable=separable + ) + + if bias: + self.bias = nn.Parameter( + init_std * torch.randn(*(tuple([self.out_channels]) + (1,) * self.order)) + ) + else: + self.bias = None + + def transform(self, x, output_shape=None): + in_shape = list(x.shape[2:]) + + if self.resolution_scaling_factor is not None and output_shape is None: + out_shape = tuple( + [round(s * r) for (s, r) in zip(in_shape, self.resolution_scaling_factor)] + ) + elif output_shape is not None: + out_shape = output_shape + else: + out_shape = in_shape + + if in_shape == out_shape: + return x + else: + return resample(x, 1.0, list(range(2, x.ndim)), output_shape=out_shape) + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + if isinstance(n_modes, int): # Should happen for 1D FNO only + n_modes = [n_modes] + else: + n_modes = list(n_modes) + # the real FFT is skew-symmetric, so the last mode has a redundacy if our data is real in space + # As a design choice we do the operation here to avoid users dealing with the +1 + # if we use the full FFT we cannot cut off informtion from the last mode + if not self.complex_data: + n_modes[-1] = n_modes[-1] // 2 + 1 + self._n_modes = n_modes + + def forward(self, x: torch.Tensor, output_shape: Optional[Tuple[int]] = None): + """Generic forward pass for the Factorized Spectral Conv + + Parameters + ---------- + x : torch.Tensor + input activation of size (batch_size, channels, d1, ..., dN) + + Returns + ------- + tensorized_spectral_conv(x) + """ + batchsize, channels, *mode_sizes = x.shape + + fft_size = list(mode_sizes) + if not self.complex_data: + fft_size[-1] = fft_size[-1] // 2 + 1 # Redundant last coefficient in real spatial data + fft_dims = list(range(-self.order, 0)) + + if self.fno_block_precision == "half": + x = x.half() + + if self.complex_data: + x = torch.fft.fftn(x, norm=self.fft_norm, dim=fft_dims) + dims_to_fft_shift = fft_dims + else: + x = torch.fft.rfftn(x, norm=self.fft_norm, dim=fft_dims) + # When x is real in spatial domain, the last half of the last dim is redundant. + # See :ref:`fft_shift_explanation` for discussion of the FFT shift. + dims_to_fft_shift = fft_dims[:-1] + + if self.order > 1: + x = torch.fft.fftshift(x, dim=dims_to_fft_shift) + + if self.fno_block_precision == "mixed": + # if 'mixed', the above fft runs in full precision, but the + # following operations run at half precision + x = x.chalf() + + if self.fno_block_precision in ["half", "mixed"]: + out_dtype = torch.chalf + else: + out_dtype = torch.cfloat + out_fft = torch.zeros( + [batchsize, self.out_channels, *fft_size], device=x.device, dtype=out_dtype + ) + + # if current modes are less than max, start indexing modes closer to the center of the weight tensor + starts = [ + (max_modes - min(size, n_mode)) + for (size, n_mode, max_modes) in zip(fft_size, self.n_modes, self.max_n_modes) + ] + # if contraction is separable, weights have shape (channels, modes_x, ...) + # otherwise they have shape (in_channels, out_channels, modes_x, ...) + if self.separable: + slices_w = [slice(None)] # channels + else: + slices_w = [slice(None), slice(None)] # in_channels, out_channels + if self.complex_data: + slices_w += [ + slice(start // 2, -start // 2) if start else slice(start, None) + for start in starts + ] + else: + # The last mode already has redundant half removed in real FFT + slices_w += [ + slice(start // 2, -start // 2) if start else slice(start, None) + for start in starts[:-1] + ] + slices_w += [slice(None, -starts[-1]) if starts[-1] else slice(None)] + + slices_w = tuple(slices_w) + weight = self.weight[slices_w] + + ### Pick the first n_modes modes of FFT signal along each dim + + # if separable conv, weight tensor only has one channel dim + if self.separable: + weight_start_idx = 1 + # otherwise drop first two dims (in_channels, out_channels) + else: + weight_start_idx = 2 + + slices_x = [slice(None), slice(None)] # Batch_size, channels + + for all_modes, kept_modes in zip(fft_size, list(weight.shape[weight_start_idx:])): + # After fft-shift, the 0th frequency is located at n // 2 in each direction + # We select n_modes modes around the 0th frequency (kept at index n//2) by grabbing indices + # n//2 - n_modes//2 to n//2 + n_modes//2 if n_modes is even + # n//2 - n_modes//2 to n//2 + n_modes//2 + 1 if n_modes is odd + center = all_modes // 2 + negative_freqs = kept_modes // 2 + positive_freqs = kept_modes // 2 + kept_modes % 2 + + # this slice represents the desired indices along each dim + slices_x += [slice(center - negative_freqs, center + positive_freqs)] + + if weight.shape[-1] < fft_size[-1]: + slices_x[-1] = slice(None, weight.shape[-1]) + else: + slices_x[-1] = slice(None) + + slices_x = tuple(slices_x) + out_fft[slices_x] = self._contract( + x[slices_x], weight, separable=self.separable + ) + + if self.resolution_scaling_factor is not None and output_shape is None: + mode_sizes = tuple([round(s * r) for (s, r) in zip(mode_sizes, self.resolution_scaling_factor)]) + + if output_shape is not None: + mode_sizes = output_shape + + + if self.order > 1: + out_fft = torch.fft.ifftshift(out_fft, dim=fft_dims[:-1]) + + + # Inverse FFT + if self.complex_data: + # For complex data, we can use ifftn. + x = torch.fft.ifftn(out_fft, s=mode_sizes, dim=fft_dims, norm=self.fft_norm) + + else: + # For real data, we need to enforce Hermitian symmetry conditions for irfft. + # On certain GPUs and for certain input sizes, this is not handled within irfftn in cuFFT, + # and as a result causes line artifacts. + # To fix this, we split the ifftn into a ifftn in (n-1) dimensions and a irfft in the last dimension, + # although it incurs a small additional computational cost. + + if self.enforce_hermitian_symmetry: + out_fft = torch.fft.ifftn(out_fft, s=mode_sizes[:-1], dim=fft_dims[:-1], norm=self.fft_norm) + + # Enforce Hermitian symmetry conditions for irfft + # 0th frequency must be real + out_fft[..., 0].imag.zero_() + + # Nyquist frequency must be real if the spatial size is even + if mode_sizes[-1] % 2 == 0: + out_fft[..., -1].imag.zero_() + + # Now that the Hermitian symmetry conditions are enforced, we can use irfft on the last dimension. + x = torch.fft.irfft(out_fft, n=mode_sizes[-1], dim=fft_dims[-1], norm=self.fft_norm) + + else: + + # If Hemrmitian symmetry is not a concern, we can use irfftn on all dimensions. + x = torch.fft.irfftn(out_fft, s=mode_sizes, dim=fft_dims, norm=self.fft_norm) + + + if self.bias is not None: + x = x + self.bias + + return x \ No newline at end of file diff --git a/sources/neuraloperator/neuralop/layers/spectral_projection.py b/sources/neuraloperator/neuralop/layers/spectral_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..caa3fe8971e5829d6cce916752f1efb684d2e177 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/spectral_projection.py @@ -0,0 +1,102 @@ +import torch +import numpy as np +import torch.nn.functional as F + + +def spectral_projection_divergence_free(u, domain_size, constraint_modes): + """Apply spectral projection layer to make a velocity field divergence-free. + + Parameters + ---------- + u : torch.Tensor + Input velocity field [batch, 2, height, width] where the last two + dimensions represent the 2D velocity components (u_x, u_y) + domain_size : float or tuple of float + Physical domain size. If float, assumes square domain with same size for height and width. + If tuple, should be (height_size, width_size) for non-square domains. + constraint_modes : tuple + Number of modes to use for constraint resolution (height_modes, width_modes). + If larger than input dimensions, they are truncated to the input dimensions. + + Returns + ------- + torch.Tensor + Divergence-free projected velocity field with [batch, 2, height, width] shape. + The output maintains the same shape as the input while satisfying ∇·u = 0. + + Notes + ----- + **Mathematical formulation:** Helmholtz-Hodge projection in spectral domain: + û_proj = û - (k·û)/|k|² * k. Enforces ∇·u = 0 by removing the irrotational component. + **Periodicity:** Velocity fields are assumed periodic. For non-periodic fields, extend + via Fourier continuation (neuralop.layers.fourier_continuation), project, then truncate. + + References + ---------- + The method is based on the spectral projection approach described in: + + [1] Towards Enforcing Hard Physics Constraints in Operator Learning Frameworks + V. Duruisseaux, M. Liu-Schiaffini, J. Berner, and A. Anandkumar + ICML 2024 AI for Science Workshop + https://openreview.net/pdf?id=Zvxm14Rd1F + + [2] Enforcing physical constraints in CNNs through differentiable PDE layer. + C. M. Jiang, K. Kashinath, P. Prabhat, and P. Marcus + ICLR 2020 Workshop on Integration of Deep Neural Models and Differential Equations, 2020. + https://openreview.net/pdf?id=q2noHUqMkK + + + """ + + device = u.device + dtype = u.dtype + batch_size, channels, height, width = u.shape + + # Get domain size + if isinstance(domain_size, (int, float)): + # Square domain: use same size for both dimensions + domain_height = domain_width = float(domain_size) + elif isinstance(domain_size, (tuple, list)) and len(domain_size) == 2: + # Non-square domain: separate sizes for height and width + domain_height, domain_width = float(domain_size[0]), float(domain_size[1]) + + # Ensure constraint modes do not exceed input dimensions + constraint_modes = (min(constraint_modes[0], height), min(constraint_modes[1], width)) + + # 2D FFT over height and width + u_ft = torch.fft.fftn(u, dim=(2, 3)) + + # Extract lower modes for both dimensions where the constraint is applied + if (height != constraint_modes[0]) or (width != constraint_modes[1]): + u_ft = torch.fft.fftshift(u_ft, dim=(2, 3)) + u_ft = u_ft[:, :, + (height - constraint_modes[0])//2 : (height - constraint_modes[0])//2 + constraint_modes[0], + (width - constraint_modes[1])//2 : (width - constraint_modes[1])//2 + constraint_modes[1]] + u_ft = torch.fft.ifftshift(u_ft, dim=(2, 3)) + + # Set up wavenumber grids for spectral operations + ky = 2*np.pi * torch.fft.fftfreq(constraint_modes[0], d=domain_height/constraint_modes[0]).to(dtype).to(device) + kx = 2*np.pi * torch.fft.fftfreq(constraint_modes[1], d=domain_width/constraint_modes[1]).to(dtype).to(device) + KX, KY = torch.meshgrid(kx, ky, indexing='ij' if constraint_modes[0] == constraint_modes[1] else 'xy') + + + # Apply Helmholtz-Hodge projection: û_proj = û - (k·û)/|k|² * k + k_dot_u = KX * u_ft[:, 0, :, :] + KY * u_ft[:, 1, :, :] + k_squared = KX**2 + KY**2 + 1e-8 # Add small epsilon to avoid division by zero + + projected_u_ft = u_ft - (k_dot_u / k_squared).unsqueeze(1) * torch.stack([KX, KY], dim=0).unsqueeze(0) + + # Handle zero mode explicitly + projected_u_ft[:, :, 0, 0] = 0.0 + + + # Pad zeros back to full resolution if needed + if height != constraint_modes[0] or width != constraint_modes[1]: + projected_u_ft = torch.fft.fftshift(projected_u_ft) + pad_h = height - constraint_modes[0] + pad_w = width - constraint_modes[1] + projected_u_ft = F.pad(projected_u_ft, [pad_w//2, pad_w - pad_w//2, pad_h//2, pad_h - pad_h//2]) + projected_u_ft = torch.fft.ifftshift(projected_u_ft) + + # Transform back to physical space + return torch.fft.ifftn(projected_u_ft, dim=(2, 3)).real diff --git a/sources/neuraloperator/neuralop/layers/spherical_convolution.py b/sources/neuraloperator/neuralop/layers/spherical_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..35c860de3034d10bb9a12fe28727176576cc078a --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/spherical_convolution.py @@ -0,0 +1,484 @@ +from typing import List, Optional, Union + +import torch +from torch import nn +from torch_harmonics import RealSHT, InverseRealSHT + +import tensorly as tl +from tensorly.plugins import use_opt_einsum +from tltorch.factorized_tensors.core import FactorizedTensor + +from neuralop.utils import validate_scaling_factor +from .base_spectral_conv import BaseSpectralConv + +tl.set_backend("pytorch") +use_opt_einsum("optimal") + +einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + + +def _contract_dense(x, weight, separable=False, dhconv=True): + order = tl.ndim(x) + # batch-size, in_channels, x, y... + x_syms = list(einsum_symbols[:order]) + + # in_channels, out_channels, x, y... + weight_syms = list(x_syms[1:]) # no batch-size + + # batch-size, out_channels, x, y... + if separable: + out_syms = [x_syms[0]] + list(weight_syms) + else: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + if dhconv: + weight_syms.pop() + + eq = "".join(x_syms) + "," + "".join(weight_syms) + "->" + "".join(out_syms) + + if not torch.is_tensor(weight): + weight = weight.to_tensor() + + return tl.einsum(eq, x, weight) + + +def _contract_dense_separable(x, weight, separable=True, dhconv=False): + if not separable: + raise ValueError("This function is only for separable=True") + if dhconv: + return x * weight.unsqueeze(-1) + return x * weight + + +def _contract_cp(x, cp_weight, separable=False, dhconv=True): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + rank_sym = einsum_symbols[order] + out_sym = einsum_symbols[order + 1] + out_syms = list(x_syms) + + if separable: + factor_syms = [einsum_symbols[1] + rank_sym] # in only + else: + out_syms[1] = out_sym + factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out + + if dhconv: + factor_syms += [xs + rank_sym for xs in x_syms[2:-1]] # x, y, ... + else: + factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ... + + eq = ( + x_syms + "," + rank_sym + "," + ",".join(factor_syms) + "->" + "".join(out_syms) + ) + + return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors) + + +def _contract_tucker(x, tucker_weight, separable=False, dhconv=False): + order = tl.ndim(x) + + x_syms = str(einsum_symbols[:order]) + out_sym = einsum_symbols[order] + out_syms = list(x_syms) + if separable: + core_syms = einsum_symbols[order + 1 : 2 * order] + # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only + factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)] # x, y, ... + + elif dhconv: + core_syms = einsum_symbols[order + 1 : 2 * order] + out_syms[1] = out_sym + factor_syms = [ + einsum_symbols[1] + core_syms[0], + out_sym + core_syms[1], + ] # out, in + factor_syms += [ + xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:]) + ] # x, y, ... + else: + core_syms = einsum_symbols[order + 1 : 2 * order + 1] + out_syms[1] = out_sym + factor_syms = [ + einsum_symbols[1] + core_syms[0], + out_sym + core_syms[1], + ] # out, in + factor_syms += [ + xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:]) + ] # x, y, ... + + eq = ( + x_syms + + "," + + core_syms + + "," + + ",".join(factor_syms) + + "->" + + "".join(out_syms) + ) + + return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors) + + +def _contract_tt(x, tt_weight, separable=False, dhconv=False): + order = tl.ndim(x) + + x_syms = list(einsum_symbols[:order]) + weight_syms = list(x_syms[1:]) # no batch-size + if not separable: + weight_syms.insert(1, einsum_symbols[order]) # outputs + out_syms = list(weight_syms) + out_syms[0] = x_syms[0] + else: + out_syms = list(x_syms) + + if dhconv: + weight_syms = weight_syms[:-1] # no batch-size, no y dim + + rank_syms = list(einsum_symbols[order + 1 :]) + tt_syms = [] + for i, s in enumerate(weight_syms): + tt_syms.append([rank_syms[i], s, rank_syms[i + 1]]) + eq = ( + "".join(x_syms) + + "," + + ",".join("".join(f) for f in tt_syms) + + "->" + + "".join(out_syms) + ) + + return tl.einsum(eq, x, *tt_weight.factors) + + +def get_contract_fun(weight, implementation="reconstructed", separable=False): + """Generic ND implementation of Fourier Spectral Conv contraction + + Parameters + ---------- + weight : tensorly-torch's FactorizedTensor + implementation : {'reconstructed', 'factorized'}, default is 'reconstructed' + whether to reconstruct the weight and do a forward pass (reconstructed) + or contract directly the factors of the factorized weight with the input + (factorized) + separable : bool + whether to use the separable implementation of contraction. This arg is + only checked when `implementation=reconstructed`. + + Returns + ------- + function : (x, weight) -> x * weight in Fourier space + """ + if implementation == "reconstructed": + if separable: + return _contract_dense_separable + else: + return _contract_dense + elif implementation == "factorized": + if torch.is_tensor(weight): + return _contract_dense + elif isinstance(weight, FactorizedTensor): + if weight.name.lower().endswith("dense"): + return _contract_dense + elif weight.name.lower().endswith("tucker"): + return _contract_tucker + elif weight.name.lower().endswith("tt"): + return _contract_tt + elif weight.name.lower().endswith("cp"): + return _contract_cp + else: + raise ValueError(f"Got unexpected factorized weight type {weight.name}") + else: + raise ValueError( + f"Got unexpected weight type of class {weight.__class__.__name__}" + ) + else: + raise ValueError( + f'Got implementation={implementation}, expected "reconstructed" or ' + f'"factorized"' + ) + + +Number = Union[int, float] + + +class SHT(nn.Module): + """A wrapper for the Spherical Harmonics transform. + + Allows to call it with an interface similar to that of FFT + """ + + def __init__(self, dtype=torch.float32, device=None): + super().__init__() + self.device = device + self.dtype = dtype + self._SHT_cache = nn.ModuleDict() + self._iSHT_cache = nn.ModuleDict() + + def sht(self, x, s=None, norm="ortho", grid="equiangular"): + *_, height, width = x.shape # height = latitude, width = longitude + if s is None: + if grid == "equiangular": + modes_width = height // 2 + else: + modes_width = height + modes_height = height + else: + modes_height, modes_width = s + + cache_key = f"{height}_{width}_{modes_height}_{modes_width}_{norm}_{grid}" + + try: + sht = self._SHT_cache[cache_key] + except KeyError: + sht = ( + RealSHT( + nlat=height, + nlon=width, + lmax=modes_height, + mmax=modes_width, + grid=grid, + norm=norm, + ) + .to(device=x.device) + .to(dtype=self.dtype) + ) + self._SHT_cache[cache_key] = sht + + return sht(x) + + def isht(self, x, s=None, norm="ortho", grid="equiangular"): + *_, modes_height, modes_width = x.shape # height = latitude, width = longitude + if s is None: + if grid == "equiangular": + width = modes_width * 2 + else: + width = modes_width + height = modes_height + else: + height, width = s + + cache_key = f"{height}_{width}_{modes_height}_{modes_width}_{norm}_{grid}" + + try: + isht = self._iSHT_cache[cache_key] + except KeyError: + isht = ( + InverseRealSHT( + nlat=height, + nlon=width, + lmax=modes_height, + mmax=modes_width, + grid=grid, + norm=norm, + ) + .to(device=x.device) + .to(dtype=self.dtype) + ) + self._iSHT_cache[cache_key] = isht + + return isht(x) + + +class SphericalConv(BaseSpectralConv): + """Spherical Convolution for the SFNO. + + It is implemented as described in [1]_. + + Parameters + ---------- + sht_norm : str, {'ortho'} + sht_grids : str or str list, default is "equiangular", {"equiangular", "legendre-gauss"} + * If str, the same grid is used for all layers + * If list, should have n_layers + 1 values, corresponding to the input and output grid of each layer + e.g. for 1 layer, ["input_grid", "output_grid"] + + See SpectralConv for full list of other parameters + + References + ---------- + .. [1] Spherical Fourier Neural Operators: Learning Stable Dynamics on the Sphere, + Boris Bonev, Thorsten Kurth, Christian Hundt, Jaideep Pathak, Maximilian Baust, Karthik Kashinath, Anima Anandkumar, + ICML 2023. + """ + + def __init__( + self, + in_channels, + out_channels, + n_modes, + max_n_modes=None, + bias=True, + separable=False, + resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None, + fno_block_precision="full", + rank=0.5, + factorization="cp", + implementation="reconstructed", + fixed_rank_modes=False, + joint_factorization=False, + decomposition_kwargs=dict(), + init_std="auto", + sht_norm="ortho", + sht_grids="equiangular", + device=None, + dtype=torch.float32, + complex_data=False, # dummy param until we unify dtype interface + ): + super().__init__(dtype=dtype, device=device) + + self.in_channels = in_channels + self.out_channels = out_channels + self.joint_factorization = joint_factorization + + if isinstance(n_modes, int): + n_modes = [n_modes] + self._n_modes = n_modes + self.order = len(n_modes) + + if max_n_modes is None: + max_n_modes = self.n_modes + elif isinstance(max_n_modes, int): + max_n_modes = [max_n_modes] + self.max_n_modes = max_n_modes + + self.rank = rank + self.factorization = factorization + self.implementation = implementation + + self.resolution_scaling_factor: Union[ + None, List[List[float]] + ] = validate_scaling_factor(resolution_scaling_factor, self.order) + + if init_std == "auto": + init_std = (2 / (in_channels + out_channels)) ** 0.5 + + if isinstance(fixed_rank_modes, bool): + if fixed_rank_modes: + # If bool, keep the number of layers fixed + fixed_rank_modes = [0] + else: + fixed_rank_modes = None + + # Make sure we are using a Complex Factorized Tensor to parametrize the conv + if factorization is None: + factorization = "Dense" # No factorization + if not factorization.lower().startswith("complex"): + factorization = f"Complex{factorization}" + + if separable: + if in_channels != out_channels: + raise ValueError( + "To use separable Fourier Conv, in_channels must be equal " + f"to out_channels, but got in_channels={in_channels} " + f"and out_channels={out_channels}", + ) + weight_shape = (in_channels, *self.n_modes[:-1]) + else: + weight_shape = (in_channels, out_channels, *self.n_modes[:-1]) + self.separable = separable + self.weight = FactorizedTensor.new( + weight_shape, + rank=self.rank, + factorization=factorization, + fixed_rank_modes=fixed_rank_modes, + **decomposition_kwargs, + ) + self.weight.normal_(0, init_std) + + self._contract = get_contract_fun( + self.weight, implementation=implementation, separable=separable + ) + + if bias: + self.bias = nn.Parameter( + init_std + * torch.randn(*(tuple([self.out_channels]) + (1,) * self.order)) + ) + else: + self.bias = None + + self.sht_norm = sht_norm + if isinstance(sht_grids, str): + sht_grids = [sht_grids] * 2 + self.sht_grids = sht_grids + self.sht_handle = SHT(dtype=self.dtype, device=self.device) + + def transform(self, x, output_shape=None): + *_, in_height, in_width = x.shape + + if self.resolution_scaling_factor is not None and output_shape is None: + height = round(in_height * self.resolution_scaling_factor[0]) + width = round(in_width * self.resolution_scaling_factor[1]) + elif output_shape is not None: + height, width = output_shape[0], output_shape[1] + else: + height, width = in_height, in_width + + # Return the identity if the resolution and grid of the input and output are the same + if ((in_height, in_width) == (height, width)) and (self.sht_grids[0] == self.sht_grids[1]): + return x + else: + coefs = self.sht_handle.sht( + x, s=self.n_modes, norm=self.sht_norm, grid=self.sht_grids[0] + ) + return self.sht_handle.isht( + coefs, s=(height, width), norm=self.sht_norm, grid=self.sht_grids[1] + ) + + def forward(self, x, output_shape=None): + """Generic forward pass for the Factorized Spectral Conv + + Parameters + ---------- + x : torch.Tensor + input activation of size (batch_size, channels, d1, ..., dN) + + Returns + ------- + tensorized_spectral_conv(x) + """ + batchsize, channels, height, width = x.shape + + if self.resolution_scaling_factor is not None and output_shape is None: + scaling_factors = self.resolution_scaling_factor + height = round(height * scaling_factors[0]) + width = round(width * scaling_factors[1]) + elif output_shape is not None: + height, width = output_shape[0], output_shape[1] + + out_fft = self.sht_handle.sht( + x, + s=(self.n_modes[0], self.n_modes[1] // 2), + norm=self.sht_norm, + grid=self.sht_grids[0], + ) + + out_fft = self._contract( + out_fft[:, :, : self.n_modes[0], : self.n_modes[1] // 2], + self.weight[:, :, : self.n_modes[0]], + separable=self.separable, + dhconv=True, + ) + + x = self.sht_handle.isht( + out_fft, s=(height, width), norm=self.sht_norm, grid=self.sht_grids[1] + ) + + if self.bias is not None: + x = x + self.bias + + return x + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + if isinstance(n_modes, int): # Should happen for 1D FNO only + n_modes = [n_modes] + else: + n_modes = list(n_modes) + self._n_modes = n_modes diff --git a/sources/neuraloperator/neuralop/layers/tests/__init__.py b/sources/neuraloperator/neuralop/layers/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/layers/tests/test_attention_layer.py b/sources/neuraloperator/neuralop/layers/tests/test_attention_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..b3673f1d67a887f729a9e058efc2b2344a360330 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_attention_layer.py @@ -0,0 +1,32 @@ +import pytest +import torch +from ..attention_kernel_integral import AttentionKernelIntegral +from ..embeddings import RotaryEmbedding2D + + +def test_AttentionWithRoPE(): + """Test for Attention kernel integral with rotary position embeddings + + Checks the output size + """ + head_n_channels = 32 + channels = 32 + num_heads = 4 + n_dim = 2 + num_points = 64 + batch_size = 4 + + attn_layer = AttentionKernelIntegral(channels, channels, num_heads, head_n_channels) + pos_emb_module = RotaryEmbedding2D(head_n_channels // n_dim) + + x = torch.randn(batch_size, num_points, channels) + pos = torch.randn(batch_size, num_points, n_dim) + + freqs_0 = pos_emb_module(pos[..., 0]) + assert freqs_0.shape == (batch_size, num_points, head_n_channels // n_dim) + + freqs_1 = pos_emb_module(pos[..., 1]) + assert freqs_1.shape == (batch_size, num_points, head_n_channels // n_dim) + + res = attn_layer(x, pos, positional_embedding_module=pos_emb_module) + assert res.shape == (batch_size, num_points, channels) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_coda_layer.py b/sources/neuraloperator/neuralop/layers/tests/test_coda_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5864c1eec958cfb7a410e8f564734cedd99600 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_coda_layer.py @@ -0,0 +1,57 @@ +import pytest +import torch +from ..coda_layer import * +from ..spectral_convolution import * + +device = "cuda" if torch.backends.cuda.is_built() else "cpu" +# device = 'cpu' + + +@pytest.mark.parametrize("token_codimension", [1, 2, 5]) +@pytest.mark.parametrize("n_dim", [2, 3]) +@pytest.mark.parametrize("norm", ["instance_norm", None]) +@pytest.mark.parametrize("nonlinear_attention", ["True", "False"]) +@pytest.mark.parametrize("per_channel_attention", ["False", "True"]) +@pytest.mark.parametrize("output_scale", [1, 2]) +def test_Codano( + token_codimension, + n_dim, + norm, + nonlinear_attention, + per_channel_attention, + output_scale, +): + """ + Test CoDA-NO layers + """ + n_modes = [64] * n_dim + n_heads = 3 + head_codimension = 3 + codimension_size = None + permutation_eq = True + temperature = 1.0 + + layer = CODALayer( + n_modes=n_modes, + n_heads=n_heads, + token_codimension=token_codimension, + head_codimension=head_codimension, + norm=norm, + codimension_size=codimension_size, + per_channel_attention=per_channel_attention, + permutation_eq=permutation_eq, + temperature=temperature, + nonlinear_attention=nonlinear_attention, + ).to(device) + + spatial_res = [64] * n_dim + x = torch.randn(2, 10, *spatial_res).to(device) + output_shape = [int(s * output_scale) for s in spatial_res] + out = layer(x, output_shape) + assert list(out.shape[-n_dim:]) == output_shape + + # test different spatial resolution + spatial_res = [48] * n_dim + x = torch.randn(2, 10, *spatial_res).to(device) + out = layer(x) + assert out.shape == x.shape diff --git a/sources/neuraloperator/neuralop/layers/tests/test_disco_conv.py b/sources/neuraloperator/neuralop/layers/tests/test_disco_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..06b84986772015f854ec9d8c65ce4423a866e58d --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_disco_conv.py @@ -0,0 +1,98 @@ +import pytest +import torch + +# Skip tests if torch_harmonics is not installed +try: + import torch_harmonics +except ModuleNotFoundError: + pytest.skip( + "Skipping because torch_harmonics is not installed", allow_module_level=True + ) + +from ..discrete_continuous_convolution import ( + DiscreteContinuousConv2d, + DiscreteContinuousConvTranspose2d, + EquidistantDiscreteContinuousConv2d, + EquidistantDiscreteContinuousConvTranspose2d, +) + +from ..embeddings import regular_grid_2d + +# global params +batch_size = 4 +in_channels = 6 +out_channels = 3 +side_length_in = 64 +side_length_out = 48 + +device = "cuda" if torch.backends.cuda.is_built() else "cpu" + + +@pytest.mark.parametrize( + "conv_type", [DiscreteContinuousConv2d, DiscreteContinuousConvTranspose2d] +) +@pytest.mark.parametrize("groups", [1, 3]) +@pytest.mark.parametrize("basis_type", ["piecewise_linear", "morlet", "zernike"]) +def test_regular_disco_conv2d(conv_type, groups, basis_type): + # create regular grids of in and output coords + grid_in = torch.stack( + regular_grid_2d(spatial_dims=[side_length_in, side_length_in]) + ) + grid_out = torch.stack( + regular_grid_2d(spatial_dims=[side_length_out, side_length_out]) + ) + + # reshape grids to point clouds (channels, n_pts) + grid_in = grid_in.view(2, -1) + grid_out = grid_out.view(2, -1) + + # quad weights: one weight per point + quadrature_weights = torch.randn(grid_in.shape[1]) + + conv_layer = conv_type( + in_channels=in_channels, + out_channels=out_channels, + basis_type=basis_type, + grid_in=grid_in, + grid_out=grid_out, + kernel_shape=3, + quadrature_weights=quadrature_weights, + groups=groups, + ) + + # start with a grid, pass to forward as a point cloud + x = torch.randn(batch_size, in_channels, side_length_in, side_length_in) + x = x.reshape(batch_size, in_channels, -1) + + res = conv_layer(x) + assert res.shape == (batch_size, out_channels, side_length_out**2) + + +@pytest.mark.parametrize( + "conv_type", + [EquidistantDiscreteContinuousConv2d, EquidistantDiscreteContinuousConvTranspose2d], +) +@pytest.mark.parametrize("groups", [1, 3]) +@pytest.mark.parametrize("basis_type", ["piecewise_linear", "morlet", "zernike"]) +def test_equidistant_disco_conv2d(conv_type, groups, basis_type): + in_shape = (side_length_in, side_length_in) + if conv_type == EquidistantDiscreteContinuousConv2d: + out_shape = (side_length_in // 2, side_length_in // 2) + else: + out_shape = (side_length_in * 2, side_length_in * 2) + + conv_layer = conv_type( + in_channels=in_channels, + out_channels=out_channels, + in_shape=in_shape, + out_shape=out_shape, + basis_type=basis_type, + kernel_shape=3, + groups=groups, + ) + + # start with a grid, pass to forward as a grid + x = torch.randn(batch_size, in_channels, *in_shape) + + res = conv_layer(x) + assert res.shape == (batch_size, out_channels, *out_shape) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_finite_difference_conv.py b/sources/neuraloperator/neuralop/layers/tests/test_finite_difference_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..74aec1cae08d6fba74bd5eb652cf22773237adf8 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_finite_difference_conv.py @@ -0,0 +1,67 @@ +####### ####### ####### +# This script discretizes a parabola on a 2d grid and check to see that +# the output converges to the theoretical limit. +####### ####### ####### + +import pytest +import numpy as np +import torch +import math + +from ..differential_conv import FiniteDifferenceConvolution + + +def get_grid(S, batchsize, device): + gridx = torch.tensor(np.linspace(0, 1, S), dtype=torch.float) + gridx = gridx.reshape(1, 1, S, 1).repeat([batchsize, 1, 1, S]) + gridy = torch.tensor(np.linspace(0, 1, S), dtype=torch.float) + gridy = gridy.reshape(1, 1, 1, S).repeat([batchsize, 1, S, 1]) + return torch.cat((gridx, gridy), dim=1).to(device) + + +@pytest.mark.parametrize("resolution", [500, 700, 1000]) +def test_convergence_FiniteDifferenceConvolution_subtract_middle(resolution): + torch.manual_seed(0) + device = torch.device("cpu") + + num_channels = 10 + kernel_size = 3 + coeff = torch.rand((num_channels,)) + + differential_block = FiniteDifferenceConvolution( + in_channels=num_channels, + out_channels=1, + n_dim=2, + kernel_size=kernel_size, + groups=1, # mixing derivatives + ).to(device) + + with torch.no_grad(): + weight = differential_block.conv.weight[0] # [0] because output channels is 1 + + diff_block_output_list = [] + grid_width = 1 / resolution + grid = get_grid(resolution, 1, device) + + channels = [ + torch.sum(coeff[i] * torch.square(grid), dim=1) for i in range(num_channels) + ] + parabola = torch.stack(channels, dim=1).to(device) + + diff_block_output = differential_block(parabola, grid_width) + diff_block_output_list.append(diff_block_output) + + theoretical_value = 0 + for k in range(num_channels): + direction_k = 0 + for i in range(kernel_size): + for j in range(kernel_size): + direction_k += weight[k, i, j] * torch.tensor( + [[[[i - kernel_size // 2, j - kernel_size // 2]]]] + ).to(device) + direction_k = direction_k.movedim(-1, 1).repeat([1, 1, resolution, resolution]) + theoretical_value += 2 * coeff[k] * torch.sum(grid * direction_k, dim=1) + + error = 1/(resolution-2) * torch.norm(diff_block_output.squeeze()[1:-1, 1:-1] - theoretical_value.squeeze()[1:-1, 1:-1]).item() + + assert math.isclose(0, error, abs_tol=0.1) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_fno_block.py b/sources/neuraloperator/neuralop/layers/tests/test_fno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..13fca79ded109f5b9a644c5b86fd8488ae25f2f2 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_fno_block.py @@ -0,0 +1,250 @@ +import pytest +import torch +from ..fno_block import FNOBlocks + + +def test_FNOBlock_resolution_scaling_factor(): + """Test FNOBlocks with upsampled or downsampled outputs""" + max_n_modes = [8, 8, 8, 8] + n_modes = [4, 4, 4, 4] + + size = [10] * 4 + channel_mlp_dropout = 0 + channel_mlp_expansion = 0.5 + channel_mlp_skip = "linear" + for dim in [1, 2, 3, 4]: + block = FNOBlocks( + 3, + 4, + max_n_modes[:dim], + max_n_modes=max_n_modes[:dim], + n_layers=1, + channel_mlp_skip=channel_mlp_skip, + ) + + assert block.convs[0].n_modes[:-1] == max_n_modes[: dim - 1] + assert block.convs[0].n_modes[-1] == max_n_modes[dim - 1] // 2 + 1 + + block.n_modes = n_modes[:dim] + assert block.convs[0].n_modes[:-1] == n_modes[: dim - 1] + assert block.convs[0].n_modes[-1] == n_modes[dim - 1] // 2 + 1 + + block.n_modes = max_n_modes[:dim] + assert block.convs[0].n_modes[:-1] == max_n_modes[: dim - 1] + assert block.convs[0].n_modes[-1] == max_n_modes[dim - 1] // 2 + 1 + + # Downsample outputs + block = FNOBlocks( + 3, + 4, + n_modes[:dim], + n_layers=1, + resolution_scaling_factor=0.5, + use_channel_mlp=True, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + x = torch.randn(2, 3, *size[:dim]) + res = block(x) + assert list(res.shape[2:]) == [m // 2 for m in size[:dim]] + + # Upsample outputs + block = FNOBlocks( + 3, + 4, + n_modes[:dim], + n_layers=1, + resolution_scaling_factor=2, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + x = torch.randn(2, 3, *size[:dim]) + res = block(x) + assert res.shape[1] == 4 # Check out channels + assert list(res.shape[2:]) == [m * 2 for m in size[:dim]] + + +@pytest.mark.parametrize("n_dim", [1, 2, 3, 4]) +@pytest.mark.parametrize( + "norm", ["instance_norm", "ada_in", "group_norm", "batch_norm"] +) +def test_FNOBlock_norm(norm, n_dim): + """Test SpectralConv with upsampled or downsampled outputs""" + modes = (8, 8, 8) + size = [10] * 3 + channel_mlp_dropout = 0 + channel_mlp_expansion = 0.5 + channel_mlp_skip = "linear" + ada_in_features = 4 + block = FNOBlocks( + 3, + 4, + modes[:n_dim], + n_layers=1, + norm=norm, + ada_in_features=ada_in_features, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + if norm == "ada_in": + embedding = torch.randn(ada_in_features) + block.set_ada_in_embeddings(embedding) + + x = torch.randn(2, 3, *size[:n_dim]) + res = block(x) + assert list(res.shape[2:]) == size[:n_dim] + + +@pytest.mark.parametrize("norm_groups", [1, 2, 4, 8]) +def test_FNOBlock_group_norm(norm_groups): + """Test FNOBlocks with group_norm and custom norm_groups""" + modes = (8, 8, 8) + hidden_channels = 16 + n_layers = 1 + + block = FNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=modes, + n_layers=n_layers, + norm="group_norm", + norm_groups=norm_groups, + ) + + # Check that GroupNorm layers are correctly initialized + assert block.norm is not None + for norm_layer in block.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + assert norm_layer.num_channels == hidden_channels + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +def test_FNOBlock_complex_data(n_dim): + """Test FNO layers with complex input data""" + modes = (8, 8, 8) + size = [10] * 3 + channel_mlp_dropout = 0 + channel_mlp_expansion = 0.5 + channel_mlp_skip = "linear" + # Instantiate a complex-valued FNO block + block = FNOBlocks( + 3, + 4, + modes[:n_dim], + n_layers=1, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + complex_data=True, + ) + + x = torch.randn(2, 3, *size[:n_dim], dtype=torch.cfloat) + res = block(x) + + assert list(res.shape[2:]) == size[:n_dim] + + +@pytest.mark.parametrize("fno_skip", ["linear", None]) +@pytest.mark.parametrize("channel_mlp_skip", ["linear", None]) +def test_FNOBlock_skip_connections(fno_skip, channel_mlp_skip): + """Test FNOBlocks with different skip connection options including None""" + modes = (8, 8, 8) + size = [10, 10, 10] + + # Skip test cases that are incompatible + # Soft-gating requires same input/output channels + if fno_skip == "soft-gating" or channel_mlp_skip == "soft-gating": + pytest.skip("Soft-gating requires same input/output channels") + + # Test with channel MLP enabled + block = FNOBlocks( + 3, + 4, + modes, + n_layers=2, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + use_channel_mlp=True, + channel_mlp_expansion=0.5, + channel_mlp_dropout=0.0, + ) + + x = torch.randn(2, 3, *size) + res = block(x) + + # Check output shape + assert res.shape == (2, 4, *size) + + # Test with channel MLP disabled + block_no_mlp = FNOBlocks( + 3, + 4, + modes, + n_layers=2, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + use_channel_mlp=False, + ) + + res_no_mlp = block_no_mlp(x) + assert res_no_mlp.shape == (2, 4, *size) + + +@pytest.mark.parametrize("fno_skip", ["linear", None]) +@pytest.mark.parametrize("channel_mlp_skip", ["linear", None]) +def test_FNOBlock_skip_connections_preactivation(fno_skip, channel_mlp_skip): + """Test FNOBlocks with preactivation and different skip connection options""" + modes = (8, 8, 8) + size = [10, 10, 10] + + # Test with preactivation enabled + block = FNOBlocks( + 3, + 4, + modes, + n_layers=2, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + use_channel_mlp=True, + channel_mlp_expansion=0.5, + channel_mlp_dropout=0.0, + preactivation=True, + ) + + x = torch.randn(2, 3, *size) + res = block(x) + + # Check output shape + assert res.shape == (2, 4, *size) + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +def test_FNOBlock_conv_bias_kernel(n_dim): + """Test local convolutional bias kernels beside spectral convolution.""" + modes = (8, 8, 8) + size = [10, 10, 10] + conv_bias_kernel = 3 + + block = FNOBlocks( + 3, + 4, + modes[:n_dim], + n_layers=2, + conv_bias_kernel=conv_bias_kernel, + fno_skip="linear", + use_channel_mlp=False, + ) + + x = torch.randn(2, 3, *size[:n_dim]) + res = block(x) + + assert res.shape == (2, 4, *size[:n_dim]) + assert block.conv_bias_kernel == conv_bias_kernel + assert block.fno_skips[0].kernel_size == (conv_bias_kernel,) * n_dim diff --git a/sources/neuraloperator/neuralop/layers/tests/test_fourier_continuation.py b/sources/neuraloperator/neuralop/layers/tests/test_fourier_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..3dbb6cd22f7083372221b2882c4f3d9d360ef4f8 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_fourier_continuation.py @@ -0,0 +1,135 @@ +import torch +import pytest +from ..fourier_continuation import FCLegendre, FCGram + + +@pytest.mark.parametrize("FC_class", [FCLegendre, FCGram]) +@pytest.mark.parametrize("dim", [1, 2, 3]) +@pytest.mark.parametrize("d", [3, 4]) +def test_fourier_continuation(FC_class, dim: int, d: int): + if dim == 1: + batch_size = 3 + length_signal = 101 + add_pts = 50 + + x = torch.linspace(0, 1, length_signal).repeat(batch_size, 1) + f = torch.sin(16 * x) - torch.cos(8 * x) + + Extension = FC_class(d=d, n_additional_pts=add_pts) + + f_extend = Extension(f, dim=1) + + # Check shape + assert f_extend.shape[-1] == f.shape[-1] + add_pts + # Check values of original signal + torch.testing.assert_close(f, f_extend[..., add_pts // 2 : -add_pts // 2]) + + if dim == 2: + batch_size = 3 + length_signal = 101 + add_pts = 50 + + x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1).repeat(batch_size, 1, length_signal) + y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal).repeat(batch_size, length_signal, 1) + f = torch.sin(12 * x) - torch.cos(14 * y) + 3*x*y + + Extension = FC_class(d=d, n_additional_pts=add_pts) + + f_extend = Extension(f, dim=2) + + # Check shape + assert f_extend.shape[-1] == f.shape[-1] + add_pts + assert f_extend.shape[-2] == f.shape[-2] + add_pts + # Check values of original signal + torch.testing.assert_close( + f, f_extend[..., add_pts // 2 : -add_pts // 2, add_pts // 2 : -add_pts // 2] + ) + + if dim == 3: + batch_size = 2 + length_signal = 81 + add_pts = 50 + + # Create 3D grid + x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1, 1).repeat(batch_size, 1, length_signal, length_signal) + y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal, 1).repeat(batch_size, length_signal, 1, length_signal) + z = torch.linspace(0, 1, length_signal).view(1, 1, 1, length_signal).repeat(batch_size, length_signal, length_signal, 1) + + # Create 3D function + f = torch.exp(-2*z) + 2*z*x + torch.sin(12*x*y) + y*torch.sin(10*y*z) + + Extension = FC_class(d=d, n_additional_pts=add_pts) + + f_extend = Extension(f, dim=3) + + # Check shape + assert f_extend.shape[-1] == f.shape[-1] + add_pts + assert f_extend.shape[-2] == f.shape[-2] + add_pts + assert f_extend.shape[-3] == f.shape[-3] + add_pts + # Check values of original signal + torch.testing.assert_close( + f, + f_extend[ + ..., + add_pts // 2 : -add_pts // 2, + add_pts // 2 : -add_pts // 2, + add_pts // 2 : -add_pts // 2, + ], + ) + + +@pytest.mark.parametrize("FC_class", [FCLegendre, FCGram]) +@pytest.mark.parametrize( + "dim_tuple", + [(1,), (2,), (1, 2), (1, 3), (2, 3), (-1,), (-2,), (-1, -2), (-1, -3), (1, -1)], +) +@pytest.mark.parametrize("d", [3, 4]) +def test_fourier_continuation_tuple_dims(FC_class, dim_tuple, d: int): + """ + Test Fourier continuation with tuple dimensions. + + Tests various combinations of positive and negative axis indices + to ensure the extension works correctly along specific axes. + """ + batch_size = 2 + add_pts = 30 + + # Create a 4D tensor for comprehensive testing + x = torch.randn(batch_size, 20, 25, 30) + + try: + Extension = FC_class(d=d, n_additional_pts=add_pts) + except FileNotFoundError as e: + if FC_class.__name__ == "FCGram": + pytest.skip(f"FCGram matrices not available: {e}") + else: + raise + + # Extend along specified dimensions + f_extend = Extension(x, dim=dim_tuple) + + # Calculate expected shape + expected_shape = list(x.shape) + for dim in dim_tuple: + # Convert negative indices to positive + if dim < 0: + dim = x.ndim + dim + expected_shape[dim] += add_pts + + # Check shape + assert f_extend.shape == tuple( + expected_shape + ), f"Expected shape {tuple(expected_shape)}, got {f_extend.shape}" + + # Test restrict functionality + f_restricted = Extension.restrict(f_extend, dim=dim_tuple) + + # Check that restrict returns original shape + assert ( + f_restricted.shape == x.shape + ), f"Restrict failed: expected {x.shape}, got {f_restricted.shape}" + + # Check that restrict returns original values + torch.testing.assert_close( + x, f_restricted, msg="Restrict did not return original values" + ) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_gno_block.py b/sources/neuraloperator/neuralop/layers/tests/test_gno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7107eab2a50989204664c7a5433950fe42aa4e --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_gno_block.py @@ -0,0 +1,110 @@ +import torch +from torch.autograd import grad +import pytest +from tensorly import tenalg + +tenalg.set_backend("einsum") + +# Parameterize use of torch_scatter if it is built +try: + from torch_scatter import segment_csr + + use_torch_scatter = [True, False] +except: + use_torch_scatter = [False] + +from ..gno_block import GNOBlock + +# Fixed variables +in_channels = 3 +out_channels = 3 +mlp_hidden_layers = [16, 16, 16] + +# data parameters +n_in = 100 +n_out = 100 + +# test open3d mode if built +try: + from neighbor_search import FixedRadiusSearch + + open3d_built = True +except: + open3d_built = False + +if open3d_built: + use_open3d_parametrize = [True, False] +else: + use_open3d_parametrize = [False] + + +@pytest.mark.parametrize("batch_size", [1, 4]) +@pytest.mark.parametrize("gno_coord_dim", [2, 3]) +@pytest.mark.parametrize("gno_pos_embed_type", ["nerf", "transformer", None]) +@pytest.mark.parametrize( + "gno_transform_type", ["linear", "nonlinear_kernelonly", "nonlinear"] +) +@pytest.mark.parametrize("use_open3d", use_open3d_parametrize) +@pytest.mark.parametrize("use_torch_scatter", use_torch_scatter) +def test_gno_block( + gno_transform_type, + gno_coord_dim, + gno_pos_embed_type, + batch_size, + use_open3d, + use_torch_scatter, +): + if torch.backends.cuda.is_built(): + device = torch.device("cuda:0") + else: + device = torch.device("cpu:0") + + use_open3d = use_open3d and (gno_coord_dim == 3) + + gno_block = GNOBlock( + in_channels=in_channels, + out_channels=out_channels, # dummy var currently + coord_dim=gno_coord_dim, + pos_embedding_type=gno_pos_embed_type, + radius=0.25, + channel_mlp_layers=mlp_hidden_layers, + transform_type=gno_transform_type, + use_open3d_neighbor_search=use_open3d, + use_torch_scatter_reduce=use_torch_scatter, + ).to(device) + + # create input geometry and output queries + input_geom_shape = [n_in, gno_coord_dim] + input_geom = torch.randn(*input_geom_shape, device=device) + + output_queries_shape = [n_out, gno_coord_dim] + output_queries = torch.randn(*output_queries_shape, device=device) + + f_y = None + if gno_transform_type != "linear": + # create data and features + f_y_shape = [batch_size, n_in, in_channels] + f_y = torch.randn(*f_y_shape, device=device) + # require and retain grad to check for backprop + f_y.requires_grad_(True) + + out = gno_block(y=input_geom, x=output_queries, f_y=f_y) + + # Check output size + # Batched outputs only matter in the nonlinear kernel use case + if gno_transform_type != "linear": + assert list(out.shape) == [batch_size, n_out, out_channels] + else: + assert list(out.shape) == [n_out, out_channels] + + # Check backward pass + assert out.isfinite().all() + if batch_size > 1: + loss = out[0].sum() + else: + loss = out.sum() + loss.backward() + + if batch_size > 1 and gno_transform_type != "linear": + # assert f_y[1:] accumulates no grad if it's used + assert not f_y.grad[1:].nonzero().any() diff --git a/sources/neuraloperator/neuralop/layers/tests/test_grid_embeddings.py b/sources/neuraloperator/neuralop/layers/tests/test_grid_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..5c12917a6af84a0101da1996dce1799dd6e3924a --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_grid_embeddings.py @@ -0,0 +1,42 @@ +import random + +import torch +from torch.testing import assert_close +import pytest + +from ..embeddings import GridEmbedding2D, GridEmbeddingND + +# Testing grid-based pos encoding: choose a random grid +# point and assert the proper encoding is applied there + + +def test_GridEmbedding2D(): + grid_boundaries = [[0, 1], [0, 1]] + pos_embed = GridEmbedding2D(in_channels=1, grid_boundaries=grid_boundaries) + + input_res = (20, 20) + x = torch.randn(1, 1, *input_res) + x = pos_embed(x) + + index = [random.randint(0, res-1) for res in input_res] + true_coords = x[0,1:,index[0], index[1]].squeeze() # grab pos encoding channels at coord index + expected_coords = torch.tensor([i/j for i,j in zip(index,input_res)]) + assert_close(true_coords, expected_coords) + + +@pytest.mark.parametrize("dim", [1, 2, 3, 4]) +def test_GridEmbeddingND(dim): + grid_boundaries = [[0, 1]] * dim + pos_embed = GridEmbeddingND(in_channels=1, dim=dim, grid_boundaries=grid_boundaries) + + input_res = [20] * dim + x = torch.randn(1, 1, *input_res) + x = pos_embed(x) + + index = [random.randint(0, res - 1) for res in input_res] + # grab pos encoding channels at coord index + pos_channels = x[0, 1:, ...] + indices = (slice(None), *index) + true_coords = pos_channels[indices] + expected_coords = torch.tensor([i / j for i, j in zip(index, input_res)]) + assert_close(true_coords, expected_coords) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_legacy_spectral_convolution.py b/sources/neuraloperator/neuralop/layers/tests/test_legacy_spectral_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..9e0ceed5d1b3a084c45bfce6d84c106e9c492544 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_legacy_spectral_convolution.py @@ -0,0 +1,228 @@ +import pytest +import torch +from tltorch import FactorizedTensor +from ..legacy_spectral_convolution import ( + SpectralConv3d, + SpectralConv2d, + SpectralConv1d, + SpectralConv, +) + + +@pytest.mark.parametrize( + "factorization", ["ComplexDense", "ComplexCP", "ComplexTucker", "ComplexTT"] +) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +def test_SpectralConv(factorization, implementation): + """Test for SpectralConv of any order + + Compares Factorized and Dense convolution output + Verifies that a dense conv and factorized conv with the same weight produce the same output + + Checks the output size + + Verifies that dynamically changing the number of Fourier modes doesn't break the conv + """ + modes = (10, 8, 6, 6) + incremental_modes = (6, 6, 4, 4) + + # Test for Conv1D to Conv4D + for dim in [1, 2, 3, 4]: + conv = SpectralConv( + 3, + 3, + modes[:dim], + n_layers=1, + bias=False, + implementation=implementation, + factorization=factorization, + ) + + conv_dense = SpectralConv( + 3, + 3, + modes[:dim], + n_layers=1, + bias=False, + implementation="reconstructed", + factorization=None, + ) + + for i in range(2 ** (dim - 1)): + conv_dense.weight[i] = FactorizedTensor.from_tensor( + conv.weight[i].to_tensor(), rank=None, factorization="ComplexDense" + ) + + x = torch.randn(2, 3, *(12,) * dim) + + res_dense = conv_dense(x) + res = conv(x) + res_shape = res.shape + + torch.testing.assert_close(res_dense, res) + + # Dynamically reduce the number of modes in Fourier space + conv.incremental_n_modes = incremental_modes[:dim] + res = conv(x) + assert res_shape == res.shape + + # Downsample outputs + block = SpectralConv(3, 4, modes[:dim], n_layers=1, resolution_scaling_factor=0.5) + + x = torch.randn(2, 3, *(12, )*dim) + res = block(x) + assert list(res.shape[2:]) == [12 // 2] * dim + + # Upsample outputs + block = SpectralConv(3, 4, modes[:dim], n_layers=1, resolution_scaling_factor=2) + + x = torch.randn(2, 3, *(12,) * dim) + res = block(x) + assert res.shape[1] == 4 # Check out channels + assert list(res.shape[2:]) == [12 * 2] * dim + + +def test_SpectralConv_resolution_scaling_factor(): + """Test SpectralConv with upsampled or downsampled outputs""" + modes = (4, 4, 4, 4) + size = [6] * 4 + for dim in [1, 2, 3, 4]: + # Downsample outputs + conv = SpectralConv( + 3, 3, modes[:dim], n_layers=1, resolution_scaling_factor=0.5 + ) + + x = torch.randn(2, 3, *size[:dim]) + res = conv(x) + assert list(res.shape[2:]) == [m // 2 for m in size[:dim]] + + # Upsample outputs + conv = SpectralConv(3, 3, modes[:dim], n_layers=1, resolution_scaling_factor=2) + + x = torch.randn(2, 3, *size[:dim]) + res = conv(x) + assert list(res.shape[2:]) == [m * 2 for m in size[:dim]] + + +@pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"]) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +def test_SpectralConv3D(factorization, implementation): + """Compare generic SpectralConv with hand written SpectralConv2D + + Verifies that a dense conv and factorized conv with the same weight produce the same output + Note that this implies the order in which the conv is done in the manual implementation matches the automatic one, + take with a grain of salt + """ + conv = SpectralConv( + 3, + 6, + (4, 5, 2), + n_layers=1, + bias=False, + implementation=implementation, + factorization=factorization, + ) + + conv_dense = SpectralConv3d( + 3, + 6, + (4, 5, 2), + n_layers=1, + bias=False, + implementation="reconstructed", + factorization=None, + ) + for i, w in enumerate(conv.weight): + rec = w.to_tensor() + dtype = rec.dtype + assert dtype == torch.cfloat + conv_dense.weight[i] = FactorizedTensor.from_tensor( + rec, rank=None, factorization="ComplexDense" + ) + + x = torch.randn(2, 3, 12, 12, 12) + res_dense = conv_dense(x) + res = conv(x) + torch.testing.assert_close(res_dense, res) + + +@pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"]) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +def test_SpectralConv2D(factorization, implementation): + """Compare generic SpectralConv with hand written SpectralConv2D + + Verifies that a dense conv and factorized conv with the same weight produce the same output + Note that this implies the order in which the conv is done in the manual implementation matches the automatic one, + take with a grain of salt + """ + conv = SpectralConv( + 10, + 11, + (4, 5), + n_layers=1, + bias=False, + implementation=implementation, + factorization=factorization, + ) + + conv_dense = SpectralConv2d( + 10, + 11, + (4, 5), + n_layers=1, + bias=False, + implementation="reconstructed", + factorization=None, + ) + for i, w in enumerate(conv.weight): + rec = w.to_tensor() + dtype = rec.dtype + assert dtype == torch.cfloat + conv_dense.weight[i] = FactorizedTensor.from_tensor( + rec, rank=None, factorization="ComplexDense" + ) + + x = torch.randn(2, 10, 12, 12) + res_dense = conv_dense(x) + res = conv(x) + torch.testing.assert_close(res_dense, res) + + +@pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"]) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +def test_SpectralConv1D(factorization, implementation): + """Test for SpectralConv1D + + Verifies that a dense conv and factorized conv with the same weight produce the same output + """ + conv = SpectralConv( + 10, + 11, + (5,), + n_layers=1, + bias=False, + implementation=implementation, + factorization=factorization, + ) + + conv_dense = SpectralConv1d( + 10, + 11, + (5,), + n_layers=1, + bias=False, + implementation="reconstructed", + factorization=None, + ) + for i, w in enumerate(conv.weight): + rec = w.to_tensor() + dtype = rec.dtype + assert dtype == torch.cfloat + conv_dense.weight[i] = FactorizedTensor.from_tensor( + rec, rank=None, factorization="ComplexDense" + ) + + x = torch.randn(2, 10, 12) + res_dense = conv_dense(x) + res = conv(x) + torch.testing.assert_close(res_dense, res) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_local_no_block.py b/sources/neuraloperator/neuralop/layers/tests/test_local_no_block.py new file mode 100644 index 0000000000000000000000000000000000000000..7075366633ff936f6fbd197aabbe7fda72c05553 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_local_no_block.py @@ -0,0 +1,194 @@ +import pytest +import torch + +try: + import torch_harmonics +except ModuleNotFoundError: + pytest.skip( + "Skipping because torch_harmonics is not installed", allow_module_level=True + ) + +from ..local_no_block import LocalNOBlocks + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +def test_LocalNOBlock_resolution_scaling_factor(n_dim): + """Test LocalNOBlocks with upsampled or downsampled outputs""" + max_n_modes = [8, 8, 8] + n_modes = [4, 4, 4] + + size = [10] * 3 + channel_mlp_dropout = 0 + channel_mlp_expansion = 0.5 + channel_mlp_skip = "linear" + block = LocalNOBlocks( + 3, + 4, + default_in_shape=tuple(size[:n_dim]), + n_modes=max_n_modes[:n_dim], + max_n_modes=max_n_modes[:n_dim], + n_layers=1, + diff_layers=[True], + disco_layers=[(n_dim == 2)], + ) + + assert block.convs[0].n_modes[:-1] == max_n_modes[: n_dim - 1] + assert block.convs[0].n_modes[-1] == max_n_modes[n_dim - 1] // 2 + 1 + + block.n_modes = n_modes[:n_dim] + assert block.convs[0].n_modes[:-1] == n_modes[: n_dim - 1] + assert block.convs[0].n_modes[-1] == n_modes[n_dim - 1] // 2 + 1 + + block.n_modes = max_n_modes[:n_dim] + assert block.convs[0].n_modes[:-1] == max_n_modes[: n_dim - 1] + assert block.convs[0].n_modes[-1] == max_n_modes[n_dim - 1] // 2 + 1 + + # Downsample outputs + block = LocalNOBlocks( + 3, + 4, + n_modes[:n_dim], + default_in_shape=tuple(size[:n_dim]), + n_layers=1, + diff_layers=[True], + disco_layers=[(n_dim == 2)], + resolution_scaling_factor=0.5, + use_channel_mlp=True, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + x = torch.randn(2, 3, *size[:n_dim]) + res = block(x) + assert list(res.shape[2:]) == [m // 2 for m in size[:n_dim]] + + # Upsample outputs + block = LocalNOBlocks( + 3, + 4, + n_modes[:n_dim], + default_in_shape=tuple(size[:n_dim]), + n_layers=1, + diff_layers=[True], + disco_layers=[(n_dim == 2)], + resolution_scaling_factor=2, + use_channel_mlp=True, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + x = torch.randn(2, 3, *size[:n_dim]) + res = block(x) + assert res.shape[1] == 4 # Check out channels + assert list(res.shape[2:]) == [m * 2 for m in size[:n_dim]] + + +@pytest.mark.parametrize("norm", ["instance_norm", "ada_in", "group_norm"]) +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +def test_LocalNOBlock_norm(norm, n_dim): + """Test LocalNOBlock with normalization""" + modes = (8, 8, 8) + size = [10] * 3 + channel_mlp_dropout = 0 + channel_mlp_expansion = 0.5 + channel_mlp_skip = "linear" + ada_in_features = 4 + block = LocalNOBlocks( + 3, + 4, + modes[:n_dim], + default_in_shape=tuple(size[:n_dim]), + n_layers=1, + diff_layers=[True], + disco_layers=[(n_dim == 2)], + use_channel_mlp=True, + norm=norm, + ada_in_features=ada_in_features, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_skip=channel_mlp_skip, + ) + + if norm == "ada_in": + embedding = torch.randn(ada_in_features) + block.set_ada_in_embeddings(embedding) + + x = torch.randn(2, 3, *size[:n_dim]) + res = block(x) + assert list(res.shape[2:]) == size[:n_dim] + + +@pytest.mark.parametrize("local_no_skip", ["linear", None]) +@pytest.mark.parametrize("channel_mlp_skip", ["linear", None]) +def test_LocalNOBlock_skip_connections(local_no_skip, channel_mlp_skip): + """Test LocalNOBlocks with different skip connection options including None""" + modes = (8, 8, 8) + size = [10, 10, 10] + + # Test with channel MLP enabled + block = LocalNOBlocks( + 3, + 4, + modes, + default_in_shape=tuple(size), + n_layers=2, + local_no_skip=local_no_skip, + channel_mlp_skip=channel_mlp_skip, + use_channel_mlp=True, + channel_mlp_expansion=0.5, + channel_mlp_dropout=0.0, + diff_layers=[True, True], + disco_layers=[False, False], + ) + + x = torch.randn(2, 3, *size) + res = block(x) + + # Check output shape + assert res.shape == (2, 4, *size) + + # Test with channel MLP disabled + block_no_mlp = LocalNOBlocks( + 3, + 4, + modes, + default_in_shape=tuple(size), + n_layers=2, + local_no_skip=local_no_skip, + channel_mlp_skip=channel_mlp_skip, + use_channel_mlp=False, + diff_layers=[True, True], + disco_layers=[False, False], + ) + + res_no_mlp = block_no_mlp(x) + assert res_no_mlp.shape == (2, 4, *size) + + +@pytest.mark.parametrize("norm_groups", [1, 2, 4, 8]) +def test_LocalNOBlock_group_norm(norm_groups): + """Test LocalNOBlocks with group_norm and custom norm_groups""" + modes = (8, 8) + hidden_channels = 16 + n_layers = 1 + size = [12] * 2 + + block = LocalNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=modes, + default_in_shape=tuple(size), + n_layers=n_layers, + norm="group_norm", + norm_groups=norm_groups, + diff_layers=[True], + disco_layers=[False], + ) + + assert block.norm is not None + for norm_layer in block.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + assert norm_layer.num_channels == hidden_channels diff --git a/sources/neuraloperator/neuralop/layers/tests/test_neighbor_search.py b/sources/neuraloperator/neuralop/layers/tests/test_neighbor_search.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e1cc90e8603afb4d8d12aa9879d47b40c3b412 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_neighbor_search.py @@ -0,0 +1,55 @@ +""" +Tests fallback neighbor search on a small 2d grid +that was calculated manually +""" + +import numpy as np +import torch +import pytest + +from ..neighbor_search import native_neighbor_search + +# Manually-calculated CSR list of neighbors +# in a 5x5 grid on [0,1] X [0,1] for radius=0.3 + +indices = [0, 1, 5, 0, 1, 2, 6, 1, 2, 3, 7, 2, 3, 4, 8, + 3, 4, 9, 0, 5, 6, 10, 1, 5, 6, 7, 11, 2, 6, 7, + 8, 12, 3, 7, 8, 9, 13, 4, 8, 9, 14, 5, 10, 11, + 15, 6, 10, 11, 12, 16, 7, 11, 12, 13, 17, 8, 12, + 13, 14, 18, 9, 13, 14, 19, 10, 15, 16, 20, 11, 15, + 16, 17, 21, 12, 16, 17, 18, 22, 13, 17, 18, 19, 23, + 14, 18, 19, 24, 15, 20, 21, 16, 20, 21, 22, 17, 21, + 22, 23, 18, 22, 23, 24, 19, 23, 24] + +splits = [0, 3, 7, 11, 15, 18, 22, 27, 32, 37, 41, 45, 50, + 55, 60, 64, 68, 73, 78, 83, 87, 90, 94, 98, 102, 105] + +def test_fallback_nb_search(): + mesh_grid = np.stack( + np.meshgrid(*[np.linspace(0, 1, 5) for _ in range(2)], indexing="ij"), axis=-1 + ) + coords = torch.Tensor( + mesh_grid.reshape(-1, 2) + ) # reshape into n**d x d coord points + return_dict = native_neighbor_search( + data=coords, queries=coords, radius=0.3, return_norm=True + ) + + assert return_dict["neighbors_index"].tolist() == indices + assert return_dict["neighbors_row_splits"].tolist() == splits + print(f"{return_dict['weights']=}") + + def compute_norm_separate(nbrs, data, queries): + return_dict = nbrs + num_reps = ( + return_dict["neighbors_row_splits"][1:] + - return_dict["neighbors_row_splits"][:-1] + ) + rep_queries = torch.repeat_interleave(queries, num_reps, dim=0) + rep_data = data[return_dict["neighbors_index"]] + rep_dist = rep_queries - rep_data + return_dict["squared_norm"] = (rep_dist**2).sum(dim=-1) + return return_dict + + return_dict = compute_norm_separate(return_dict, coords, coords) + print(return_dict["squared_norm"]) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_padding.py b/sources/neuraloperator/neuralop/layers/tests/test_padding.py new file mode 100644 index 0000000000000000000000000000000000000000..13bb3dbdccbcd013f831cbddd65bd41dbf605d7f --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_padding.py @@ -0,0 +1,17 @@ +import torch +from ..padding import DomainPadding +import pytest + + +def test_DomainPadding(): + data = torch.randn((2, 3, 10, 10)) + padder = DomainPadding(0.2) + padded = padder.pad(data) + + # With 0.2 padding and symmetric mode, output size should be 14 + target_shape = list(padded.shape) + target_shape[-1] = target_shape[-2] = 14 + assert list(padded.shape) == target_shape + + unpadded = padder.unpad(padded) + assert unpadded.shape == data.shape diff --git a/sources/neuraloperator/neuralop/layers/tests/test_resample.py b/sources/neuraloperator/neuralop/layers/tests/test_resample.py new file mode 100644 index 0000000000000000000000000000000000000000..aced5ee8d6fab70255ab1e54717666b29b8b78f0 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_resample.py @@ -0,0 +1,24 @@ +from ..resample import resample +import torch + + +def test_resample(): + a = torch.randn(10, 20, 40, 50) + + res_scale = [2, 3] + axis = [-2, -1] + + b = resample(a, res_scale, axis) + assert b.shape[-1] == 3 * a.shape[-1] and b.shape[-2] == 2 * a.shape[-2] + + a = torch.randn((10, 20, 40, 50, 60)) + + res_scale = [0.5, 3, 4] + axis = [-3, -2, -1] + b = resample(a, res_scale, axis) + + assert ( + b.shape[-1] == 4 * a.shape[-1] + and b.shape[-2] == 3 * a.shape[-2] + and b.shape[-3] == int(0.5 * a.shape[-3]) + ) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_rno_block.py b/sources/neuraloperator/neuralop/layers/tests/test_rno_block.py new file mode 100644 index 0000000000000000000000000000000000000000..43a34e50923cb58e6af520c30b7b03ba1db9e90e --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_rno_block.py @@ -0,0 +1,252 @@ +import pytest +import torch +from ..rno_block import RNOBlock + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_basic(n_dim, complex_data): + """Test RNOBlock with basic functionality""" + modes = (8, 8, 8) + width = 16 + size = [12] * n_dim + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes[:n_dim], + hidden_channels=width, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + # Test forward pass + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + # Test with custom hidden state + h_init = torch.randn(batch_size, width, *size, dtype=dtype) + out_custom = layer(x, h_init) + assert out_custom.shape == (batch_size, width, *size) + assert out_custom.dtype == dtype + + +@pytest.mark.parametrize("return_sequences", [False, True]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_return_sequences(return_sequences, complex_data): + """Test RNOBlock with return_sequences option""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + return_sequences=return_sequences, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + + if return_sequences: + assert out.shape == (batch_size, num_timesteps, width, *size) + else: + assert out.shape == (batch_size, width, *size) + + assert out.dtype == dtype + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +@pytest.mark.parametrize("complex_data", [False]) # Skip complex for resolution scaling (interpolation not supported) +def test_RNOBlock_resolution_scaling(n_dim, complex_data): + """Test RNOBlock with resolution scaling""" + modes = (8, 8, 8) + width = 16 + size = [12] * n_dim + batch_size = 2 + num_timesteps = 3 + + # Test upsampling + layer_up = RNOBlock( + n_modes=modes[:n_dim], + hidden_channels=width, + resolution_scaling_factor=2.0, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out_up = layer_up(x) + expected_size_up = tuple(s * 2 for s in size) + assert out_up.shape == (batch_size, width, *expected_size_up) + assert out_up.dtype == dtype + + # Test downsampling + layer_down = RNOBlock( + n_modes=modes[:n_dim], + hidden_channels=width, + resolution_scaling_factor=0.5, + complex_data=complex_data, + ) + + out_down = layer_down(x) + expected_size_down = tuple(s // 2 for s in size) + assert out_down.shape == (batch_size, width, *expected_size_down) + assert out_down.dtype == dtype + + +@pytest.mark.parametrize("norm", [None, "group_norm", "instance_norm"]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_norm(norm, complex_data): + """Test RNOBlock with different normalization options""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + norm=norm, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + +@pytest.mark.parametrize("stabilizer", [None, "tanh"]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_stabilizer(stabilizer, complex_data): + """Test RNOBlock with stabilizer options""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + stabilizer=stabilizer, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + +@pytest.mark.parametrize("separable", [False, True]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_separable(separable, complex_data): + """Test RNOBlock with separable convolutions""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + separable=separable, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + +@pytest.mark.parametrize("preactivation", [False, True]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_preactivation(preactivation, complex_data): + """Test RNOBlock with preactivation""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + preactivation=preactivation, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + +@pytest.mark.parametrize("factorization", [None, "Tucker"]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_RNOBlock_factorization(factorization, complex_data): + """Test RNOBlock with factorization""" + modes = (8, 8) + width = 16 + size = [12, 12] + batch_size = 2 + num_timesteps = 3 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=width, + factorization=factorization, + rank=0.5 if factorization else 1.0, + complex_data=complex_data, + ) + + dtype = torch.cfloat if complex_data else torch.float32 + x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype) + + out = layer(x) + assert out.shape == (batch_size, width, *size) + assert out.dtype == dtype + + +@pytest.mark.parametrize("norm_groups", [1, 2, 4, 8]) +def test_RNOBlock_group_norm(norm_groups): + """Test RNOBlock with group_norm and custom norm_groups""" + modes = (8, 8) + hidden_channels = 16 + + layer = RNOBlock( + n_modes=modes, + hidden_channels=hidden_channels, + norm="group_norm", + norm_groups=norm_groups, + ) + + # RNOBlock contains an RNOCell which contains 6 FNOBlocks (3 input + 3 hidden gates) + for fno_block in [*layer.cell.input_gates, *layer.cell.hidden_gates]: + assert fno_block.norm is not None + for norm_layer in fno_block.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + assert norm_layer.num_channels == hidden_channels diff --git a/sources/neuraloperator/neuralop/layers/tests/test_segment_csr.py b/sources/neuraloperator/neuralop/layers/tests/test_segment_csr.py new file mode 100644 index 0000000000000000000000000000000000000000..14b7af6f29b778d99a8ee59e47fe2cab83f7756e --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_segment_csr.py @@ -0,0 +1,46 @@ +import torch +from ..segment_csr import segment_csr + +import pytest + + +@pytest.mark.parametrize("batch_size", [1, 4]) +def test_native_segcsr_shapes(batch_size): + n_pts = 25 + n_channels = 5 + max_nbrhd_size = 7 # prevent degenerate cases in testing + + # tensor to reduce + src = torch.randn((batch_size, n_pts, n_channels)) + + # randomly generate index pointer tensor for CSR format + nbrhd_sizes = [torch.tensor([0])] + while sum(nbrhd_sizes) < n_pts: + nbrhd_sizes.append(torch.randint(0, max_nbrhd_size + 1, size=(1,))) + max_nbrhd_size = min(max_nbrhd_size, n_pts - sum(nbrhd_sizes)) + indptr = torch.cumsum(torch.tensor(nbrhd_sizes, dtype=torch.long), dim=0) + if batch_size > 1: + indptr = indptr.repeat([batch_size] + [1] * indptr.ndim) + else: + src = src.squeeze(0) + out = segment_csr(src, indptr, reduction="sum", use_scatter=False) + + if batch_size == 1: + assert out.shape == (len(indptr) - 1, n_channels) + else: + assert out.shape == (batch_size, indptr.shape[1] - 1, n_channels) + + +def test_native_segcsr_reductions(): + src = torch.ones([10, 3]) + indptr = torch.tensor([0, 3, 8, 10], dtype=torch.long) + + out_sum = segment_csr(src, indptr, reduction="sum", use_scatter=False) + assert out_sum.shape == (3, 3) + diff = out_sum - torch.tensor([[3, 5, 2]]).T * torch.ones([3, 3]) + assert not diff.nonzero().any() + + out_mean = segment_csr(src, indptr, reduction="mean", use_scatter=False) + assert out_mean.shape == (3, 3) + diff = out_mean - torch.ones([3, 3]) + assert not diff.nonzero().any() diff --git a/sources/neuraloperator/neuralop/layers/tests/test_sin_embeddings.py b/sources/neuraloperator/neuralop/layers/tests/test_sin_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5c52b1261372b97406cee4e0623112b8726271 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_sin_embeddings.py @@ -0,0 +1,110 @@ +import math + +import torch +from torch.testing import assert_close +import pytest + +from ..embeddings import SinusoidalEmbedding + +# Testing NeRF Embedding: start with a simple range +# and see that it is embedded properly + +batch_size = 4 +num_freqs = 3 +in_channels = 3 +n_in = 2 +max_pos = 10000 + +if torch.backends.cuda.is_built(): + device = "cuda" +else: + device = "cpu" + + +def test_NeRFEmbedding(): + nerf_embed = SinusoidalEmbedding( + in_channels=in_channels, num_frequencies=3, embedding_type="nerf" + ) + unbatched_inputs = torch.arange(in_channels) * torch.tensor([[1.0], [0.5]]) + embeds = nerf_embed(unbatched_inputs.to(device)) + + true_outputs = torch.zeros(n_in, in_channels * num_freqs * 2).to(device) + + # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p)) + for channel in range(in_channels): + for wavenumber in range(num_freqs): + for i in range(2): + idx = channel * (num_freqs * 2) + wavenumber * 2 + i + freqs = 2**wavenumber * math.pi * unbatched_inputs[:, channel] + if i == 0: + true_outputs[:, idx] = freqs.sin() + else: + true_outputs[:, idx] = freqs.cos() + assert_close(embeds, true_outputs) + + batched_inputs = torch.stack( + [torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])] * batch_size + ) + embeds = nerf_embed(batched_inputs.to(device)) + + true_outputs = torch.zeros(batch_size, n_in, in_channels * num_freqs * 2).to(device) + + # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p)) + for channel in range(in_channels): + for wavenumber in range(num_freqs): + for i in range(2): + idx = channel * (num_freqs * 2) + wavenumber * 2 + i + freqs = 2**wavenumber * math.pi * batched_inputs[:, :, channel] + if i == 0: + true_outputs[:, :, idx] = freqs.sin() + else: + true_outputs[:, :, idx] = freqs.cos() + assert_close(embeds, true_outputs) + + +def test_TransformerEmbedding(): + sin_embed = SinusoidalEmbedding( + in_channels=in_channels, + num_frequencies=3, + embedding_type="transformer", + max_positions=max_pos, + ) + unbatched_inputs = torch.arange(in_channels) * torch.tensor([[1.0], [0.5]]) + embeds = sin_embed(unbatched_inputs.to(device)) + + true_outputs = torch.zeros(n_in, in_channels * num_freqs * 2).to(device) + + # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p)) + for channel in range(in_channels): + for wavenumber in range(num_freqs): + for i in range(2): + idx = channel * (num_freqs * 2) + wavenumber * 2 + i + freqs = ( + (1 / max_pos) ** (wavenumber / sin_embed.num_frequencies * 2) + ) * unbatched_inputs[:, channel] + if i == 0: + true_outputs[:, idx] = freqs.sin() + else: + true_outputs[:, idx] = freqs.cos() + assert_close(embeds, true_outputs) + + batched_inputs = torch.stack( + [torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])] * batch_size + ) + embeds = sin_embed(batched_inputs.to(device)) + + true_outputs = torch.zeros(batch_size, n_in, in_channels * num_freqs * 2).to(device) + + # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p)) + for channel in range(in_channels): + for wavenumber in range(num_freqs): + for i in range(2): + idx = channel * (num_freqs * 2) + wavenumber * 2 + i + freqs = ( + (1 / max_pos) ** (wavenumber / sin_embed.num_frequencies * 2) + ) * batched_inputs[:, :, channel] + if i == 0: + true_outputs[:, :, idx] = freqs.sin() + else: + true_outputs[:, :, idx] = freqs.cos() + assert_close(embeds, true_outputs) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_spectral_convolution.py b/sources/neuraloperator/neuralop/layers/tests/test_spectral_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..db31b6304751040c719a45f1f2d5c2f0f9586a82 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_spectral_convolution.py @@ -0,0 +1,115 @@ +import pytest +import torch +from tltorch import FactorizedTensor +from ..spectral_convolution import SpectralConv + + +@pytest.mark.parametrize("factorization", ["Dense", "CP", "Tucker", "TT"]) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +@pytest.mark.parametrize("separable", [False, True]) +@pytest.mark.parametrize("dim", [1, 2, 3, 4]) +@pytest.mark.parametrize("complex_data", [False, True]) +def test_SpectralConv(factorization, implementation, separable, dim, complex_data): + """Test for SpectralConv of any order + + Compares Factorized and Dense convolution output + Verifies that a dense conv and factorized conv with the same weight produce the same output + + Checks the output size + + Verifies that dynamically changing the number of Fourier modes doesn't break the conv + """ + modes = (10, 8, 6, 6) + incremental_modes = (6, 6, 4, 4) + dtype = torch.cfloat if complex_data else torch.float32 + + # Test for Conv1D to Conv4D + conv = SpectralConv( + 3, + 3, + modes[:dim], + bias=False, + implementation=implementation, + factorization=factorization, + complex_data=complex_data, + separable=separable, + ) + + conv_dense = SpectralConv( + 3, + 3, + modes[:dim], + bias=False, + implementation="reconstructed", + factorization=None, + complex_data=complex_data, + ) + + x = torch.randn(2, 3, *(12,) * dim, dtype=dtype) + + assert torch.is_complex(conv.weight) + assert torch.is_complex(conv_dense.weight) + + # this closeness test only works if the weights in full form have the same shape + if not separable: + conv_dense.weight = FactorizedTensor.from_tensor( + conv.weight.to_tensor(), rank=None, factorization="ComplexDense" + ) + + res_dense = conv_dense(x) + res = conv(x) + res_shape = res.shape + + # this closeness test only works if the weights in full form have the same shape + if not separable: + torch.testing.assert_close(res_dense, res) + + # Dynamically reduce the number of modes in Fourier space + conv.n_modes = incremental_modes[:dim] + res = conv(x) + assert res_shape == res.shape + + # Downsample outputs + block = SpectralConv(3, 4, modes[:dim], resolution_scaling_factor=0.5) + + x = torch.randn(2, 3, *(12,) * dim) + res = block(x) + assert list(res.shape[2:]) == [12 // 2] * dim + + # Upsample outputs + block = SpectralConv(3, 4, modes[:dim], resolution_scaling_factor=2) + + x = torch.randn(2, 3, *(12,) * dim) + res = block(x) + assert res.shape[1] == 4 # Check out channels + assert list(res.shape[2:]) == [12 * 2] * dim + + +@pytest.mark.parametrize("enforce_hermitian_symmetry", [True, False]) +@pytest.mark.parametrize("dim", [1, 2, 3]) +@pytest.mark.parametrize("spatial_size", [8, 9]) # Even and odd: Nyquist handling differs +@pytest.mark.parametrize("resolution_scaling_factor", [None, 0.5, 2]) +@pytest.mark.parametrize("modes", [(4, 4, 4), (4, 5, 7)]) +def test_SpectralConv2(enforce_hermitian_symmetry, dim, spatial_size, modes, resolution_scaling_factor): + modes = modes[:dim] + size = [spatial_size] * dim + if resolution_scaling_factor is None: + out_size = size + else: + out_size = [round(s * resolution_scaling_factor) for s in size] + + # Test with real-valued data + conv = SpectralConv( + 3, + 4, + modes, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + complex_data=False, + resolution_scaling_factor=resolution_scaling_factor, + ) + x = torch.randn(2, 3, *size, dtype=torch.float32) + res = conv(x) + + assert res.shape == (2, 4, *out_size) + assert res.dtype == torch.float32 + assert not torch.is_complex(res) diff --git a/sources/neuraloperator/neuralop/layers/tests/test_spectral_projection.py b/sources/neuraloperator/neuralop/layers/tests/test_spectral_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b2e94a1e5cf29b6b9a9dcaeabc08be57ed08a7 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_spectral_projection.py @@ -0,0 +1,36 @@ +import torch +import pytest +import numpy as np +from ..spectral_projection import spectral_projection_divergence_free + +@pytest.mark.parametrize("resolution", [(64, 64), (80, 60), (60, 80)]) +@pytest.mark.parametrize("constraint_modes", [(64, 64), (50, 64), (72, 60)]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) +def test_spectral_projection(resolution, constraint_modes, dtype): + """Test spectral projection functionality with different resolutions, constraint modes and dtypes.""" + + height, width = resolution + batch_size = 3 + domain_size = 2 * np.pi + + # Create a simple velocity field with some divergence + x = torch.linspace(0, domain_size, width) + y = torch.linspace(0, domain_size, height) + X, Y = torch.meshgrid(x, y, indexing='ij') + + # Example u_x = sin(y), u_y = cos(x) + u_x = torch.sin(Y.T).unsqueeze(0).unsqueeze(0).expand(batch_size, 1, height, width) + u_y = torch.cos(X.T).unsqueeze(0).unsqueeze(0).expand(batch_size, 1, height, width) + u = torch.cat([u_x, u_y], dim=1).to(dtype) + + # Apply spectral projection + u_projected = spectral_projection_divergence_free(u, domain_size, constraint_modes) + + # Check output shape and properties + assert u_projected.shape == u.shape + assert u_projected.dtype == dtype + assert u_projected.device == u.device + + # Check no NaN or inf values + assert not torch.isnan(u_projected).any() + assert not torch.isinf(u_projected).any() diff --git a/sources/neuraloperator/neuralop/layers/tests/test_spherical_convolution.py b/sources/neuraloperator/neuralop/layers/tests/test_spherical_convolution.py new file mode 100644 index 0000000000000000000000000000000000000000..c987efa2dcc7453d259f88f240032e931f40c597 --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/tests/test_spherical_convolution.py @@ -0,0 +1,108 @@ +import pytest +import torch +from tltorch import FactorizedTensor + +try: + import torch_harmonics +except ModuleNotFoundError: + pytest.skip( + "Skipping because torch_harmonics is not installed", allow_module_level=True + ) + +from ..spherical_convolution import SphericalConv +from ..spherical_convolution import SHT + + +@pytest.mark.parametrize( + "factorization", ["ComplexDense", "ComplexCP", "ComplexTucker", "ComplexTT"] +) +@pytest.mark.parametrize("implementation", ["factorized", "reconstructed"]) +def test_SphericalConv(factorization, implementation): + """Test for SphericalConv (2D only) + + Compares Factorized and Dense convolution output + Verifies that a dense conv and factorized conv with the same weight produce the same output + + Checks the output size + + Verifies that dynamically changing the number of Fourier modes doesn't break the conv + """ + n_modes = (6, 6) + + conv = SphericalConv( + 3, + 3, + n_modes, + bias=False, + implementation=implementation, + factorization=factorization, + ) + + conv_dense = SphericalConv( + 3, 3, n_modes, bias=False, implementation="reconstructed", factorization=None + ) + + conv_dense.weight = FactorizedTensor.from_tensor( + conv.weight.to_tensor(), rank=None, factorization="ComplexDense" + ) + x = torch.randn(2, 3, *(12, 12)) + + res_dense = conv_dense(x) + res = conv(x) + + torch.testing.assert_close(res_dense, res) + + # Downsample outputs + block = SphericalConv(3, 4, n_modes, resolution_scaling_factor=0.5) + + x = torch.randn(2, 3, *(12, 12)) + res = block(x) + assert list(res.shape[2:]) == [12 // 2, 12 // 2] + + # Upsample outputs + block = SphericalConv(3, 4, n_modes, resolution_scaling_factor=2) + + x = torch.randn(2, 3, *(12, 12)) + res = block(x) + assert res.shape[1] == 4 # Check out channels + assert list(res.shape[2:]) == [12 * 2, 12 * 2] + + # Test change of grid + block_0 = SphericalConv(4, 4, n_modes, sht_grids=["equiangular", "legendre-gauss"]) + + block_1 = SphericalConv(4, 4, n_modes, sht_grids=["legendre-gauss", "equiangular"]) + + x = torch.randn(2, 4, *(12, 12)) + res = block_0(x) + res = block_1(res) + assert res.shape[2:] == x.shape[2:] + + res = block_0.transform(x) + res = block_1.transform(res) + assert res.shape[2:] == x.shape[2:] + + +@pytest.mark.parametrize("grid", ["equiangular", "legendre-gauss"]) +def test_sht(grid): + nlat = 16 + nlon = 2 * nlat + batch_size = 2 + if grid == "equiangular": + mmax = nlat // 2 + else: + mmax = nlat + lmax = mmax + norm = "ortho" + dtype = torch.float32 + + sht_handle = SHT(dtype=dtype) + + # Create input + coeffs = torch.zeros(batch_size, lmax, mmax, dtype=torch.complex64) + coeffs[:, :lmax, :mmax] = torch.randn(batch_size, lmax, mmax, dtype=torch.complex64) + + signal = sht_handle.isht(coeffs, s=(nlat, nlon), grid=grid, norm=norm).to(torch.float32) + + coeffs = sht_handle.sht(signal, s=(lmax, mmax), grid=grid, norm=norm) + rec = sht_handle.isht(coeffs, s=(nlat, nlon), grid=grid, norm=norm) + torch.testing.assert_close(signal, rec, rtol=1e-4, atol=1e-4) diff --git a/sources/neuraloperator/neuralop/losses/__init__.py b/sources/neuraloperator/neuralop/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3dc773465f650a70bb0a387dd70b8ca5861cd4b --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/__init__.py @@ -0,0 +1,10 @@ +from .data_losses import LpLoss, H1Loss +from .equation_losses import BurgersEqnLoss, ICLoss +from .differentiation import FourierDiff, non_uniform_fd, FiniteDiff +from .meta_losses import ( + WeightedSumLoss, + FieldwiseAggregatorLoss, + Aggregator, + Relobralo, + SoftAdapt, +) diff --git a/sources/neuraloperator/neuralop/losses/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/losses/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2330f11055ea4ff48cbdfd31e146b1135b3cf98 Binary files /dev/null and b/sources/neuraloperator/neuralop/losses/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/losses/__pycache__/data_losses.cpython-313.pyc b/sources/neuraloperator/neuralop/losses/__pycache__/data_losses.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a41163401b944fd61a85860c9aa35095d7d2d98d Binary files /dev/null and b/sources/neuraloperator/neuralop/losses/__pycache__/data_losses.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/losses/__pycache__/differentiation.cpython-313.pyc b/sources/neuraloperator/neuralop/losses/__pycache__/differentiation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dca489c0420fba6f61a6444d629ddcc7ba1bfbae Binary files /dev/null and b/sources/neuraloperator/neuralop/losses/__pycache__/differentiation.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/losses/__pycache__/equation_losses.cpython-313.pyc b/sources/neuraloperator/neuralop/losses/__pycache__/equation_losses.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48b9b1378e2a51929013d4d8ee321e202f1555e2 Binary files /dev/null and b/sources/neuraloperator/neuralop/losses/__pycache__/equation_losses.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/losses/__pycache__/meta_losses.cpython-313.pyc b/sources/neuraloperator/neuralop/losses/__pycache__/meta_losses.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..014e10e4453924a465026164763fba6e4870ea81 Binary files /dev/null and b/sources/neuraloperator/neuralop/losses/__pycache__/meta_losses.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/losses/data_losses.py b/sources/neuraloperator/neuralop/losses/data_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..eab850e73c604ca2d0a65f58828fc1dfb2d61cd7 --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/data_losses.py @@ -0,0 +1,879 @@ +""" +data_losses.py contains code to compute standard data objective +functions for training Neural Operators. + +By default, losses expect arguments y_pred (model predictions) and y (ground y.) +""" + +import math +import warnings +from typing import List + +import torch + +from .differentiation import FiniteDiff + +# Set warning filter to show each warning only once +warnings.filterwarnings("once", category=UserWarning) + + +#loss function with rel/abs Lp loss +class LpLoss(object): + """LpLoss provides the Lp norm between two discretized d-dimensional functions. + + Note that LpLoss always averages over the spatial dimensions. + + .. note:: + In function space, the Lp norm is an integral over the + entire domain. To ensure the norm converges to the integral, + we scale the matrix norm by quadrature weights along each spatial dimension. + + If no quadrature is passed at a call to LpLoss, we assume a regular + discretization and take ``1 / measure`` as the quadrature weights. + + Parameters + ---------- + d : int, optional + dimension of data on which to compute, by default 1 + p : int, optional + order of L-norm, by default 2 + L-p norm: [\\sum_{i=0}^n (x_i - y_i)**p] ** (1/p) + measure : float or list, optional + measure of the domain, by default 1.0 + either single scalar for each dim, or one per dim + + .. note:: + To perform quadrature, ``LpLoss`` scales ``measure`` by the size + of each spatial dimension of ``x``, and multiplies them with + ||x-y||, such that the final norm is a scaled average over the spatial + dimensions of ``x``. + reduction : str, optional + whether to reduce across the batch and channel dimensions + by summing ('sum') or averaging ('mean') + + .. warning:: + ``LpLoss`` always reduces over the spatial dimensions according to ``self.measure``. + `reduction` only applies to the batch and channel dimensions. + eps : float, optional + small number added to the denominator for numerical stability when using the relative loss + + Examples + -------- + See the module docstring or the user guide for usage examples. + """ + + def __init__(self, d=1, p=2, measure=1.0, reduction="sum", eps=1e-8): + super().__init__() + + self.d = d + self.p = p + self.eps = eps + + allowed_reductions = ["sum", "mean"] + assert ( + reduction in allowed_reductions + ), f"error: expected `reduction` to be one of {allowed_reductions}, got {reduction}" + self.reduction = reduction + + if isinstance(measure, float): + self.measure = [measure] * self.d + else: + self.measure = measure + + @property + def name(self): + return f"L{self.p}_{self.d}Dloss" + + def uniform_quadrature(self, x): + """ + uniform_quadrature creates quadrature weights + scaled by the spatial size of ``x`` to ensure that + ``LpLoss`` computes the average over spatial dims. + + Parameters + ---------- + x : torch.Tensor + input data + + Returns + ------- + quadrature : list + list of quadrature weights per-dim + """ + quadrature = [0.0] * self.d + for j in range(self.d, 0, -1): + quadrature[-j] = self.measure[-j] / x.size(-j) + + return quadrature + + def reduce_all(self, x): + """ + reduce x across the batch according to `self.reduction` + + Parameters + ---------- + x: torch.Tensor + inputs + """ + if self.reduction == "sum": + x = torch.sum(x) + else: + x = torch.mean(x) + + return x + + def abs(self, x, y, quadrature=None, take_root=True): + """absolute Lp-norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + quadrature weights for integral + either single scalar or one per dimension + take_root : bool, optional + whether to take the p-th root of the norm, by default True + """ + # Assume uniform mesh + if quadrature is None: + quadrature = self.uniform_quadrature(x) + else: + if isinstance(quadrature, float): + quadrature = [quadrature]*self.d + + diff_flat = torch.flatten(x, start_dim=-self.d) - torch.flatten(y, start_dim=-self.d) + + if self.p == 1: + const = math.prod(quadrature) + diff = const * torch.sum(torch.abs(diff_flat), dim=-1, keepdim=False) + elif self.p % 2 == 0: # Even power p: no need for abs() since x^p > 0 + const = math.prod(quadrature) + diff = const * torch.sum(diff_flat**self.p, dim=-1, keepdim=False) + else: + const = math.prod(quadrature) + diff = const * torch.sum( + torch.abs(diff_flat) ** self.p, dim=-1, keepdim=False + ) + + if take_root and self.p != 1: + diff = diff ** (1.0 / self.p) + + diff = self.reduce_all(diff).squeeze() + + return diff + + def rel(self, x, y, take_root=True): + """ + rel: relative LpLoss + computes ||x-y||/(||y|| + eps) + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + take_root : bool, optional + whether to take the p-th root of the norm, by default True + """ + + diff_flat = torch.flatten(x, start_dim=-self.d) - torch.flatten(y, start_dim=-self.d) + y_flat = torch.flatten(y, start_dim=-self.d) + + if self.p == 1: + diff = torch.sum(torch.abs(diff_flat), dim=-1, keepdim=False) + ynorm = torch.sum(torch.abs(y_flat), dim=-1, keepdim=False) + elif self.p % 2 == 0: # Even power p: no need for abs() since x^p > 0 + diff = torch.sum(diff_flat**self.p, dim=-1, keepdim=False) + ynorm = torch.sum(y_flat**self.p, dim=-1, keepdim=False) + else: + diff = torch.sum(torch.abs(diff_flat) ** self.p, dim=-1, keepdim=False) + ynorm = torch.sum(torch.abs(y_flat) ** self.p, dim=-1, keepdim=False) + + if take_root and self.p != 1: + diff = (diff ** (1.0 / self.p)) / (ynorm ** (1.0 / self.p) + self.eps) + else: + diff = diff / (ynorm + self.eps) + + diff = self.reduce_all(diff).squeeze() + + return diff + + def __call__(self, y_pred, y, **kwargs): + if kwargs: + warnings.warn( + f"LpLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + return self.rel(y_pred, y) + +class H1Loss(object): + """H1 Sobolev norm between two d-dimensional discretized functions. + + .. note:: + In function space, the Sobolev norm is an integral over the + entire domain. To ensure the norm converges to the integral, + we scale the matrix norm by quadrature weights along each spatial dimension. + + If no quadrature is passed at a call to H1Loss, we assume a regular + discretization and take ``1 / measure`` as the quadrature weights. + + Parameters + ---------- + d : int, optional + dimension of input functions, by default 1 + measure : float or list, optional + measure of the domain, by default 1.0 + either single scalar for each dim, or one per dim + + .. note:: + To perform quadrature, ``H1Loss`` scales ``measure`` by the size + of each spatial dimension of ``x``, and multiplies them with + ||x-y||, such that the final norm is a scaled average over the spatial + dimensions of ``x``. + + reduction : str, optional + whether to reduce across the batch and channel dimension + by summing ('sum') or averaging ('mean') + + .. warning:: + H1Loss always averages over the spatial dimensions. + `reduction` only applies to the batch and channel dimensions. + eps : float, optional + small number added to the denominator for numerical stability when using the relative loss + periodic_in_x : bool, optional + whether to use periodic boundary conditions in x-direction when computing finite differences: + - True: periodic in x (default) + - False: non-periodic in x with forward/backward differences at boundaries + by default True + periodic_in_y : bool, optional + whether to use periodic boundary conditions in y-direction when computing finite differences: + - True: periodic in y (default) + - False: non-periodic in y with forward/backward differences at boundaries + by default True + """ + + def __init__( + self, + d=1, + measure=1.0, + reduction="sum", + eps=1e-8, + periodic_in_x=True, + periodic_in_y=True, + periodic_in_z=True, + ): + super().__init__() + + assert d > 0 and d < 4, "Currently only implemented for 1, 2, and 3-D." + + self.d = d + self.periodic_in_x = periodic_in_x + self.periodic_in_y = periodic_in_y + self.periodic_in_z = periodic_in_z + + self.eps = eps + + allowed_reductions = ["sum", "mean"] + assert ( + reduction in allowed_reductions + ), f"error: expected `reduction` to be one of {allowed_reductions}, got {reduction}" + self.reduction = reduction + + if isinstance(measure, float): + self.measure = [measure] * self.d + else: + self.measure = measure + + @property + def name(self): + return f"H1_{self.d}DLoss" + + def compute_terms(self, x, y, quadrature): + """compute_terms computes the necessary + finite-difference derivative terms for computing + the H1 norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : int or list + quadrature weights + + """ + dict_x = {} + dict_y = {} + + if self.d == 1: + dict_x[0] = x + dict_y[0] = y + + fd1d = FiniteDiff(dim=1, h=quadrature[0], periodic_in_x=self.periodic_in_x) + x_x = fd1d.dx(x) + y_x = fd1d.dx(y) + + dict_x[1] = x_x + dict_y[1] = y_x + + elif self.d == 2: + dict_x[0] = torch.flatten(x, start_dim=-2) + dict_y[0] = torch.flatten(y, start_dim=-2) + + fd2d = FiniteDiff(dim=2, h=quadrature, periodic_in_x=self.periodic_in_x, periodic_in_y=self.periodic_in_y) + x_x, x_y = fd2d.dx(x), fd2d.dy(x) + y_x, y_y = fd2d.dx(y), fd2d.dy(y) + + dict_x[1] = torch.flatten(x_x, start_dim=-2) + dict_x[2] = torch.flatten(x_y, start_dim=-2) + + dict_y[1] = torch.flatten(y_x, start_dim=-2) + dict_y[2] = torch.flatten(y_y, start_dim=-2) + + else: + dict_x[0] = torch.flatten(x, start_dim=-3) + dict_y[0] = torch.flatten(y, start_dim=-3) + + fd3d = FiniteDiff(dim=3, h=quadrature, periodic_in_x=self.periodic_in_x, periodic_in_y=self.periodic_in_y, periodic_in_z=self.periodic_in_z) + x_x, x_y, x_z = fd3d.dx(x), fd3d.dy(x), fd3d.dz(x) + y_x, y_y, y_z = fd3d.dx(y), fd3d.dy(y), fd3d.dz(y) + + dict_x[1] = torch.flatten(x_x, start_dim=-3) + dict_x[2] = torch.flatten(x_y, start_dim=-3) + dict_x[3] = torch.flatten(x_z, start_dim=-3) + + dict_y[1] = torch.flatten(y_x, start_dim=-3) + dict_y[2] = torch.flatten(y_y, start_dim=-3) + dict_y[3] = torch.flatten(y_z, start_dim=-3) + + return dict_x, dict_y + + def uniform_quadrature(self, x): + """ + uniform_quadrature creates quadrature weights + scaled by the spatial size of ``x`` to ensure that + ``LpLoss`` computes the average over spatial dims. + + Parameters + ---------- + x : torch.Tensor + input data + + Returns + ------- + quadrature : list + list of quadrature weights per-dim + """ + quadrature = [0.0] * self.d + for j in range(self.d, 0, -1): + quadrature[-j] = self.measure[-j] / x.size(-j) + + return quadrature + + def reduce_all(self, x): + """ + reduce x across the batch according to `self.reduction` + + Parameters + ---------- + x: torch.Tensor + inputs + """ + if self.reduction == "sum": + x = torch.sum(x) + else: + x = torch.mean(x) + + return x + + def abs(self, x, y, quadrature=None, take_root=True): + """absolute H1 norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + quadrature constant for reduction along each dim, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + # Assume uniform mesh + if quadrature is None: + quadrature = self.uniform_quadrature(x) + else: + if isinstance(quadrature, float): + quadrature = [quadrature] * self.d + + dict_x, dict_y = self.compute_terms(x, y, quadrature) + + const = math.prod(quadrature) + diff = const * torch.sum((dict_x[0] - dict_y[0]) ** 2, dim=-1, keepdim=False) + + for j in range(1, self.d + 1): + diff += const*torch.sum((dict_x[j] - dict_y[j])**2, dim=-1, keepdim=False) + + if take_root: + diff = diff**0.5 + + diff = self.reduce_all(diff).squeeze() + + return diff + + def rel(self, x, y, quadrature=None, take_root=True): + """relative H1-norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + quadrature constant for reduction along each dim, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + # Assume uniform mesh + if quadrature is None: + quadrature = self.uniform_quadrature(x) + else: + if isinstance(quadrature, float): + quadrature = [quadrature] * self.d + + dict_x, dict_y = self.compute_terms(x, y, quadrature) + + diff = torch.sum((dict_x[0] - dict_y[0]) ** 2, dim=-1, keepdim=False) + ynorm = torch.sum(dict_y[0] ** 2, dim=-1, keepdim=False) + + for j in range(1, self.d + 1): + diff += torch.sum((dict_x[j] - dict_y[j]) ** 2, dim=-1, keepdim=False) + ynorm += torch.sum(dict_y[j] ** 2, dim=-1, keepdim=False) + + if take_root: + diff = (diff**0.5) / (ynorm**0.5 + self.eps) + else: + diff = diff / (ynorm + self.eps) + + diff = self.reduce_all(diff).squeeze() + + return diff + + def __call__(self, y_pred, y, quadrature=None, take_root=True, **kwargs): + """ + Parameters + ---------- + y_pred : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + normalization constant for reduction, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + if kwargs: + warnings.warn( + f"H1Loss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + return self.rel(y_pred, y, quadrature=quadrature) + +class HdivLoss(object): + """Hdiv Sobolev norm between two d-dimensional discretized functions. + + .. note:: + In function space, the Sobolev norm is an integral over the + entire domain. To ensure the norm converges to the integral, + we scale the matrix norm by quadrature weights along each spatial dimension. + + If no quadrature is passed at a call to HdivLoss, we assume a regular + discretization and take ``1 / measure`` as the quadrature weights. + + Parameters + ---------- + d : int, optional + dimension of input functions, by default 1 + measure : float or list, optional + measure of the domain, by default 1.0 + either single scalar for each dim, or one per dim + + .. note:: + To perform quadrature, ``HdivLoss`` scales ``measure`` by the size + of each spatial dimension of ``x``, and multiplies them with + ||x-y||, such that the final norm is a scaled average over the spatial + dimensions of ``x``. + + reduction : str, optional + whether to reduce across the batch and channel dimension + by summing ('sum') or averaging ('mean') + + .. warning:: + HdivLoss always averages over the spatial dimensions. + `reduction` only applies to the batch and channel dimensions. + eps : float, optional + small number added to the denominator for numerical stability when using the relative loss + periodic_in_x : bool, optional + whether to use periodic boundary conditions in x-direction when computing finite differences: + - True: periodic in x (default) + - False: non-periodic in x with forward/backward differences at boundaries + by default True + periodic_in_y : bool, optional + whether to use periodic boundary conditions in y-direction when computing finite differences: + - True: periodic in y (default) + - False: non-periodic in y with forward/backward differences at boundaries + by default True + periodic_in_z : bool, optional + whether to use periodic boundary conditions in z-direction when computing finite differences: + - True: periodic in z (default) + - False: non-periodic in z with forward/backward differences at boundaries + by default True + """ + + def __init__( + self, + d=1, + measure=1.0, + reduction="sum", + eps=1e-8, + periodic_in_x=True, + periodic_in_y=True, + periodic_in_z=True, + ): + super().__init__() + + assert d > 0 and d < 4, "Currently only implemented for 1, 2, and 3-D." + + self.d = d + self.periodic_in_x = periodic_in_x + self.periodic_in_y = periodic_in_y + self.periodic_in_z = periodic_in_z + + self.eps = eps + + allowed_reductions = ["sum", "mean"] + assert ( + reduction in allowed_reductions + ), f"error: expected `reduction` to be one of {allowed_reductions}, got {reduction}" + self.reduction = reduction + + if isinstance(measure, float): + self.measure = [measure] * self.d + else: + self.measure = measure + + @property + def name(self): + return f"Hdiv_{self.d}DLoss" + + def compute_terms(self, x, y, quadrature): + """compute_terms computes the necessary + finite-difference derivative terms for computing + the Hdiv norm: it will return x and y along with their + divergence terms. + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : int or list + quadrature weights + + """ + dict_x = {} + dict_y = {} + + if self.d == 1: + dict_x[0] = x + dict_y[0] = y + + fd1d = FiniteDiff(dim=1, h=quadrature[0], periodic_in_x=self.periodic_in_x) + div_x = fd1d.dx(x) + div_y = fd1d.dx(y) + + elif self.d == 2: + dict_x[0] = torch.flatten(x, start_dim=-2) + dict_y[0] = torch.flatten(y, start_dim=-2) + + fd2d = FiniteDiff(dim=2, h=quadrature, periodic_in_x=self.periodic_in_x, periodic_in_y=self.periodic_in_y) + x_x, x_y = fd2d.dx(x), fd2d.dy(x) + y_x, y_y = fd2d.dx(y), fd2d.dy(y) + + div_x = torch.flatten(x_x + x_y, start_dim=-2) + div_y = torch.flatten(y_x + y_y, start_dim=-2) + + else: + dict_x[0] = torch.flatten(x, start_dim=-3) + dict_y[0] = torch.flatten(y, start_dim=-3) + + fd3d = FiniteDiff(dim=3, h=quadrature, periodic_in_x=self.periodic_in_x, periodic_in_y=self.periodic_in_y, periodic_in_z=self.periodic_in_z) + x_x, x_y, x_z = fd3d.dx(x), fd3d.dy(x), fd3d.dz(x) + y_x, y_y, y_z = fd3d.dx(y), fd3d.dy(y), fd3d.dz(y) + + div_x = torch.flatten(x_x + x_y + x_z, start_dim=-3) + div_y = torch.flatten(y_x + y_y + y_z, start_dim=-3) + + dict_x[1] = div_x + dict_y[1] = div_y + + return dict_x, dict_y + + def uniform_quadrature(self, x): + """ + uniform_quadrature creates quadrature weights + scaled by the spatial size of ``x`` to ensure that + ``LpLoss`` computes the average over spatial dims. + + Parameters + ---------- + x : torch.Tensor + input data + + Returns + ------- + quadrature : list + list of quadrature weights per-dim + """ + quadrature = [0.0] * self.d + for j in range(self.d, 0, -1): + quadrature[-j] = self.measure[-j] / x.size(-j) + + return quadrature + + def reduce_all(self, x): + """ + reduce x across the batch according to `self.reduction` + + Parameters + ---------- + x: torch.Tensor + inputs + """ + if self.reduction == "sum": + x = torch.sum(x) + else: + x = torch.mean(x) + + return x + + def abs(self, x, y, quadrature=None, take_root=True): + """absolute Hdiv norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + quadrature constant for reduction along each dim, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + # Assume uniform mesh + if quadrature is None: + quadrature = self.uniform_quadrature(x) + else: + if isinstance(quadrature, float): + quadrature = [quadrature] * self.d + + dict_x, dict_y = self.compute_terms(x, y, quadrature) + + const = math.prod(quadrature) + diff = const * torch.sum((dict_x[0] - dict_y[0]) ** 2, dim=-1, keepdim=False) + + diff += const * torch.sum((dict_x[1] - dict_y[1]) ** 2, dim=-1, keepdim=False) + + if take_root: + diff = diff**0.5 + + diff = self.reduce_all(diff).squeeze() + + return diff + + def rel(self, x, y, quadrature=None, take_root=True): + """relative Hdiv norm + + Parameters + ---------- + x : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + quadrature constant for reduction along each dim, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + # Assume uniform mesh + if quadrature is None: + quadrature = self.uniform_quadrature(x) + else: + if isinstance(quadrature, float): + quadrature = [quadrature] * self.d + + dict_x, dict_y = self.compute_terms(x, y, quadrature) + + diff = torch.sum((dict_x[0] - dict_y[0]) ** 2, dim=-1, keepdim=False) + ynorm = torch.sum(dict_y[0] ** 2, dim=-1, keepdim=False) + + diff += torch.sum((dict_x[1] - dict_y[1]) ** 2, dim=-1, keepdim=False) + ynorm += torch.sum(dict_y[1] ** 2, dim=-1, keepdim=False) + + if take_root: + diff = (diff**0.5) / (ynorm**0.5 + self.eps) + else: + diff = diff / (ynorm + self.eps) + + diff = self.reduce_all(diff).squeeze() + + return diff + + def __call__(self, y_pred, y, quadrature=None, take_root=True, **kwargs): + """ + Parameters + ---------- + y_pred : torch.Tensor + inputs + y : torch.Tensor + targets + quadrature : float or list, optional + normalization constant for reduction, by default None + take_root : bool, optional + whether to take the square root of the norm, by default True + """ + if kwargs: + warnings.warn( + f"HdivLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + return self.rel(y_pred, y, quadrature=quadrature) + +class PointwiseQuantileLoss(object): + """PointwiseQuantileLoss computes Quantile Loss. + + It is used for uncertainty quantification of Neural Operators, as described in [1]_. + + Parameters + ---------- + alpha : float + value, between 0 and 1, of the proportion of points + in the output domain expected to fall within predicted quantiles + reduction : str, optional + whether to reduce across the batch and channel dimensions + by summing ('sum') or averaging ('mean') + + .. warning:: + PointwiseQuantileLoss always averages over the spatial dimensions. + `reduction` only applies to the batch and channel dimensions. + + References + ---------- + .. [1] Ma, Z., Pitt, D., Azizzadenesheli, K., Anandkumar, A., (2024). + Calibrated Uncertainty Quantification for Operator Learning via Conformal Prediction + TMLR 2024, https://openreview.net/pdf?id=cGpegxy12T + """ + + def __init__(self, alpha, reduction="sum"): + super().__init__() + + self.alpha = alpha + + allowed_reductions = ["sum", "mean"] + assert ( + reduction in allowed_reductions + ), f"error: expected `reduction` to be one of {allowed_reductions}, got {reduction}" + self.reduction = reduction + + def reduce_all(self, x): + """ + reduce x across the batch according to `self.reduction` + + Parameters + ---------- + x: torch.Tensor + inputs + """ + if self.reduction == "sum": + x = torch.sum(x) + else: + x = torch.mean(x) + + return x + + def __call__(self, y_pred, y, eps=1e-7, **kwargs): + """ + y_pred : torch.tensor + predicted pointwise quantile widths + y : torch.tensor + true pointwise diffs (model pred - ytrue) + """ + if kwargs: + warnings.warn( + f"PointwiseQuantileLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + + quantile = 1 - self.alpha + y_abs = torch.abs(y) + diff = y_abs - y_pred + yscale, _ = torch.max(y_abs, dim=0) + yscale = yscale + eps + ptwise_loss = torch.max(quantile * diff, -(1 - quantile) * diff) + + # scale pointwise loss: with prob 1-q it's weighed by q and prob q weighed by 1-q + ptwise_loss_scaled = ptwise_loss / 2 / quantile / (1 - quantile) / yscale + ptavg_loss = ptwise_loss_scaled.view(ptwise_loss_scaled.shape[0], -1).mean(1, keepdim=True) + + loss_batch = self.reduce_all(ptavg_loss).squeeze() + + return loss_batch + + +class MSELoss(object): + """Mean-squared L2 error between two tensors. + """ + + def __init__(self): + super().__init__() + + def __call__(self, y_pred: torch.Tensor, y: torch.Tensor, dim: List[int] = None, **kwargs): + """MSE loss call + + Parameters + ---------- + y_pred : torch.Tensor + tensor of predictions + y : torch.Tensor + ground truth, must be same shape as y_pred + dim : List[int], optional + dimensions across which to compute MSE, by default None + """ + if kwargs: + warnings.warn( + f"MSELoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + assert y_pred.shape == y.shape, (y.shape, y_pred.shape) + if dim is None: + dim = list(range(1, y_pred.ndim)) # no reduction across batch dim + return torch.mean((y_pred - y) ** 2, dim=dim).sum() # sum of MSEs for each element diff --git a/sources/neuraloperator/neuralop/losses/differentiation.py b/sources/neuraloperator/neuralop/losses/differentiation.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8f14d1aa180c0cb386a5a1b6e034a94c82dd2f --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/differentiation.py @@ -0,0 +1,1360 @@ +import torch +import warnings +from ..layers.fourier_continuation import FCLegendre, FCGram + +""" +differentiation.py implements utilities for computing derivatives via finite-differences +and Fourier/spectral differentiation methods +""" + + +class FiniteDiff: + """A unified class for computing finite differences in 1D, 2D, or 3D. + + This class provides comprehensive methods for computing derivatives using finite differences + with support for both periodic and non-periodic boundary conditions. + + It implements the following high-order finite difference schemes: + - Interior points: Second-order central differences for optimal accuracy + - Periodic boundaries: Uses torch.roll for seamless periodic wrapping. + - Non-periodic boundaries: Uses third-order one-sided differences at boundary points. + + Parameters + ---------- + dim : int + Dimension of the input field. Must be 1, 2, or 3. + h : float or tuple, optional + Grid spacing(s) for finite difference calculations, by default 1.0. + - For 1D: single float or tuple with one element + - For 2D: tuple (h_x, h_y) or single float for uniform spacing + - For 3D: tuple (h_x, h_y, h_z) or single float for uniform spacing + periodic_in_x : bool, optional + Whether to use periodic boundary conditions in x-direction, by default True. + When True, uses torch.roll for efficient periodic wrapping. + When False, uses high-order one-sided differences at boundaries. + periodic_in_y : bool, optional + Whether to use periodic boundary conditions in y-direction, by default True. + When True, uses torch.roll for efficient periodic wrapping. + When False, uses high-order one-sided differences at boundaries. + Only used for 2D and 3D fields. + periodic_in_z : bool, optional + Whether to use periodic boundary conditions in z-direction, by default True. + When True, uses torch.roll for efficient periodic wrapping. + When False, uses high-order one-sided differences at boundaries. + Only used for 3D fields. + + + Available Methods + ---------------- + Derivative Methods: + - dx(u, order=1): Compute derivative with respect to x + - dy(u, order=1): Compute derivative with respect to y (2D/3D only) + - dz(u, order=1): Compute derivative with respect to z (3D only) + + Vector Calculus Operators: + - laplacian(u): Compute the Laplacian ∇²f + - gradient(u): Compute the gradient ∇f (returns vector field) + - divergence(u): Compute the divergence ∇·u (for vector fields) + - curl(u): Compute the curl ∇×u (for vector fields, 2D/3D only) + + + Mathematical Formulas + --------------------- + For first-order derivatives: + - Interior: (f_{i+1} - f_{i-1})/(2h) [2nd order central] + - Left boundary: (-11f_0 + 18f_1 - 9f_2 + 2f_3)/(6h) [3rd order forward] + - Right boundary: (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h) [3rd order backward] + + For second-order derivatives: + - Interior: (f_{i+1} - 2f_i + f_{i-1})/(h²) [2nd order central] + - Left boundary: (2f_0 - 5f_1 + 4f_2 - f_3)/(h²) [3rd order forward] + - Right boundary: (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/(h²) [3rd order backward] + + + Examples + -------- + >>> # 1D finite differences + >>> x = torch.linspace(0, 2*torch.pi, 100) + >>> u = torch.sin(x) + >>> fd1d = FiniteDiff(dim=1, h=0.1, periodic_in_x=True) + >>> du_dx = fd1d.dx(u) # First derivative + >>> d2u_dx2 = fd1d.dx(u, order=2) # Second derivative + >>> + >>> # 2D finite differences + >>> fd2d = FiniteDiff(dim=2, h=(0.1, 0.1), periodic_in_x=True, periodic_in_y=False) + >>> x = torch.linspace(0, 2*torch.pi, 50) + >>> y = torch.linspace(0, 2*torch.pi, 50) + >>> X, Y = torch.meshgrid(x, y, indexing='ij') + >>> u = torch.sin(X) * torch.cos(Y) + >>> du_dx = fd2d.dx(u) + >>> du_dy = fd2d.dy(u) + >>> grad = fd2d.gradient(u) # Returns [du_dx, du_dy] + >>> + >>> # 3D finite differences + >>> fd3d = FiniteDiff(dim=3, h=(0.1, 0.1, 0.1), periodic_in_x=True, periodic_in_y=True, periodic_in_z=False) + >>> x = torch.linspace(0, 2*torch.pi, 20) + >>> y = torch.linspace(0, 2*torch.pi, 20) + >>> z = torch.linspace(0, 2*torch.pi, 20) + >>> X, Y, Z = torch.meshgrid(x, y, z, indexing='ij') + >>> u = torch.sin(X) * torch.cos(Y) * torch.sin(Z) # 3D scalar field + >>> du_dx = fd3d.dx(u) + >>> du_dy = fd3d.dy(u) + >>> du_dz = fd3d.dz(u) + >>> laplacian = fd3d.laplacian(u) # Sum of all second derivatives + >>> + >>> # Vector field operations + >>> vx = torch.sin(X) * torch.cos(Y) * torch.sin(Z) + >>> vy = torch.cos(X) * torch.sin(Y) * torch.cos(Z) + >>> vz = torch.sin(X) * torch.sin(Y) * torch.cos(Z) + >>> v = torch.stack([vx, vy, vz], dim=-4) # 3D vector field + >>> div_v = fd3d.divergence(v) # Scalar field + >>> curl_v = fd3d.curl(v) # Vector field + + """ + + def __init__( + self, dim, h=1.0, periodic_in_x=True, periodic_in_y=True, periodic_in_z=True + ): + """ + Initialize the FiniteDiff class for computing finite differences. + + See class docstring for detailed parameter descriptions. + """ + + # Check if dim is valid + if dim not in [1, 2, 3]: + raise ValueError("dim must be 1, 2, or 3") + + self.dim = dim + + # Set up grid spacing + if isinstance(h, (int, float)): + # Create tuple of length dim with repeated h value + self.h = tuple(h for _ in range(dim)) + else: + # h is already a tuple/list + if len(h) != dim: + raise ValueError(f"For {dim}D, h must be a float or a tuple of length {dim}") + self.h = tuple(h) # Convert to tuple + + # Set up periodic conditions + self.periodic_in_x = periodic_in_x + if dim >= 2: + self.periodic_in_y = periodic_in_y + if dim >= 3: + self.periodic_in_z = periodic_in_z + + def dx(self, u, order=1): + """ + Compute derivative with respect to x. + + Parameters + ---------- + u : torch.Tensor + Input tensor + order : int, optional + Order of the derivative, by default 1 + + Returns + ------- + torch.Tensor + Derivative with respect to x + """ + if self.dim == 1: + return self._dx_1d(u, order) + elif self.dim == 2: + return self._dx_2d(u, order) + else: # dim == 3 + return self._dx_3d(u, order) + + def dy(self, u, order=1): + """ + Compute derivative with respect to y. + + Parameters + ---------- + u : torch.Tensor + Input tensor + order : int, optional + Order of the derivative, by default 1 + + Returns + ------- + torch.Tensor + Derivative with respect to y + """ + if self.dim < 2: + raise ValueError("dy is only available for 2D and 3D") + elif self.dim == 2: + return self._dy_2d(u, order) + else: # dim == 3 + return self._dy_3d(u, order) + + def dz(self, u, order=1): + """ + Compute derivative with respect to z. + + Parameters + ---------- + u : torch.Tensor + Input tensor + order : int, optional + Order of the derivative, by default 1 + + Returns + ------- + torch.Tensor + Derivative with respect to z + """ + if self.dim < 3: + raise ValueError("dz is only available for 3D") + return self._dz_3d(u, order) + + def laplacian(self, u): + """ + Compute the Laplacian ∇²f. + + Parameters + ---------- + u : torch.Tensor + Input tensor + + Returns + ------- + torch.Tensor + The Laplacian of the input tensor + """ + if self.dim == 1: + return self._dx_1d(u, 2) + elif self.dim == 2: + return self._dx_2d(u, 2) + self._dy_2d(u, 2) + else: # dim == 3 + return self._dx_3d(u, 2) + self._dy_3d(u, 2) + self._dz_3d(u, 2) + + def gradient(self, u): + """ + Compute the gradient ∇f for scalar fields. + + Parameters + ---------- + u : torch.Tensor + Input scalar field + + Returns + ------- + torch.Tensor + The gradient of the scalar field + """ + if self.dim == 1: + return self._dx_1d(u, 1) + elif self.dim == 2: + grad_x = self._dx_2d(u, 1) + grad_y = self._dy_2d(u, 1) + return torch.stack([grad_x, grad_y], dim=-3) + else: # dim == 3 + grad_x = self._dx_3d(u, 1) + grad_y = self._dy_3d(u, 1) + grad_z = self._dz_3d(u, 1) + return torch.stack([grad_x, grad_y, grad_z], dim=-4) + + def divergence(self, u): + """ + Compute the divergence ∇·u for vector fields. + + Parameters + ---------- + u : torch.Tensor + Input vector field + + Returns + ------- + torch.Tensor + The divergence of the vector field + """ + # Check input dimensions match vector field components + n_components_expected = self.dim + n_components_actual = u.shape[-self.dim - 1] + if n_components_actual != n_components_expected: + raise ValueError(f"Input must be a {self.dim}D vector field with {n_components_expected} components") + + if self.dim == 1: + return self._dx_1d(u[..., 0, :], 1) + elif self.dim == 2: + u1, u2 = u[..., 0, :, :], u[..., 1, :, :] + return self._dx_2d(u1, 1) + self._dy_2d(u2, 1) + else: # dim == 3 + u1, u2, u3 = u[..., 0, :, :, :], u[..., 1, :, :, :], u[..., 2, :, :, :] + return self._dx_3d(u1, 1) + self._dy_3d(u2, 1) + self._dz_3d(u3, 1) + + def curl(self, u): + """ + Compute the curl ∇×u for vector fields. + + Parameters + ---------- + u : torch.Tensor + Input vector field + + Returns + ------- + torch.Tensor + The curl of the vector field + """ + if self.dim == 1: + raise ValueError("Curl is not defined for 1D") + elif self.dim == 2: + if u.shape[-3] != 2: + raise ValueError("Input must be a 2D vector field with 2 components") + u1, u2 = u[..., 0, :, :], u[..., 1, :, :] + return self._dx_2d(u2, 1) - self._dy_2d(u1, 1) + else: # dim == 3 + if u.shape[-4] != 3: + raise ValueError("Input must be a 3D vector field with 3 components") + u1, u2, u3 = u[..., 0, :, :, :], u[..., 1, :, :, :], u[..., 2, :, :, :] + curl_x = self._dy_3d(u3, 1) - self._dz_3d(u2, 1) + curl_y = self._dz_3d(u1, 1) - self._dx_3d(u3, 1) + curl_z = self._dx_3d(u2, 1) - self._dy_3d(u1, 1) + return torch.stack([curl_x, curl_y, curl_z], dim=-4) + + def _dx_1d(self, u, order): + """1D derivative with respect to x.""" + if order == 1: + return self._dx_1st_1d(u) + elif order == 2: + return self._dx_2nd_1d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dx_1st_1d(self, u): + """First order derivative with respect to x (1D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1} - f_{i-1})/(2h) + dx = (torch.roll(u, -1, dims=-1) - torch.roll(u, 1, dims=-1)) / (2.0 * self.h[0]) + + else: + # Non-periodic case: handle boundaries separately + dx = torch.zeros_like(u) + + # Interior points: Second-order central differences (f_{i+1} - f_{i-1})/(2h) + dx[..., 1:-1] = (u[..., 2:] - u[..., :-2]) / (2.0 * self.h[0]) + + # Left boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h) + dx[..., 0] = (-11 * u[..., 0] + 18 * u[..., 1] - 9 * u[..., 2] + 2 * u[..., 3]) / (6.0 * self.h[0]) + + # Right boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h) + dx[..., -1] = (-2 * u[..., -4] + 9 * u[..., -3] - 18 * u[..., -2] + 11 * u[..., -1]) / (6.0 * self.h[0]) + + return dx + + def _dx_2nd_1d(self, u): + """Second order derivative with respect to x (1D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1} - 2f_{i} + f_{i-1})/(h²) + dxx = (torch.roll(u, -1, dims=-1) - 2 * u + torch.roll(u, 1, dims=-1)) / (self.h[0]**2) + + else: + # Non-periodic case: handle boundaries separately + dxx = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i+1} - 2f_{i} + f_{i-1})/(h²) + dxx[..., 1:-1] = (u[..., 2:] - 2 * u[..., 1:-1] + u[..., :-2]) / (self.h[0]**2) + + # Left boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h² + dxx[..., 0] = (2 * u[..., 0] - 5 * u[..., 1] + 4 * u[..., 2] - u[..., 3]) / (self.h[0]**2) + + # Right boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h² + dxx[..., -1] = (-u[..., -4] + 4 * u[..., -3] - 5 * u[..., -2] + 2 * u[..., -1]) / (self.h[0]**2) + + return dxx + + def _dx_2d(self, u, order): + """2D derivative with respect to x.""" + if order == 1: + return self._dx_1st_2d(u) + elif order == 2: + return self._dx_2nd_2d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dy_2d(self, u, order): + """2D derivative with respect to y.""" + if order == 1: + return self._dy_1st_2d(u) + elif order == 2: + return self._dy_2nd_2d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dx_1st_2d(self, u): + """First order derivative with respect to x (2D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1,j} - f_{i-1,j})/(2h_{x}) + dx = (torch.roll(u, -1, dims=-2) - torch.roll(u, 1, dims=-2)) / (2.0 * self.h[0]) + + else: + # Non-periodic case: handle boundaries separately + dx = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i+1,j} - f_{i-1,j})/(2h_{x}) + dx[..., 1:-1, :] = (u[..., 2:, :] - u[..., :-2, :]) / (2.0 * self.h[0]) + + # Left boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h_{x}) + dx[..., 0, :] = (-11 * u[..., 0, :] + 18 * u[..., 1, :] - 9 * u[..., 2, :] + 2 * u[..., 3, :]) / (6.0 * self.h[0]) + + # Right boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h_{x}) + dx[..., -1, :] = (-2 * u[..., -4, :] + 9 * u[..., -3, :] - 18 * u[..., -2, :] + 11 * u[..., -1, :]) / (6.0 * self.h[0]) + + return dx + + def _dy_1st_2d(self, u): + """First order derivative with respect to y (2D).""" + + if self.periodic_in_y: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j+1} - f_{i,j-1})/(2h_{y}) + dy = (torch.roll(u, -1, dims=-1) - torch.roll(u, 1, dims=-1)) / (2.0 * self.h[1]) + + else: + # Non-periodic case: handle boundaries separately + dy = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j+1} - f_{i,j-1})/(2h_{y}) + dy[..., :, 1:-1] = (u[..., :, 2:] - u[..., :, :-2]) / (2.0 * self.h[1]) + + # Bottom boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h_{y}) + dy[..., :, 0] = (-11 * u[..., :, 0] + 18 * u[..., :, 1] - 9 * u[..., :, 2] + 2 * u[..., :, 3]) / (6.0 * self.h[1]) + + # Top boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h_{y}) + dy[..., :, -1] = (-2 * u[..., :, -4] + 9 * u[..., :, -3] - 18 * u[..., :, -2] + 11 * u[..., :, -1]) / (6.0 * self.h[1]) + + return dy + + def _dx_2nd_2d(self, u): + """Second order derivative with respect to x (2D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1,j} - 2f_{i,j} + f_{i-1,j})/(h_{x}²) + dxx = (torch.roll(u, -1, dims=-2) - 2 * u + torch.roll(u, 1, dims=-2)) / (self.h[0] ** 2) + + else: + # Non-periodic case: handle boundaries separately + dxx = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i+1,j} - 2f_{i,j} + f_{i-1,j})/(h_{x}²) + dxx[..., 1:-1, :] = (u[..., 2:, :] - 2 * u[..., 1:-1, :] + u[..., :-2, :]) / (self.h[0] ** 2) + + # Left boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h_{x}² + dxx[..., 0, :] = (2 * u[..., 0, :] - 5 * u[..., 1, :] + 4 * u[..., 2, :] - u[..., 3, :]) / (self.h[0] ** 2) + + # Right boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h_{x}² + dxx[..., -1, :] = (-u[..., -4, :] + 4 * u[..., -3, :] - 5 * u[..., -2, :] + 2 * u[..., -1, :]) / (self.h[0] ** 2) + + return dxx + + def _dy_2nd_2d(self, u): + """Second order derivative with respect to y (2D).""" + + if self.periodic_in_y: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j+1} - 2f_{i,j} + f_{i,j-1})/(h_{y}²) + dyy = (torch.roll(u, -1, dims=-1) - 2 * u + torch.roll(u, 1, dims=-1)) / (self.h[1] ** 2) + + else: + # Non-periodic case: handle boundaries separately + dyy = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j+1} - 2f_{i,j} + f_{i,j-1})/(h_{y}²) + dyy[..., :, 1:-1] = (u[..., :, 2:] - 2 * u[..., :, 1:-1] + u[..., :, :-2]) / (self.h[1] ** 2) + + # Bottom boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h_{y}² + dyy[..., :, 0] = (2 * u[..., :, 0] - 5 * u[..., :, 1] + 4 * u[..., :, 2] - u[..., :, 3]) / (self.h[1] ** 2) + + # Top boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h_{y}² + dyy[..., :, -1] = (-u[..., :, -4] + 4 * u[..., :, -3] - 5 * u[..., :, -2] + 2 * u[..., :, -1]) / (self.h[1] ** 2) + + return dyy + + def _dx_3d(self, u, order): + """3D derivative with respect to x.""" + if order == 1: + return self._dx_1st_3d(u) + elif order == 2: + return self._dx_2nd_3d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dy_3d(self, u, order): + """3D derivative with respect to y.""" + if order == 1: + return self._dy_1st_3d(u) + elif order == 2: + return self._dy_2nd_3d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dz_3d(self, u, order): + """3D derivative with respect to z.""" + if order == 1: + return self._dz_1st_3d(u) + elif order == 2: + return self._dz_2nd_3d(u) + else: + raise ValueError("Only 1st and 2nd order derivatives currently supported") + + def _dx_1st_3d(self, u): + """First order derivative with respect to x (3D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1,j,k} - f_{i-1,j,k})/(2h_{x}) + dx = (torch.roll(u, -1, dims=-3) - torch.roll(u, 1, dims=-3)) / (2.0 * self.h[0]) + + else: + # Non-periodic case: handle boundaries separately + dx = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i+1,j,k} - f_{i-1,j,k})/(2h_{x}) + dx[..., 1:-1, :, :] = (u[..., 2:, :, :] - u[..., :-2, :, :]) / (2.0 * self.h[0]) + + # Left boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h_{x}) + dx[..., 0, :, :] = (-11 * u[..., 0, :, :] + 18 * u[..., 1, :, :] - 9 * u[..., 2, :, :] + 2 * u[..., 3, :, :]) / (6.0 * self.h[0]) + + # Right boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h_{x}) + dx[..., -1, :, :] = (-2 * u[..., -4, :, :] + 9 * u[..., -3, :, :] - 18 * u[..., -2, :, :] + 11 * u[..., -1, :, :]) / (6.0 * self.h[0]) + + return dx + + def _dy_1st_3d(self, u): + """First order derivative with respect to y (3D).""" + + if self.periodic_in_y: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j+1,k} - f_{i,j-1,k})/(2h_{y}) + dy = (torch.roll(u, -1, dims=-2) - torch.roll(u, 1, dims=-2)) / (2.0 * self.h[1]) + + else: + # Non-periodic case: handle boundaries separately + dy = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j+1,k} - f_{i,j-1,k})/(2h_{y}) + dy[..., :, 1:-1, :] = (u[..., :, 2:, :] - u[..., :, :-2, :]) / (2.0 * self.h[1]) + + # Bottom boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h_{y}) + dy[..., :, 0, :] = (-11 * u[..., :, 0, :] + 18 * u[..., :, 1, :] - 9 * u[..., :, 2, :] + 2 * u[..., :, 3, :]) / (6.0 * self.h[1]) + + # Top boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h_{y}) + dy[..., :, -1, :] = (-2 * u[..., :, -4, :] + 9 * u[..., :, -3, :] - 18 * u[..., :, -2, :] + 11 * u[..., :, -1, :]) / (6.0 * self.h[1]) + + return dy + + def _dz_1st_3d(self, u): + """First order derivative with respect to z (3D).""" + + if self.periodic_in_z: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j,k+1} - f_{i,j,k-1})/(2h_{z}) + dz = (torch.roll(u, -1, dims=-1) - torch.roll(u, 1, dims=-1)) / (2.0 * self.h[2]) + + else: + # Non-periodic case: handle boundaries separately + dz = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j,k+1} - f_{i,j,k-1})/(2h_{z}) + dz[..., :, :, 1:-1] = (u[..., :, :, 2:] - u[..., :, :, :-2]) / (2.0 * self.h[2]) + + # Front boundary: 3rd-order forward differences (-11f_{0} + 18f_{1} - 9f_{2} + 2f_{3})/(6h_{z}) + dz[..., :, :, 0] = (-11 * u[..., :, :, 0] + 18 * u[..., :, :, 1] - 9 * u[..., :, :, 2] + 2 * u[..., :, :, 3]) / (6.0 * self.h[2]) + + # Back boundary: 3rd-order backward differences (-2f_{n-4} + 9f_{n-3} - 18f_{n-2} + 11f_{n-1})/(6h_{z}) + dz[..., :, :, -1] = (-2 * u[..., :, :, -4] + 9 * u[..., :, :, -3] - 18 * u[..., :, :, -2] + 11 * u[..., :, :, -1]) / (6.0 * self.h[2]) + + return dz + + def _dx_2nd_3d(self, u): + """Second order derivative with respect to x (3D).""" + + if self.periodic_in_x: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i+1,j,k} - 2f_{i,j,k} + f_{i-1,j,k})/(h_{x}²) + dxx = (torch.roll(u, -1, dims=-3) - 2 * u + torch.roll(u, 1, dims=-3)) / (self.h[0] ** 2) + + else: + # Non-periodic case: handle boundaries separately + dxx = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i+1,j,k} - 2f_{i,j,k} + f_{i-1,j,k})/(h_{x}²) + dxx[..., 1:-1, :, :] = (u[..., 2:, :, :] - 2 * u[..., 1:-1, :, :] + u[..., :-2, :, :]) / (self.h[0] ** 2) + + # Left boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h_{x}² + dxx[..., 0, :, :] = (2 * u[..., 0, :, :] - 5 * u[..., 1, :, :] + 4 * u[..., 2, :, :] - u[..., 3, :, :]) / (self.h[0] ** 2) + + # Right boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h_{x}² + dxx[..., -1, :, :] = (-u[..., -4, :, :] + 4 * u[..., -3, :, :] - 5 * u[..., -2, :, :] + 2 * u[..., -1, :, :]) / (self.h[0] ** 2) + + return dxx + + def _dy_2nd_3d(self, u): + """Second order derivative with respect to y (3D).""" + + if self.periodic_in_y: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j+1,k} - 2f_{i,j,k} + f_{i,j-1,k})/(h_{y}²) + dyy = (torch.roll(u, -1, dims=-2) - 2 * u + torch.roll(u, 1, dims=-2)) / (self.h[1] ** 2) + + else: + # Non-periodic case: handle boundaries separately + dyy = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j+1,k} - 2f_{i,j,k} + f_{i,j-1,k})/(h_{y}²) + dyy[..., :, 1:-1, :] = (u[..., :, 2:, :] - 2 * u[..., :, 1:-1, :] + u[..., :, :-2, :]) / (self.h[1] ** 2) + + # Bottom boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h_{y}² + dyy[..., :, 0, :] = (2 * u[..., :, 0, :] - 5 * u[..., :, 1, :] + 4 * u[..., :, 2, :] - u[..., :, 3, :]) / (self.h[1] ** 2) + + # Top boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h_{y}² + dyy[..., :, -1, :] = (-u[..., :, -4, :] + 4 * u[..., :, -3, :] - 5 * u[..., :, -2, :] + 2 * u[..., :, -1, :]) / (self.h[1] ** 2) + + return dyy + + def _dz_2nd_3d(self, u): + """Second order derivative with respect to z (3D).""" + + if self.periodic_in_z: + # Periodic case: use torch.roll for boundary wrapping + # Central difference: (f_{i,j,k+1} - 2f_{i,j,k} + f_{i,j,k-1})/(h_{z}²) + dzz = (torch.roll(u, -1, dims=-1) - 2 * u + + torch.roll(u, 1, dims=-1)) / (self.h[2] ** 2) + + else: + # Non-periodic case: handle boundaries separately + dzz = torch.zeros_like(u) + + # Interior points: Second-order central differences + # (f_{i,j,k+1} - 2f_{i,j,k} + f_{i,j,k-1})/(h_{z}²) + dzz[..., :, :, 1:-1] = (u[..., :, :, 2:] - 2 * u[..., :, :, 1:-1] + u[..., :, :, :-2]) / (self.h[2] ** 2) + + # Front boundary: 3rd-order forward differences (2f_{0} - 5f_{1} + 4f_{2} - f_{3})/h_{z}² + dzz[..., :, :, 0] = (2 * u[..., :, :, 0] - 5 * u[..., :, :, 1] + 4 * u[..., :, :, 2] - u[..., :, :, 3]) / (self.h[2] ** 2) + + # Back boundary: 3rd-order backward differences (-f_{n-4} + 4f_{n-3} - 5f_{n-2} + 2f_{n-1})/h_{z}² + dzz[..., :, :, -1] = (-u[..., :, :, -4] + 4 * u[..., :, :, -3] - 5 * u[..., :, :, -2] + 2 * u[..., :, :, -1]) / (self.h[2] ** 2) + + return dzz + + +# Backward compatibility functions +def central_diff_1d(x, h, periodic_in_x=True): + """ + Backward compatibility function for central_diff_1d. + Creates a FiniteDiff instance with dim=1 and returns dx. + + .. deprecated:: + This function is deprecated and will be removed in future versions. + Please use the FiniteDiff class instead for better performance and features. + """ + warnings.warn( + "central_diff_1d is deprecated and may not be maintained. " + "Please use FiniteDiff class instead for better performance and features.", + DeprecationWarning, + stacklevel=2, + ) + fd1d = FiniteDiff(dim=1, h=h, periodic_in_x=periodic_in_x) + return fd1d.dx(x) + + +def central_diff_2d(x, h, periodic_in_x=True, periodic_in_y=True): + """ + Backward compatibility function for central_diff_2d. + Creates a FiniteDiff instance with dim=2 and returns dx, dy. + + .. deprecated:: + This function is deprecated and will be removed in future versions. + Please use the FiniteDiff class instead for better performance and features. + """ + warnings.warn( + "central_diff_2d is deprecated and may not be maintained. " + "Please use FiniteDiff class instead for better performance and features.", + DeprecationWarning, + stacklevel=2, + ) + fd2d = FiniteDiff( + dim=2, h=h, periodic_in_x=periodic_in_x, periodic_in_y=periodic_in_y + ) + return fd2d.dx(x), fd2d.dy(x) + + +def central_diff_3d(x, h, periodic_in_x=True, periodic_in_y=True, periodic_in_z=True): + """ + Backward compatibility function for central_diff_3d. + Creates a FiniteDiff instance with dim=3 and returns dx, dy, dz. + + .. deprecated:: + This function is deprecated and will be removed in future versions. + Please use the FiniteDiff class instead for better performance and features. + """ + warnings.warn( + "central_diff_3d is deprecated and may not be maintained. " + "Please use FiniteDiff class instead for better performance and features.", + DeprecationWarning, + stacklevel=2, + ) + fd3d = FiniteDiff( + dim=3, + h=h, + periodic_in_x=periodic_in_x, + periodic_in_y=periodic_in_y, + periodic_in_z=periodic_in_z, + ) + return fd3d.dx(x), fd3d.dy(x), fd3d.dz(x) + + +def get_non_uniform_fd_weights( + points, num_neighbors=5, derivative_indices=[0], radius=None, regularize_lstsq=False +): + """ + Compute finite difference weights for approximating the first order derivative + on an unstructured grid of points + + Parameters + ---------- + points : torch tensor of shape (N, d) containing the d coordinates of the N points + num_neighbors: int for the number of nearest neighbors to include in the stencil (including the point itself) + At least 3 and at most N + derivative_indices : indices of the derivatives to compute, e.g. in 2D, [0] for x, [1] for y, [0, 1] for x and y + radius : float, the cutoff distance to use a neighbor as radius + Neighbors with distances beyond this value are not used (their weights are set to zero) + Always keep at least 3 neighbors (including the point itself) + regularize_lstsq : bool, whether to regularize the least squares system + Sometimes torch.linalg.lstsq(A, b).solution creates artifacts so can add regularizer + But regularizer can deteriorate performance when system is well-conditioned + + Returns + ------- + indices : torch tensor of shape (N, k) for the indices of k nearest neighbors (including the point itself) + fd_weights : torch tensor of weights of shape (N, len(derivative_indices), k) + fd_weights[i,j,m] contains the weights for the m-th nearest neighbor + in the j-th 1st order derivative for the i-th point + """ + + N = points.shape[0] + d = points.shape[1] + k = min(max(num_neighbors, 3), N) + + # Get the indices of the k nearest neighbors (including the point itself) + pairwise_distances = torch.cdist(points, points, p=2) + distances, indices = torch.topk(pairwise_distances, k=k, dim=1, largest=False) + + # Get mask for neighbors within cutoff radius (and always keep at least 3) + if radius is None: + radius_mask = torch.ones_like(distances, dtype=torch.bool) + else: + radius_mask = distances <= radius + radius_mask[:, :3] = True + + # Initialize A to 1 since first row for each point and derivative is 1 + A = torch.ones((N, d + 1, k), dtype=points.dtype, device=points.device) + # Compute coordinate differences + for i in range(d): + A[:, i + 1, :] = points[indices, i] - points[:, i].unsqueeze(1) + # Repeat it for each derivative to be evaluated so it becomes of shape (N, + # len(derivative_indices), d+1, k) + A = A.unsqueeze(1).expand(-1, len(derivative_indices), -1, -1) + + # Zero out columns for neighbors that are not within the radius + A = A * radius_mask.unsqueeze(1).unsqueeze(2) + + # Compute right hand side + b = torch.zeros( + (len(derivative_indices), d + 1, 1), dtype=points.dtype, device=points.device + ) + for i in range(len(derivative_indices)): + b[i, derivative_indices[i] + 1] = 1 + # Repeat so it becomes (N, len(derivative_indices), d+1, 1) + b = b.unsqueeze(0).expand(N, -1, -1, -1) + + # Solve least squares system Aw = b + # sometimes torch.linalg.lstsq(A, b).solution creates artifacts so can add regularizer + # but regularizer can deteriorate performance when system is + # well-conditioned + + if regularize_lstsq: + lambda_reg = 1e-6 + I_k = torch.eye(k, dtype=A.dtype, device=A.device).unsqueeze(0).unsqueeze(0) + + AT = A.transpose(-2, -1) + AT_b = torch.matmul(AT, b) + AT_A = torch.matmul(AT, A) + lambda_reg * I_k + + # Use Cholesky decomposition to accelerate torch.linalg.solve(AT_A, + # AT_b).squeeze(-1) + fd_weights = torch.cholesky_solve(AT_b, torch.linalg.cholesky(AT_A)).squeeze(-1) + + else: + fd_weights = torch.linalg.lstsq(A, b).solution + + return indices, fd_weights.squeeze(-1) + + +def non_uniform_fd( + points, + values, + num_neighbors=5, + derivative_indices=[0], + radius=None, + regularize_lstsq=False, +): + """Finite difference approximation of first order derivatives on unstructured point clouds. + + Parameters + ---------- + points : torch tensor of shape (N, d) containing the d coordinates of the N points + values : torch tensor of shape (N) containing the values of the function at the N points + radius : float, the cutoff distance to use a neighbor as radius + Neighbors with distances beyond this value are not used (their weights are set to zero) + Always keep at least 3 neighbors (including the point itself) + num_neighbors: int for the number of nearest neighbors to include in the stencil (including the point itself) + derivative_indices : indices of the derivatives to compute, e.g. in 2D, [0] for x, [1] for y, [0, 1] for x and y + regularize_lstsq : bool, whether to regularize the least squares system + Sometimes torch.linalg.lstsq(A, b).solution creates artifacts so can add regularizer + But regularizer can deteriorate performance when system is well-conditioned + + Returns + ------- + derivatives: tensor of shape (len(derivative_indices), N) of derivatives + e.g. in 2D with derivative_indices=[0, 1], derivatives[0] is df(x,y)/dx and derivatives[1] is df(x,y)/dy + + """ + + indices, fd_weights = get_non_uniform_fd_weights( + points=points, + num_neighbors=num_neighbors, + derivative_indices=derivative_indices, + radius=radius, + regularize_lstsq=regularize_lstsq, + ) + + derivatives = torch.einsum("nij,nj->in", fd_weights, values[indices]) + + return derivatives + + +class FourierDiff: + """A unified class for computing Fourier/spectral derivatives in 1D, 2D, 3D. + + This class provides comprehensive methods for computing derivatives using Fourier/spectral + methods with support for both periodic and non-periodic functions through Fourier continuation: + - Periodic functions: Direct Fourier differentiation using FFT + - Non-periodic functions: Fourier continuation (FC) is used to extend functions to a larger + domain on which the functions are periodic before applying Fourier differentiation with FFT. + + The class also provides gradient, divergence, curl, and Laplacian operations. + + Parameters + ---------- + dim : int + Dimension of the input field. Must be 1, 2, or 3. + L : float or tuple, optional + Length of the domain for Fourier differentiation. By default 2*pi for each dimension. + use_fc : str, optional + Whether to use Fourier continuation for non-periodic functions. + Options: False (no FC), 'Legendre', 'Gram'. By default False. + fc_degree : int, optional + Degree of the Fourier continuation polynomial matching. This is the number + of matching points on the left and right boundaries used for the Fourier + continuation procedure. By default 4. + fc_n_additional_pts : int, optional + Number of additional points to add with the Fourier continuation layer. + This extends the domain to handle non-periodic functions. By default 50. + low_pass_filter_ratio : float, optional + If not None, apply a low-pass filter to the Fourier coefficients to reduce + high-frequency noise. Should be between 0 and 1. By default None. + + + Available Methods + ---------------- + Derivative Methods: + - dx(u, order=1): Compute derivative with respect to x + - dy(u, order=1): Compute derivative with respect to y (2D/3D only) + - dz(u, order=1): Compute derivative with respect to z (3D only) + - derivative(u, order): Compute derivative with order tuple (e.g., (1,0) for ∂/∂x) + + Vector Calculus Operators: + - laplacian(u): Compute the Laplacian ∇²f + - gradient(u): Compute the gradient ∇f (returns vector field) + - divergence(u): Compute the divergence ∇·u (for vector fields) + - curl(u): Compute the curl ∇×u (for vector fields, 2D/3D only) + + + Mathematical Background + ----------------------- + For periodic functions on [0, 2π], the derivative is computed as: + - Forward transform: û_k = FFT(u) + - Derivative in Fourier space: (∂u/∂x)^_k = ik * û_k + - Inverse transform: ∂u/∂x = IFFT(ik * û_k) + + For non-periodic functions, Fourier continuation extends the function to + an extended domain (e.g. [0, 2π] → [0, 2π + 2π*additional_pts/n]) on which + the function is periodic. + + + Examples + -------- + >>> # 1D Fourier derivatives + >>> x = torch.linspace(0, 2*torch.pi, 100) + >>> u = torch.sin(x) + >>> fd1d = FourierDiff(dim=1, L=2*torch.pi, use_fc=False) + >>> du_dx = fd1d.dx(u) # First derivative + >>> d2u_dx2 = fd1d.dx(u, order=2) # Second derivative + >>> + >>> # 2D Fourier derivatives + >>> fd2d = FourierDiff(dim=2, L=(2*torch.pi, 2*torch.pi), use_fc=False) + >>> x = torch.linspace(0, 2*torch.pi, 50) + >>> y = torch.linspace(0, 2*torch.pi, 50) + >>> X, Y = torch.meshgrid(x, y, indexing='ij') + >>> u = torch.sin(X) * torch.cos(Y) + >>> du_dx = fd2d.dx(u) + >>> du_dy = fd2d.dy(u) + >>> grad = fd2d.gradient(u) # Returns [du_dx, du_dy] + >>> + >>> # 3D Fourier derivatives + >>> fd3d = FourierDiff(dim=3, L=(2*torch.pi, 2*torch.pi, 2*torch.pi), use_fc=False) + >>> x = torch.linspace(0, 2*torch.pi, 20) + >>> y = torch.linspace(0, 2*torch.pi, 20) + >>> z = torch.linspace(0, 2*torch.pi, 20) + >>> X, Y, Z = torch.meshgrid(x, y, z, indexing='ij') + >>> u = torch.sin(X) * torch.cos(Y) * torch.sin(Z) # 3D scalar field + >>> du_dx = fd3d.dx(u) + >>> du_dy = fd3d.dy(u) + >>> du_dz = fd3d.dz(u) + >>> laplacian = fd3d.laplacian(u) + >>> + >>> # Vector field operations + >>> vx = torch.sin(X) * torch.cos(Y) * torch.sin(Z) + >>> vy = torch.cos(X) * torch.sin(Y) * torch.cos(Z) + >>> vz = torch.sin(X) * torch.sin(Y) * torch.cos(Z) + >>> v = torch.stack([vx, vy, vz], dim=-4) + >>> div_v = fd3d.divergence(v) + >>> curl_v = fd3d.curl(v) + + """ + + def __init__( + self, + dim, + L=None, + use_fc=False, + fc_degree=4, + fc_n_additional_pts=50, + low_pass_filter_ratio=None, + ): + """ + Initialize the FourierDiff class for computing Fourier derivatives. + + See class docstring for detailed parameter descriptions. + """ + + # Check if dim is valid + if dim not in [1, 2, 3]: + raise ValueError("dim must be 1, 2, or 3") + + self.dim = dim + + # Set default L based on dimension + if L is None: + L = 2 * torch.pi + if not isinstance(L, (tuple, list)): + L = (L,) * dim + if len(L) != dim: + raise ValueError(f"For {dim}D, L must be a single float or tuple with {dim} elements") + self.L = L[0] if dim == 1 else L + + self.use_fc = use_fc + self.fc_degree = fc_degree + self.fc_n_additional_pts = fc_n_additional_pts + self.low_pass_filter_ratio = low_pass_filter_ratio + + # Initialize FC class if needed + self.FC = None + if self.use_fc: + if self.use_fc.lower() in ['legendre', 'gram']: + FC_class = FCLegendre if self.use_fc.lower() == 'legendre' else FCGram + self.FC = FC_class(d=self.fc_degree, n_additional_pts=self.fc_n_additional_pts) + else: + raise ValueError(f"Given FC input {self.use_fc} is not valid. Must be 'legendre' or 'gram'.") + + def compute_multiple_derivatives(self, u, derivatives): + """ + Compute multiple derivatives in a single FFT/IFFT call for better performance. + + Parameters + ---------- + u : torch.Tensor + Input tensor. + derivatives : list + List of derivative specifications: + - 1D: list of int (orders) + - 2D: list of tuples (order_x, order_y) + - 3D: list of tuples (order_x, order_y, order_z) + + Returns + ------- + list of torch.Tensor + List of computed derivatives in the same order as derivatives input + """ + if self.dim == 1: + return self._compute_multiple_derivatives_1d(u, derivatives) + elif self.dim == 2: + return self._compute_multiple_derivatives_2d(u, derivatives) + elif self.dim == 3: + return self._compute_multiple_derivatives_3d(u, derivatives) + + def derivative(self, u, order): + """ + Compute Fourier derivative of a given tensor. + + Parameters + ---------- + u : torch.Tensor + Input tensor + order : tuple + Derivative orders: + - 1D: (order_x,) + - 2D: (order_x, order_y) + - 3D: (order_x, order_y, order_z) + + Returns + ------- + torch.Tensor + The derivative of the input tensor + """ + if len(order) != self.dim: + raise ValueError(f"For {self.dim}D, order must be a tuple with {self.dim} elements") + + if self.dim == 1: + derivatives = self._compute_multiple_derivatives_1d(u, [order[0]]) + elif self.dim == 2: + derivatives = self._compute_multiple_derivatives_2d(u, [order]) + elif self.dim == 3: + derivatives = self._compute_multiple_derivatives_3d(u, [order]) + + return derivatives[0] + + def partial(self, u, direction="x", order=1): + """ + Compute partial Fourier derivative along a specific direction. + + Parameters + ---------- + u : torch.Tensor + Input tensor + direction : str, optional + Direction along which to compute the derivative, by default 'x' + Options: 'x', 'y' (2D/3D only), 'z' (3D only) + order : int, optional + Order of the derivative, by default 1 + + Returns + ------- + torch.Tensor + The partial derivative of the input tensor + """ + if direction == "x": + return self.dx(u, order=order) + elif direction == "y" and self.dim >= 2: + return self.dy(u, order=order) + elif direction == "z" and self.dim >= 3: + return self.dz(u, order=order) + else: + raise ValueError( + f"Invalid direction '{direction}' for dimension {self.dim}" + ) + + def dx(self, u, order=1): + """Compute derivative with respect to x.""" + if self.dim == 1: + return self._dx_1d(u, order) + elif self.dim == 2: + return self._dx_2d(u, order) + elif self.dim == 3: + return self._dx_3d(u, order) + + def dy(self, u, order=1): + """Compute derivative with respect to y (2D/3D only).""" + if self.dim < 2: + raise ValueError("dy method only available for 2D and 3D") + elif self.dim == 2: + return self._dy_2d(u, order) + elif self.dim == 3: + return self._dy_3d(u, order) + + def dz(self, u, order=1): + """Compute derivative with respect to z (3D only).""" + if self.dim < 3: + raise ValueError("dz method only available for 3D") + return self._dz_3d(u, order) + + def laplacian(self, u): + """Compute the Laplacian ∇²f.""" + if self.dim == 1: + return self.dx(u, order=2) + elif self.dim == 2: + return self.dx(u, order=2) + self.dy(u, order=2) + elif self.dim == 3: + return self.dx(u, order=2) + self.dy(u, order=2) + self.dz(u, order=2) + + def gradient(self, u): + """Compute the gradient ∇f (returns vector field).""" + if self.dim == 1: + return self.dx(u).unsqueeze(-2) + elif self.dim == 2: + return torch.stack([self.dx(u), self.dy(u)], dim=-3) + elif self.dim == 3: + return torch.stack([self.dx(u), self.dy(u), self.dz(u)], dim=-4) + + def divergence(self, u): + """Compute the divergence ∇·u (for vector fields).""" + expected_dims = {1: 1, 2: 2, 3: 3} + if u.shape[-self.dim - 1] != expected_dims[self.dim]: + raise ValueError( + f"For {self.dim}D, input must have {expected_dims[self.dim]} components in the vector dimension" + ) + + if self.dim == 1: + return self.dx(u.squeeze(-2)) + elif self.dim == 2: + return self.dx(u[..., 0, :, :]) + self.dy(u[..., 1, :, :]) + elif self.dim == 3: + return self.dx(u[..., 0, :, :, :]) + self.dy(u[..., 1, :, :, :]) + self.dz(u[..., 2, :, :, :]) + + def curl(self, u): + """Compute the curl ∇×u (for vector fields, 2D/3D only).""" + # Check input dimensions + if self.dim == 1: + raise ValueError("curl not defined for 1D") + elif self.dim == 2 and u.shape[-3] != 2: + raise ValueError("For 2D, input must have 2 components in the vector dimension") + elif self.dim == 3 and u.shape[-4] != 3: + raise ValueError("For 3D, input must have 3 components in the vector dimension") + if self.dim == 2: + # In 2D: ∂v/∂x - ∂u/∂y where u = (u,v) is a 2D vector field + return self.dx(u[..., 1, :, :]) - self.dy(u[..., 0, :, :]) + elif self.dim == 3: + # In 3D, ∇×u = (∂w/∂y - ∂v/∂z, ∂u/∂z - ∂w/∂x, ∂v/∂x - ∂u/∂y) where u = (u,v,w) is a 3D vector field + curl_x = self.dy(u[..., 2, :, :, :]) - self.dz(u[..., 1, :, :, :]) # ∂w/∂y - ∂v/∂z + curl_y = self.dz(u[..., 0, :, :, :]) - self.dx(u[..., 2, :, :, :]) # ∂u/∂z - ∂w/∂x + curl_z = self.dx(u[..., 1, :, :, :]) - self.dy(u[..., 0, :, :, :]) # ∂v/∂x - ∂u/∂y + + # Stack the components into a 3D vector field + return torch.stack([curl_x, curl_y, curl_z], dim=-4) + + def _compute_multiple_derivatives_1d(self, u, orders): + """1D multiple derivatives computation.""" + if u is None: + raise ValueError("Input tensor u is None") + + L_x = self.L + nx = u.shape[-1] + u_clone = u.clone() + + # Apply Fourier continuation if specified + if self.use_fc and self.FC is not None: + FC = self.FC.to(u_clone.device) + u_clone = FC(u_clone, dim=1) + L_x *= (nx + self.fc_n_additional_pts) / nx + + # Update grid parameters after extension + nx = u_clone.shape[-1] + dx = L_x / nx + + # FFT + u_h = torch.fft.rfft(u_clone, dim=-1) + + # Frequency array + k_x = torch.fft.rfftfreq(nx, d=dx, device=u_h.device) * (2 * torch.pi) + + # Apply low-pass filter if specified + if self.low_pass_filter_ratio is not None: + cutoff = int(u_h.shape[-1] * self.low_pass_filter_ratio) + u_h[..., cutoff:] = 0 + + # Compute derivatives + results = [] + for order in orders: + derivative_u_h = ((1j * k_x) ** order) * u_h + results.append(derivative_u_h) + + derivatives_ft = torch.stack(results, dim=0) + derivatives_real = torch.fft.irfft(derivatives_ft, dim=-1, n=nx) + + # Crop result if Fourier continuation was used + if self.use_fc and self.FC is not None: + FC = self.FC.to(derivatives_real.device) + derivatives_real = FC.restrict(derivatives_real, dim=1) + + return [derivatives_real[i] for i in range(len(orders))] + + def _dx_1d(self, u, order): + """1D derivative with respect to x.""" + derivatives = self._compute_multiple_derivatives_1d(u, [order]) + return derivatives[0] + + def _compute_multiple_derivatives_2d(self, u, derivatives): + """2D multiple derivatives computation.""" + if u is None: + raise ValueError("Input tensor u is None") + + L_x, L_y = self.L[0], self.L[1] + nx, ny = u.shape[-2], u.shape[-1] + u_clone = u.clone() + + # Apply Fourier continuation if specified + if self.use_fc and self.FC is not None: + FC = self.FC.to(u_clone.device) + u_clone = FC(u_clone, dim=2) + L_x *= (nx + self.fc_n_additional_pts) / nx + L_y *= (ny + self.fc_n_additional_pts) / ny + + # Update grid parameters after extension + nx, ny = u_clone.shape[-2], u_clone.shape[-1] + dx, dy = L_x / nx, L_y / ny + + # 2D FFT + u_h = torch.fft.fft2(u_clone, dim=(-2, -1)) + + # Frequency arrays + k_x = torch.fft.fftfreq(nx, d=dx, device=u_h.device) * (2 * torch.pi) + k_y = torch.fft.fftfreq(ny, d=dy, device=u_h.device) * (2 * torch.pi) + + # Create frequency meshgrid + KX, KY = torch.meshgrid(k_x, k_y, indexing="ij") + + # Apply low-pass filter if specified + if self.low_pass_filter_ratio is not None: + cutoff_x = int(nx * self.low_pass_filter_ratio) + cutoff_y = int(ny * self.low_pass_filter_ratio) + u_h[..., cutoff_y:, :] = 0 + u_h[..., :, cutoff_x:] = 0 + + # Compute derivatives + results = [] + for order_x, order_y in derivatives: + # Expand meshgrid tensors for proper broadcasting + KX_expanded = KX.expand(u_h.shape) + KY_expanded = KY.expand(u_h.shape) + + derivative_u_h = ((1j * KX_expanded) ** order_x) * ((1j * KY_expanded) ** order_y) * u_h + results.append(derivative_u_h) + + derivatives_ft = torch.stack(results, dim=0) + derivatives_real = torch.fft.ifft2(derivatives_ft, dim=(-2, -1)).real + + # Crop result if Fourier continuation was used + if self.use_fc and self.FC is not None: + FC = self.FC.to(derivatives_real.device) + derivatives_real = FC.restrict(derivatives_real, dim=2) + + return [derivatives_real[i] for i in range(len(derivatives))] + + def _dx_2d(self, u, order): + """2D derivative with respect to x.""" + derivatives = self._compute_multiple_derivatives_2d(u, [(order, 0)]) + return derivatives[0] + + def _dy_2d(self, u, order): + """2D derivative with respect to y.""" + derivatives = self._compute_multiple_derivatives_2d(u, [(0, order)]) + return derivatives[0] + + def _compute_multiple_derivatives_3d(self, u, derivatives): + """3D multiple derivatives computation.""" + if u is None: + raise ValueError("Input tensor u is None") + + L_x, L_y, L_z = self.L[0], self.L[1], self.L[2] + nx, ny, nz = u.shape[-3], u.shape[-2], u.shape[-1] + u_clone = u.clone() + + # Apply Fourier continuation if specified + if self.use_fc and self.FC is not None: + FC = self.FC.to(u_clone.device) + u_clone = FC(u_clone, dim=3) + L_x *= (nx + self.fc_n_additional_pts) / nx + L_y *= (ny + self.fc_n_additional_pts) / ny + L_z *= (nz + self.fc_n_additional_pts) / nz + + # Update grid parameters after extension + nx, ny, nz = u_clone.shape[-3], u_clone.shape[-2], u_clone.shape[-1] + dx, dy, dz = L_x / nx, L_y / ny, L_z / nz + + # 3D FFT + u_h = torch.fft.fftn(u_clone, dim=(-3, -2, -1)) + + # Frequency arrays + k_x = torch.fft.fftfreq(nx, d=dx, device=u_h.device) * (2 * torch.pi) + k_y = torch.fft.fftfreq(ny, d=dy, device=u_h.device) * (2 * torch.pi) + k_z = torch.fft.fftfreq(nz, d=dz, device=u_h.device) * (2 * torch.pi) + + # Create frequency meshgrid + KX, KY, KZ = torch.meshgrid(k_x, k_y, k_z, indexing="ij") + + # Apply low-pass filter if specified + if self.low_pass_filter_ratio is not None: + cutoff_x = int(nx * self.low_pass_filter_ratio) + cutoff_y = int(ny * self.low_pass_filter_ratio) + cutoff_z = int(nz * self.low_pass_filter_ratio) + u_h[..., cutoff_y:, :, :] = 0 + u_h[..., :, cutoff_x:, :] = 0 + u_h[..., :, :, cutoff_z:] = 0 + + # Compute derivatives + results = [] + for order_x, order_y, order_z in derivatives: + # Expand meshgrid tensors for proper broadcasting + KX_expanded = KX.expand(u_h.shape) + KY_expanded = KY.expand(u_h.shape) + KZ_expanded = KZ.expand(u_h.shape) + + derivative_u_h = ((1j * KX_expanded) ** order_x) * ((1j * KY_expanded) ** order_y) * ((1j * KZ_expanded) ** order_z) * u_h + results.append(derivative_u_h) + + derivatives_ft = torch.stack(results, dim=0) + derivatives_real = torch.fft.ifftn(derivatives_ft, dim=(-3, -2, -1)).real + + # Crop result if Fourier continuation was used + if self.use_fc and self.FC is not None: + FC = self.FC.to(derivatives_real.device) + derivatives_real = FC.restrict(derivatives_real, dim=3) + + return [derivatives_real[i] for i in range(len(derivatives))] + + def _dx_3d(self, u, order): + """3D derivative with respect to x.""" + derivatives = self._compute_multiple_derivatives_3d(u, [(order, 0, 0)]) + return derivatives[0] + + def _dy_3d(self, u, order): + """3D derivative with respect to y.""" + derivatives = self._compute_multiple_derivatives_3d(u, [(0, order, 0)]) + return derivatives[0] + + def _dz_3d(self, u, order): + """3D derivative with respect to z.""" + derivatives = self._compute_multiple_derivatives_3d(u, [(0, 0, order)]) + return derivatives[0] diff --git a/sources/neuraloperator/neuralop/losses/equation_losses.py b/sources/neuraloperator/neuralop/losses/equation_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..500b36a23de62574d53b1ae09f78e05a8afde11d --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/equation_losses.py @@ -0,0 +1,285 @@ +import torch +import torch.nn.functional as F + +from torch.autograd import grad + +from .differentiation import FiniteDiff + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +class BurgersEqnLoss(object): + """ + Computes loss for Burgers' equation. + """ + + def __init__(self, visc=0.01, method="fdm", loss=F.mse_loss, domain_length=1.0): + super().__init__() + self.visc = visc + self.method = method + self.loss = loss + self.domain_length = domain_length + if not isinstance(self.domain_length, (tuple, list)): + self.domain_length = [self.domain_length] * 2 + + def fdm(self, u): + # remove extra channel dimensions + u = u.squeeze(1) + + # shapes + _, nt, nx = u.shape + + # we assume that the input is given on a regular grid + dt = self.domain_length[0] / (nt - 1) + dx = self.domain_length[1] / nx + + # Get derivatives, du/dt and du/dx and d^2u/dxx + fd2d = FiniteDiff(dim=2, h=(dt, dx), periodic_in_x=False, periodic_in_y=False) + dudt, dudx = fd2d.dx(u), fd2d.dy(u) + dudxx = fd2d.dy(u, order=2) + + # right hand side + right_hand_side = -dudx * u + self.visc * dudxx + + # compute the loss of the left and right hand sides of Burgers' equation + return self.loss(dudt, right_hand_side) + + def __call__(self, y_pred, **kwargs): + if kwargs: + warnings.warn( + f"BurgersLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + if self.method == "fdm": + return self.fdm(u=y_pred) + raise NotImplementedError() + + +class ICLoss(object): + """ + Computes loss for initial value problems. + + Extracts the initial condition and computes the loss between predicted + and true initial conditions for all channels. + + Expected input shape: (batch_size, channels, time_dim, *spatial_dims) + """ + + def __init__(self, loss=F.mse_loss): + super().__init__() + self.loss = loss + + def __call__(self, y_pred, y, **kwargs): + """Expected input shape: (batch_size, channels, time_dim, *spatial_dims)""" + if kwargs: + warnings.warn( + f"ICLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + return self.loss(y_pred[:, :, 0], y[:, :, 0]) + + +class PoissonInteriorLoss(object): + """ + PoissonInteriorLoss computes the loss on the interior points of model outputs + according to Poisson's equation in 2d: ∇·((1 + 0.1u^2)∇u(x)) = f(x) + + Parameters + ---------- + method : Literal['autograd'] only (for now) + How to compute derivatives for equation loss. + + * If 'autograd', differentiates using torch.autograd.grad. This can be used with outputs with any irregular + point cloud structure. + loss: Callable, optional + Base loss class to compute distances between expected and true values, + by default torch.nn.functional.mse_loss + """ + + def __init__(self, method="autograd", loss=F.mse_loss): + super().__init__() + self.method = method + self.loss = loss + + def autograd(self, u, output_queries, output_source_terms_domain, num_boundary, **kwargs): + """ + Compute loss between the left-hand side and right-hand side of + nonlinear Poisson's equation: ∇·((1 + 0.1u^2)∇u(x)) = f(x) + + u: torch.Tensor | dict + output of the model. + + * If output_queries is passed to the model as a dict, this will be a + dict of outputs provided over the points at each value in output_queries. + Each tensor will be shape (batch, n_points, 2). + + * If a tensor, u will be of shape (batch, num_boundary + num_interior, 2), where + u[:, 0:num_boundary, :] are boundary points and u[:, num_boundary:, :] are interior points. + output_queries: torch.Tensor | dict + output queries provided to the model. If provided as a dict of tensors, + u will also be returned as a dict keyed the same way. If provided as a tensor, + u will be a tensor of the same shape except for number of channels. If a tensor, + output_queries[:, 0:num_boundary, :] are boundary points and output_queries[:, num_boundary:, :] + are interior points. + output_source_terms_domain: torch.Tensor + source terms f(x) defined for this specific instance of Poisson's equation. + + """ + + if isinstance(output_queries, dict): + output_queries_domain = output_queries["domain"] + u_prime = grad( + outputs=u.sum(), + inputs=output_queries_domain, + create_graph=True, + retain_graph=True, + )[0] + else: + # We only care about U defined over the interior. Grab it now if the entire U is passed. + output_queries_domain = None + u = u[:, num_boundary:, ...] + u_prime = grad( + outputs=u.sum(), + inputs=output_queries, + create_graph=True, + retain_graph=True, + )[0][:, num_boundary:, :] + + u_x = u_prime[:, :, 0] + u_y = u_prime[:, :, 1] + + # compute second derivatives + if output_queries_domain is not None: + u_xx = grad( + outputs=u_x.sum(), + inputs=output_queries_domain, + create_graph=True, + retain_graph=True, + )[0][:, :, 0] + u_yy = grad( + outputs=u_y.sum(), + inputs=output_queries_domain, + create_graph=True, + retain_graph=True, + )[0][:, :, 1] + else: + u_xx = grad( + outputs=u_x.sum(), + inputs=output_queries, + create_graph=True, + retain_graph=True, + )[0][:, num_boundary:, 0] + u_yy = grad( + outputs=u_y.sum(), + inputs=output_queries, + create_graph=True, + retain_graph=True, + )[0][:, num_boundary:, 1] + u_xx = u_xx.squeeze(0) + u_yy = u_yy.squeeze(0) + u_prime = u_prime.squeeze(0) + u = u.squeeze([0, -1]) + + # compute LHS of the Poisson equation + u_sq = torch.pow(u, 2) + laplacian = u_xx + u_yy + norm_grad_u = torch.pow(u_prime, 2).sum(dim=-1) + + assert u_sq.shape == u_xx.shape == u_yy.shape == norm_grad_u.shape + + left_hand_side = laplacian + laplacian * 0.1 * u_sq + 0.2 * u * norm_grad_u + output_source_terms_domain = output_source_terms_domain.squeeze(0) + + assert left_hand_side.shape == output_source_terms_domain.shape + loss = self.loss(left_hand_side, output_source_terms_domain) + + assert not u_prime.isnan().any() + assert not u_yy.isnan().any() + assert not u_xx.isnan().any() + del u_xx, u_yy, u_x, u_y, left_hand_side + + return loss + + def __call__(self, y_pred, **kwargs): + if kwargs: + warnings.warn( + f"PoissonInteriorLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + if self.method == "autograd": + return self.autograd(u=y_pred, **kwargs) + elif self.method == "finite_difference": + raise NotImplementedError() + else: + raise NotImplementedError() + + +class PoissonBoundaryLoss(object): + def __init__(self, loss=F.mse_loss): + super().__init__() + self.loss = loss + self.counter = 0 + + def __call__(self, y_pred, num_boundary, out_sub_level, y, output_queries, **kwargs): + if kwargs: + warnings.warn( + f"PoissonBoundaryLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + num_boundary = int(num_boundary.item() * out_sub_level) + boundary_pred = y_pred.squeeze(0).squeeze(-1)[:num_boundary] + y_bound = y.squeeze(0).squeeze(-1)[:num_boundary] + + assert boundary_pred.shape == y_bound.shape + return self.loss(boundary_pred, y_bound) + + +class PoissonEqnLoss(object): + """PoissonEqnLoss computes a weighted sum of equation loss computed on the interior points of a model's output + and a boundary loss computed on the boundary points. + + Parameters + ---------- + boundary_weight : float + weight by which to multiply boundary loss + interior_weight : float + weight by which to multiply interior loss + diff_method : Literal['autograd', 'finite_difference'], optional + method to use to compute derivatives, by default 'autograd' + base_loss : Callable, optional + base loss class to use inside equation and boundary loss, by default F.mse_loss + """ + def __init__(self, boundary_weight, interior_weight, diff_method: str="autograd", base_loss=F.mse_loss): + super().__init__() + self.boundary_weight = boundary_weight + self.boundary_loss = PoissonBoundaryLoss(loss=base_loss) + + self.interior_weight = interior_weight + self.interior_loss = PoissonInteriorLoss(method=diff_method, loss=base_loss) + + def __call__(self, out, y, **kwargs): + if kwargs: + warnings.warn( + f"PoissonEqnLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + if isinstance(out, dict): + interior_loss = self.interior_weight * self.interior_loss(out['domain'], **kwargs) + bc_loss = self.boundary_weight * self.boundary_loss(out['boundary'], y=y['boundary'], **kwargs) + else: + interior_loss = self.interior_weight * self.interior_loss(out, **kwargs) + bc_loss = self.boundary_weight * self.boundary_loss(out, y=y, **kwargs) + return interior_loss + bc_loss diff --git a/sources/neuraloperator/neuralop/losses/meta_losses.py b/sources/neuraloperator/neuralop/losses/meta_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b0a319c8828e3592f8456af1d89da7667c13ee --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/meta_losses.py @@ -0,0 +1,447 @@ +import torch +import logging +from torch import nn +from typing import Dict, List, Optional, Callable + +logger = logging.getLogger(__name__) + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +class FieldwiseAggregatorLoss(object): + """ + AggregatorLoss takes a dict of losses, keyed to correspond + to different properties or fields of a model's output. + It then returns an aggregate of all losses weighted by + an optional weight dict. + + params: + losses: dict[Loss] + a dictionary of loss functions, each of which + takes in some truth_field and pred_field + mappings: dict[tuple(Slice)] + a dictionary of mapping indices corresponding to + the output fields above. keyed 'field': indices, + so that pred[indices] contains output for specified field + logging: bool + whether to track error for each output field of the model separately + + """ + + def __init__(self, losses: dict, mappings: dict, logging=False): + # AggregatorLoss should only be instantiated with more than one loss. + assert mappings.keys() == losses.keys(), 'Mappings and losses must use the same keying' + + self.losses = losses + self.mappings = mappings + self.logging = logging + + def __call__(self, pred: torch.Tensor, truth: torch.Tensor, **kwargs): + """ + Calculate aggregate loss across model inputs and outputs. + + parameters + ---------- + pred: tensor + contains predictions output by a model, indexed for various output fields + y: tensor + contains ground truth. Indexed the same way as pred. + **kwargs: dict + bonus args to pass to each fieldwise loss + """ + if kwargs: + warnings.warn( + f"FieldwiseLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + loss = 0.0 + if self.logging: + loss_record = {} + # sum losses over output fields + for field, indices in self.mappings.items(): + pred_field = pred[indices].view(-1, 1) + truth_field = truth[indices] + field_loss = self.losses[field](pred_field, truth_field, **kwargs) + loss += field_loss + if self.logging: + loss_record["field"] = field_loss + loss = (1.0 / len(self.mappings)) * loss + + if self.logging: + return loss, field_loss + else: + return loss + + +class WeightedSumLoss(object): + """ + Computes an average or weighted sum of given losses. + """ + + def __init__(self, losses, weights=None): + super().__init__() + if weights is None: + weights = [1.0 / len(losses)] * len(losses) + if not len(weights) == len(losses): + raise ValueError("Each loss must have a weight.") + self.losses = list(zip(losses, weights)) + + def __call__(self, *args, **kwargs): + weighted_loss = 0.0 + for loss, weight in self.losses: + weighted_loss += weight * loss(*args, **kwargs) + return weighted_loss + + def __str__(self): + description = "Combined loss: " + for loss, weight in self.losses: + description += f"{loss} (weight: {weight}) " + return description + + +# Below are the implementations of the meta-losses from NVIDIA PhysicsNeMo (with almost no changes). +# These are more convenient to use when training without the Trainer/PINOTrainer class. +# NVIDIA PhysicsNeMo: An open-source framework for physics-based deep learning in science and engineering +# https://github.com/NVIDIA/physicsnemo + + +class Aggregator(nn.Module): + """ + Base class for loss aggregators that dynamically balance multiple loss components. + + This class provides the foundation for adaptive loss weighting schemes that can + automatically adjust the importance of different loss terms during training. + + Parameters + ---------- + params : List[torch.Tensor] + List of model parameters used to determine the device for tensor operations. + All parameters should be on the same device. + num_losses : int + Number of loss components that will be aggregated. This determines the + size of internal buffers for tracking loss history. + weights : Optional[Dict[str, float]], optional + Optional static weights for each loss component. If provided, these weights + will be applied to the corresponding losses before aggregation. + If a loss key is not present in the weights dict, a default weight of 1.0 + will be used, by default None + + Notes + ----- + This is an abstract base class that should be inherited by specific loss + aggregation algorithms like SoftAdapt or ReLoBRaLo. The forward method + should be implemented by subclasses to define the specific aggregation strategy. + + The device is automatically determined from the first parameter in the params list. + All parameters should be on the same device to avoid device mismatch errors. + """ + + def __init__(self, params, num_losses, weights): + super().__init__() + self.params: List[torch.Tensor] = list(params) + self.num_losses: int = num_losses + self.weights: Optional[Dict[str, float]] = weights + self.device: torch.device + self.device = list(set(p.device for p in self.params))[0] + self.init_loss: torch.Tensor = torch.tensor(0.0, device=self.device) + + def weigh_losses_initialize( + weights: Optional[Dict[str, float]] + ) -> Callable[ + [Dict[str, torch.Tensor], Optional[Dict[str, float]]], + Dict[str, torch.Tensor], + ]: + if weights is None: + + def weigh_losses( + losses: Dict[str, torch.Tensor], weights: None + ) -> Dict[str, torch.Tensor]: + return losses + + else: + + def weigh_losses( + losses: Dict[str, torch.Tensor], weights: Dict[str, float] + ) -> Dict[str, torch.Tensor]: + for key in losses.keys(): + if key not in weights.keys(): + weights.update({key: 1.0}) + losses = {key: weights[key] * losses[key] for key in losses.keys()} + return losses + + return weigh_losses + + self.weigh_losses = weigh_losses_initialize(self.weights) + + +class SoftAdapt(Aggregator): + """ + SoftAdapt algorithm for adaptive loss weighting and aggregation. + + SoftAdapt automatically adjusts the weights of multiple loss components based on + their relative magnitudes and rates of change. The algorithm uses exponential + weighting to give higher importance to losses that are not decreasing or are + relatively larger, based on their ratio to previous losses, helping to balance + the training of different objectives. + + Reference: "Heydari, A.A., Thompson, C.A. and Mehmood, A., 2019. + Softadapt: Techniques for adaptive loss weighting of neural networks with multi-part loss functions. + arXiv preprint arXiv: 1912.12355." + + Parameters + ---------- + params : List[torch.Tensor] + List of model parameters used to determine the device for tensor operations. + num_losses : int + Number of loss components that will be aggregated. + eps : float, optional + Small constant added to denominators to prevent division by zero. + Should be positive and small (e.g., 1e-8), by default 1e-8 + weights : Optional[Dict[str, float]], optional + Optional static weights for each loss component, by default None + + Notes + ----- + At step 0, all losses are simply summed with equal weights. For subsequent steps, + the algorithm computes adaptive weights based on the ratio of current to previous + loss values, with higher weights given to losses that are increasing or have + higher relative magnitudes. + + Warnings + -------- + The algorithm assumes that all loss components should be minimized. If some + losses should be maximized, they should be negated before passing to SoftAdapt. + """ + + def __init__(self, params, num_losses, eps=1e-8, weights=None): + super().__init__(params, num_losses, weights) + self.eps: float = eps + self.register_buffer( + "prev_losses", torch.zeros(self.num_losses, device=self.device) + ) + + def forward(self, losses: Dict[str, torch.Tensor], step: int) -> torch.Tensor: + """ + Weights and aggregates the losses using the original variant of the SoftAdapt algorithm. + + Parameters + ---------- + losses : Dict[str, torch.Tensor] + Dictionary of loss components to be aggregated. + For instance, the keys could be 'data_loss' and 'physics_loss'. + step : int + Current optimization step. Used to determine whether to initialize + the algorithm (step 0) or apply adaptive weighting (step > 0). + + Returns + ------- + loss : torch.Tensor + The aggregated loss value. + lmbda : torch.Tensor + The computed adaptive weights for each loss component. + + Notes + ----- + At step 0, all losses are summed with equal weights. + For subsequent steps, the algorithm computes adaptive weights based on + the ratio of current to previous loss values. + """ + + # weigh losses + losses = self.weigh_losses(losses, self.weights) + + # Initialize loss + loss: torch.Tensor = torch.zeros_like(self.init_loss) + + # Aggregate losses by summation at step 0 + if step == 0: + for i, key in enumerate(losses.keys()): + loss += losses[key] + self.prev_losses[i] = losses[key].clone().detach() + lmbda = torch.ones_like(self.prev_losses) + + # Aggregate losses using SoftAdapt for step > 0 + else: + lmbda: torch.Tensor = torch.ones_like(self.prev_losses) + lmbda_sum: torch.Tensor = torch.zeros_like(self.init_loss) + losses_stacked: torch.Tensor = torch.stack(list(losses.values())) + normalizer: torch.Tensor = (losses_stacked / self.prev_losses).max() + for i, key in enumerate(losses.keys()): + with torch.no_grad(): + lmbda[i] = torch.exp( + losses[key] / (self.prev_losses[i] + self.eps) - normalizer + ) + lmbda_sum += lmbda[i] + loss += lmbda[i].clone() * losses[key] + self.prev_losses[i] = losses[key].clone().detach() + loss *= self.num_losses / (lmbda_sum + self.eps) + + return loss, lmbda + + +class Relobralo(Aggregator): + """ + Relative Loss Balancing with Random Lookback (ReLoBRaLo) algorithm for adaptive loss weighting. + + ReLoBRaLo combines relative loss balancing with random lookback to provide more + stable and effective multi-objective optimization. The algorithm uses both + initial loss values and previous loss values to compute adaptive weights, + with a random lookback mechanism. This random lookback mechanism introduces + stochasticity in the weighting by sometimes reverting to initial loss values, + encouraging robustness across loss scales over time. + + Reference: "Bischof, R. and Kraus, M., 2021. + Multi-Objective Loss Balancing for Physics-Informed Deep Learning. + arXiv preprint arXiv:2110.09813." + + Parameters + ---------- + params : List[torch.Tensor] + List of model parameters used to determine the device for tensor operations. + num_losses : int + Number of loss components that will be aggregated. + alpha : float, optional + Controls the smoothing factor for the exponential moving average of the adaptive weights. + High alpha gives more inertia to past weights (more stability). + Low alpha allows faster adaptation. + By default 0.95 + beta : float, optional + Probability for the random lookback mechanism, i.e. probability of sampling from + initial loss values instead of previous loss values during adaptive weight computation. + By default 0.99 + tau : float, optional + Temperature parameter that controls the sharpness of the exponential + weighting. Higher values make the weights more uniform, by default 1.0 + eps : float, optional + Small constant added to denominators to prevent division by zero. + Should be positive and small (e.g., 1e-8), by default 1e-8. + weights : Optional[Dict[str, float]], optional + Optional static weights for each loss component, by default None + + Notes + ----- + At step 0, all losses are simply summed with equal weights, and both initial + and previous loss buffers are initialized with the current loss values. + + The random lookback mechanism (controlled by beta) helps the algorithm escape + local minima by occasionally using initial loss values instead of recent ones. + This is particularly useful in physics-informed neural networks where different + loss components may have different convergence characteristics. + + The temperature parameter tau controls how aggressive the weighting is. Lower + values make the algorithm more selective in which losses to prioritize, + while higher values make the weights more uniform. + + Warnings + -------- + The algorithm assumes that all loss components should be minimized. If some + losses should be maximized, they should be negated before passing to ReLoBRaLo. + + The random component means that results may vary between runs, + due to the Bernoulli sampling in the weight computation. + """ + + def __init__( + self, params, num_losses, alpha=0.95, beta=0.99, tau=1.0, eps=1e-8, weights=None + ): + super().__init__(params, num_losses, weights) + self.alpha: float = alpha + self.beta: float = beta + self.tau: float = tau + self.eps: float = eps + self.register_buffer( + "init_losses", torch.zeros(self.num_losses, device=self.device) + ) + self.register_buffer( + "prev_losses", torch.zeros(self.num_losses, device=self.device) + ) + self.register_buffer( + "lmbda_ema", torch.ones(self.num_losses, device=self.device) + ) + + def forward(self, losses: Dict[str, torch.Tensor], step: int) -> torch.Tensor: + """ + Weights and aggregates the losses using the ReLoBRaLo algorithm. + + Parameters + ---------- + losses : Dict[str, torch.Tensor] + Dictionary of loss components to be aggregated. + For instance, the keys could be 'data_loss' and 'physics_loss'. + step : int + Current optimization step. Used to determine whether to initialize + the algorithm (step 0) or apply adaptive weighting (step > 0). + + Returns + ------- + loss : torch.Tensor + The aggregated loss value. + lmbda_ema : torch.Tensor + The exponential moving average of adaptive weights for each loss component. + + Notes + ----- + At step 0, all losses are summed with equal weights, and both initial + and previous loss buffers are initialized with the current loss values. + + For subsequent steps, the algorithm computes weights using both initial + and previous loss values, with a random component that helps escape + local minima. The final weights are computed as an exponential moving average. + """ + + # weigh losses + losses = self.weigh_losses(losses, self.weights) + + # Initialize loss + loss: torch.Tensor = torch.zeros_like(self.init_loss) + + # Aggregate losses by summation at step 0 + if step == 0: + for i, key in enumerate(losses.keys()): + loss += losses[key] + self.init_losses[i] = losses[key].clone().detach() + self.prev_losses[i] = losses[key].clone().detach() + + # Aggregate losses using ReLoBRaLo for step > 0 + else: + losses_stacked: torch.Tensor = torch.stack(list(losses.values())) + normalizer_prev: torch.Tensor = ( + losses_stacked / (self.tau * self.prev_losses) + ).max() + normalizer_init: torch.Tensor = ( + losses_stacked / (self.tau * self.init_losses) + ).max() + + # define a Bernoulli-sampled variable that determines whether to use initial + # or previous loss values in computing the adaptive weights + rho: torch.Tensor = torch.bernoulli(torch.tensor(self.beta)) + + with torch.no_grad(): + lmbda_prev: torch.Tensor = torch.exp( + losses_stacked / (self.tau * self.prev_losses + self.eps) + - normalizer_prev + ) + lmbda_init: torch.Tensor = torch.exp( + losses_stacked / (self.tau * self.init_losses + self.eps) + - normalizer_init + ) + lmbda_prev *= self.num_losses / (lmbda_prev.sum() + self.eps) + lmbda_init *= self.num_losses / (lmbda_init.sum() + self.eps) + + # Compute the exponential moving average of weights and aggregate losses + for i, key in enumerate(losses.keys()): + with torch.no_grad(): + self.lmbda_ema[i] = self.alpha * ( + rho * self.lmbda_ema[i].clone() + (1.0 - rho) * lmbda_init[i] + ) + self.lmbda_ema[i] += (1.0 - self.alpha) * lmbda_prev[i] + loss += self.lmbda_ema[i].clone() * losses[key] + self.prev_losses[i] = losses[key].clone().detach() + + return loss, self.lmbda_ema diff --git a/sources/neuraloperator/neuralop/losses/tests/__init__.py b/sources/neuraloperator/neuralop/losses/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/losses/tests/test_losses.py b/sources/neuraloperator/neuralop/losses/tests/test_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc7905de48db01ae84cb2ab3d5d97f32287fe5c --- /dev/null +++ b/sources/neuraloperator/neuralop/losses/tests/test_losses.py @@ -0,0 +1,496 @@ +import math +import torch +import pytest +from torch.testing import assert_close + +from ..data_losses import LpLoss, H1Loss, HdivLoss +from ..differentiation import non_uniform_fd, FiniteDiff, FourierDiff +from neuralop.layers.embeddings import regular_grid_nd + + +def test_lploss(): + l2_2d_mean = LpLoss(d=2, p=2, reduction="mean", measure=1.0) + l2_2d_sum = LpLoss(d=2, p=2, reduction="sum", measure=1.0) + x = torch.randn(10, 1, 4, 4) + + abs_0 = l2_2d_mean.abs(x, x) + assert abs_0.item() == 0.0 + + zeros = torch.zeros_like(x) + ones = torch.ones_like(x) + + # L2 w/out normalizing constant + # sum of items in each element in ones is 16 + # norm is 4 + mean_abs_l2_err = l2_2d_mean.abs(zeros, ones) + assert mean_abs_l2_err.item() == 1.0 + + sum_abs_l2_err = l2_2d_sum.abs(zeros, ones) + assert sum_abs_l2_err.item() == 10.0 + + # Test quadrature weights: for spatial dims, each weight should + # be 1/the corresponding size in x, so that after applying weights, + # lploss constitutes an average over spatial dims. + d = 2 + default_quad_weights = l2_2d_mean.uniform_quadrature(x) + assert default_quad_weights[-d:] == [1 / s for s in x.shape[-d:]] + + # Sanity check: ensure that both sum and mean reduction sum-reduce over spatial dims + x = torch.arange(1, 5) * torch.ones(4, 4) + flipped_x = x.T.unsqueeze(0).unsqueeze(0) + x = x.unsqueeze(0).unsqueeze(0) + + zeros = torch.zeros_like(x) + + # batch and channel size of 1. squared diff should be 120, avg over spatial dims 7.5 + mean_err = l2_2d_mean.abs(flipped_x, zeros) + sum_err = l2_2d_sum.abs(x, zeros) + + assert mean_err == sum_err + assert_close(mean_err, torch.sqrt(torch.tensor(7.5))) + + +def test_h1loss(): + h1 = H1Loss(d=2, reduction="mean") + x = torch.randn(10, 4, 4) + + abs_0 = h1.abs(x, x) + assert abs_0.item() == 0.0 + + zeros = torch.zeros_like(x) + ones = torch.ones_like(x) + + # H1 w/o normalizing constant, + # finite-difference derivatives of both sides are zero + # sum of items in each element in ones is 16 + # norm is 1 averaged in space + mean_abs_h1 = h1.abs(zeros, ones) + assert mean_abs_h1.item() == 1.0 + + +def test_hdivloss(): + hdiv = HdivLoss(d=2, reduction="mean") + x = torch.randn(10, 4, 4) + + abs_0 = hdiv.abs(x, x) + assert abs_0.item() == 0.0 + + zeros = torch.zeros_like(x) + ones = torch.ones_like(x) + + # Hdiv without normalizing constant, + # finite-difference derivatives of both sides are zero + # sum of items in each element in ones is 16 + # norm is 1 averaged in space + mean_abs_hdiv = hdiv.abs(zeros, ones) + assert mean_abs_hdiv.item() == 1.0 + + +@pytest.mark.parametrize("dim", [1, 2]) +def test_nonuniform_fd(dim: int): + if dim == 1: + x = torch.sort(torch.rand(256))[0].unsqueeze(1) + f = torch.exp(3 * x) + torch.sin(10 * x) - x**2 + df_ref = (3 * torch.exp(3 * x) + 10 * torch.cos(10 * x) - 2 * x).squeeze() + df_dx = non_uniform_fd( + x, + f.squeeze(), + num_neighbors=3, + derivative_indices=[0], + regularize_lstsq=False, + )[0] + + l2 = LpLoss(d=1, p=2, reduction="mean", measure=1.0) + assert l2.rel(df_ref, df_dx).item() < 5e-2 + + # # Plot to check visually + # import matplotlib.pyplot as plt + # plt.figure(figsize=(10,5)) + # plt.plot(x.detach().numpy().squeeze(), df_ref.detach().numpy(), 'r', linewidth=0.8, label='Reference') + # plt.plot(x.detach().numpy(), df_dx.detach().numpy(), 'b', linewidth=0.8, label='FD') + # plt.legend() + # plt.xlabel(r'$x$') + # plt.ylabel(r'$df/dx$') + # plt.savefig('non_uniform_fd_1D.pdf') + + if dim == 2: + num_points = 128 + x = torch.linspace(-1, 1, num_points, dtype=torch.float64) + y = torch.linspace(-1, 1, num_points, dtype=torch.float64) + X, Y = torch.meshgrid(x, y, indexing="ij") + points = torch.stack([X.flatten(), Y.flatten()], dim=1) + f = torch.exp(Y) + 0.1 * torch.sin(10 * X) - (X**2) * (Y**2) + dfdx_ref = torch.cos(10 * X) - 2 * X * (Y**2) + dfdy_ref = torch.exp(Y) - 2 * (X**2) * Y + df = non_uniform_fd( + points, + f.flatten(), + num_neighbors=5, + derivative_indices=[0, 1], + regularize_lstsq=True, + ) + df_dx = df[0].reshape(num_points, num_points) + df_dy = df[1].reshape(num_points, num_points) + + l2 = LpLoss(d=2, p=2, reduction="mean", measure=1.0) + assert l2.rel(dfdx_ref, df_dx).item() < 5e-2 + assert l2.rel(dfdy_ref, df_dy).item() < 5e-2 + + # # Plot to check visually + # import matplotlib.pyplot as plt + # plt.figure(figsize=(7, 7)) + # plt.subplot(2, 2, 1) + # img1 = plt.imshow(df_dx.detach().numpy()) + # plt.colorbar(img1, shrink=0.75) + # plt.title(r'$df/dx$') + # plt.xticks([]) + # plt.yticks([]) + # plt.subplot(2, 2, 2) + # img2 = plt.imshow(dfdx_ref.detach().numpy()) + # plt.colorbar(img2, shrink=0.75) + # plt.title(r'$df/dx$_ref') + # plt.xticks([]) + # plt.yticks([]) + # plt.subplot(2, 2, 3) + # img3 = plt.imshow(df_dy.detach().numpy()) + # plt.colorbar(img3, shrink=0.75) + # plt.title(r'$df/dy$') + # plt.xticks([]) + # plt.yticks([]) + # plt.subplot(2, 2, 4) + # img4 = plt.imshow(dfdy_ref.detach().numpy().reshape(num_points, num_points)) + # plt.colorbar(img4, shrink=0.75) + # plt.title(r'$df/dy$_ref') + # plt.xticks([]) + # plt.yticks([]) + # plt.tight_layout() + # plt.savefig('non_uniform_fd_2D.pdf') + + +@pytest.mark.parametrize("periodic_x", [True, False]) +def test_finite_diff_1d(periodic_x): + """Test the FiniteDiff class with various boundary conditions for 1D.""" + + # Create a 1D test function: f(x) = cos(x) - x + nx = 64 + x = torch.linspace(0, 2 * torch.pi, nx, dtype=torch.float64) + f = torch.cos(x) - x + + # Initialize FiniteDiff with dim=1 and specified boundary conditions + fd1d = FiniteDiff(dim=1, h=2 * torch.pi / nx, periodic_in_x=periodic_x) + + # Test first order derivatives + df_dx = fd1d.dx(f) + + # Test second order derivatives + d2f_dx2 = fd1d.dx(f, order=2) + + # Basic shape assertions + assert df_dx.shape == f.shape + assert d2f_dx2.shape == f.shape + + # Test that first derivative is approximately correct for f(x) = cos(x) - x + # df/dx ≈ -sin(x) - 1 for f(x) = cos(x) - x + if not periodic_x: + # For non-periodic, interior points should be close to expected value + expected_df_dx = -torch.sin(x[2:-2]) - 1.0 + assert_close(df_dx[2:-2], expected_df_dx, atol=0.01, rtol=0.1) + + +@pytest.mark.parametrize("periodic_x", [True, False]) +@pytest.mark.parametrize("periodic_y", [True, False]) +def test_finite_diff_2d(periodic_x, periodic_y): + """Test the FiniteDiff class with various boundary conditions for 2D.""" + + # Create a 2D test function: f(x,y) = x^2 + y^2 + nx, ny = 32, 32 + x = torch.linspace(0, 2 * torch.pi, nx, dtype=torch.float64) + y = torch.linspace(0, 2 * torch.pi, ny, dtype=torch.float64) + X, Y = torch.meshgrid(x, y, indexing="ij") + f = X**2 + Y**2 + + # Initialize FiniteDiff with dim=2 and specified boundary conditions + fd2d = FiniteDiff( + dim=2, h=(0.2, 0.2), periodic_in_x=periodic_x, periodic_in_y=periodic_y + ) + + # Test first order derivatives + df_dx = fd2d.dx(f) + df_dy = fd2d.dy(f) + + # Test second order derivatives + d2f_dx2 = fd2d.dx(f, order=2) + d2f_dy2 = fd2d.dy(f, order=2) + + # Test laplacian + laplacian = fd2d.laplacian(f) + + # Test gradient + gradient = fd2d.gradient(f) + + # Test with vector field for divergence and curl + # Create a simple vector field: u = [sin(x), cos(y)] + u1 = torch.sin(X) + u2 = torch.cos(Y) + u_vector = torch.stack([u1, u2], dim=0) + + divergence = fd2d.divergence(u_vector) + curl = fd2d.curl(u_vector) + + # Basic shape assertions + assert df_dx.shape == f.shape + assert df_dy.shape == f.shape + assert d2f_dx2.shape == f.shape + assert d2f_dy2.shape == f.shape + assert laplacian.shape == f.shape + assert gradient.shape == (2, nx, ny) + assert divergence.shape == (nx, ny) + assert curl.shape == (nx, ny) + + # Test that laplacian equals sum of second derivatives + assert_close(laplacian, d2f_dx2 + d2f_dy2) + + +@pytest.mark.parametrize("periodic_x", [True, False]) +@pytest.mark.parametrize("periodic_y", [True, False]) +@pytest.mark.parametrize("periodic_z", [True, False]) +def test_finite_diff_3d(periodic_x, periodic_y, periodic_z): + """Test the FiniteDiff class with various boundary conditions for 3D.""" + + # Create a 3D test function: f(x,y,z) = x^2 + y^2 + z^2 + nx, ny, nz = 16, 16, 16 + x = torch.linspace(0, 2 * torch.pi, nx, dtype=torch.float64) + y = torch.linspace(0, 2 * torch.pi, ny, dtype=torch.float64) + z = torch.linspace(0, 2 * torch.pi, nz, dtype=torch.float64) + X, Y, Z = torch.meshgrid(x, y, z, indexing="ij") + f = X**2 + Y**2 + Z**2 + + # Initialize FiniteDiff with dim=3 and specified boundary conditions + fd3d = FiniteDiff( + dim=3, + h=(0.4, 0.4, 0.4), + periodic_in_x=periodic_x, + periodic_in_y=periodic_y, + periodic_in_z=periodic_z, + ) + + # Test first order derivatives + df_dx = fd3d.dx(f) + df_dy = fd3d.dy(f) + df_dz = fd3d.dz(f) + + # Test second order derivatives + d2f_dx2 = fd3d.dx(f, order=2) + d2f_dy2 = fd3d.dy(f, order=2) + d2f_dz2 = fd3d.dz(f, order=2) + + # Test laplacian + laplacian = fd3d.laplacian(f) + + # Test gradient + gradient = fd3d.gradient(f) + + # Test with vector field for divergence and curl + # Create a simple vector field: u = [sin(x), cos(y), sin(z)] + u1 = torch.sin(X) + u2 = torch.cos(Y) + u3 = torch.sin(Z) + u_vector = torch.stack([u1, u2, u3], dim=0) + + divergence = fd3d.divergence(u_vector) + curl = fd3d.curl(u_vector) + + # Basic shape assertions + assert df_dx.shape == f.shape + assert df_dy.shape == f.shape + assert df_dz.shape == f.shape + assert d2f_dx2.shape == f.shape + assert d2f_dy2.shape == f.shape + assert d2f_dz2.shape == f.shape + assert laplacian.shape == f.shape + assert gradient.shape == (3, nz, ny, nx) + assert divergence.shape == (nx, ny, nz) + assert curl.shape == (3, nz, ny, nx) + + # Test that laplacian equals sum of second derivatives + assert_close(laplacian, d2f_dx2 + d2f_dy2 + d2f_dz2) + + +@pytest.mark.parametrize("periodic", [True, False]) +def test_fourier_diff(periodic: bool): + if periodic: + ## Test on periodic functions without Fourier continuation + # Consider sin(x) and cos(x) + L = 2 * torch.pi + x = torch.linspace(0, L, 101)[:-1] + f = torch.stack([torch.sin(x), torch.cos(x)], dim=0) + + # Use FourierDiff class + fd1d = FourierDiff(dim=1, L=L, use_fc=False) + derivatives = fd1d.compute_multiple_derivatives(f, [1, 2, 3]) + dfdx, df2dx2, df3dx3 = derivatives + + assert f.shape == dfdx.shape == df2dx2.shape == df3dx3.shape + + else: + ## Test on non-periodic functions using Fourier continuation + # Consider sin(16*x)-cos(8*x) and exp(-0.8x) + L = 2 * torch.pi + x = torch.linspace(0, L, 101)[:-1] + f = torch.stack([torch.sin(3 * x) - torch.cos(x), torch.exp(-0.8 * x) + torch.sin(x)], dim=0) + + # Use FourierDiff class with Fourier continuation + fd1d = FourierDiff(dim=1, L=L, use_fc="Legendre", fc_degree=4, fc_n_additional_pts=30) + derivatives = fd1d.compute_multiple_derivatives(f, [1, 2]) + dfdx, df2dx2 = derivatives + + assert f.shape == dfdx.shape == df2dx2.shape + + +@pytest.mark.parametrize("use_fc", [False, "Legendre"]) +def test_fourier_diff_2d(use_fc): + if use_fc: + fd2d = FourierDiff( + dim=2, + L=(2 * torch.pi, 2 * torch.pi), + use_fc=use_fc, + fc_degree=4, + fc_n_additional_pts=20, + ) + else: + fd2d = FourierDiff(dim=2, L=(2 * torch.pi, 2 * torch.pi)) + + # Create a 2D periodic function: sin(x) * cos(y) + L_x, L_y = 2 * torch.pi, 2 * torch.pi + nx, ny = 64, 64 + x = torch.linspace(0, L_x, nx, dtype=torch.float64) + y = torch.linspace(0, L_y, ny, dtype=torch.float64) + X, Y = torch.meshgrid(x, y, indexing="ij") + + # Test function: f(x,y) = sin(x) * cos(y) for periodic, exp(-x) * sin(y) for non-periodic + if use_fc: + f = torch.exp(-X) * torch.sin(Y) # Non-periodic function + else: + f = torch.sin(X) * torch.cos(Y) # Periodic function + + # Test partial derivatives + df_dx_computed = fd2d.dx(f) + df_dy_computed = fd2d.dy(f) + + # Test higher order derivatives + d2f_dx2_computed = fd2d.dx(f, order=2) + d2f_dy2_computed = fd2d.dy(f, order=2) + + # Test laplacian + laplacian_computed = fd2d.laplacian(f) + + # Test multiple derivatives computation + derivatives = fd2d.compute_multiple_derivatives(f, [(1, 0), (0, 1), (2, 0), (0, 2)]) + df_dx_multi, df_dy_multi, d2f_dx2_multi, d2f_dy2_multi = derivatives + + # Test gradient + gradient = fd2d.gradient(f) + assert gradient.shape == (2, nx, ny) + + # Test divergence with a vector field + # Create a vector field: u = [sin(x), cos(y)] + u1 = torch.sin(X) + u2 = torch.cos(Y) + u_vector = torch.stack([u1, u2], dim=0) + divergence = fd2d.divergence(u_vector) + + # Test curl with a vector field + curl = fd2d.curl(u_vector) + + # Basic shape assertions - just check that derivatives have correct shapes + assert df_dx_computed.shape == f.shape + assert df_dy_computed.shape == f.shape + assert d2f_dx2_computed.shape == f.shape + assert d2f_dy2_computed.shape == f.shape + assert laplacian_computed.shape == f.shape + assert len(derivatives) == 4 + assert gradient.shape == (2, nx, ny) + assert divergence.shape == (nx, ny) + assert curl.shape == (nx, ny) + + +@pytest.mark.parametrize("use_fc", [False, "Gram"]) +def test_fourier_diff_3d(use_fc): + """Test the FourierDiff class with various scenarios.""" + + # Test basic functionality + if use_fc: + fd3d = FourierDiff( + dim=3, + L=(2 * torch.pi, 2 * torch.pi, 2 * torch.pi), + use_fc=use_fc, + fc_degree=4, + fc_n_additional_pts=50, + ) + else: + fd3d = FourierDiff(dim=3, L=(2 * torch.pi, 2 * torch.pi, 2 * torch.pi)) + + # Create a 3D periodic function: sin(x) * cos(y) * sin(z) + L_x, L_y, L_z = 2 * torch.pi, 2 * torch.pi, 2 * torch.pi + nx, ny, nz = 32, 32, 32 + x = torch.linspace(0, L_x, nx, dtype=torch.float64) + y = torch.linspace(0, L_y, ny, dtype=torch.float64) + z = torch.linspace(0, L_z, nz, dtype=torch.float64) + X, Y, Z = torch.meshgrid(x, y, z, indexing="ij") + + # Test function: f(x,y,z) = sin(x) * cos(y) * sin(z) for periodic, exp(-x) * sin(y) * cos(z) for non-periodic + if use_fc: + f = torch.sin(X) * torch.cos(Y) * torch.sin(Z) # Non-periodic function + else: + f = torch.sin(X) * torch.cos(Y) * torch.sin(Z) # Periodic function + + # Test partial derivatives + df_dx_computed = fd3d.dx(f) + df_dy_computed = fd3d.dy(f) + df_dz_computed = fd3d.dz(f) + + # Test higher order derivatives + d2f_dx2_computed = fd3d.dx(f, order=2) + d2f_dy2_computed = fd3d.dy(f, order=2) + d2f_dz2_computed = fd3d.dz(f, order=2) + d2f_dxdy_computed = fd3d.dx(fd3d.dy(f)) + d2f_dxdz_computed = fd3d.dx(fd3d.dz(f)) + d2f_dydz_computed = fd3d.dy(fd3d.dz(f)) + + # Test laplacian + laplacian_computed = fd3d.laplacian(f) + + # Test multiple derivatives computation + derivatives = fd3d.compute_multiple_derivatives(f, [(1, 0, 0), (0, 1, 0), (0, 0, 1), (2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0), (1, 0, 1), (0, 1, 1)]) + df_dx_multi, df_dy_multi, df_dz_multi, d2f_dx2_multi, d2f_dy2_multi, d2f_dz2_multi, d2f_dxdy_multi, d2f_dxdz_multi, d2f_dydz_multi = derivatives + + # Test gradient + gradient = fd3d.gradient(f) + assert gradient.shape == (3, nz, ny, nx) + + # Test divergence with a vector field + # Create a vector field: u = [sin(x), cos(y), sin(z)] + u1 = torch.sin(X) + u2 = torch.cos(Y) + u3 = torch.sin(Z) + u_vector = torch.stack([u1, u2, u3], dim=0) + divergence = fd3d.divergence(u_vector) + + # Test curl with a vector field + curl = fd3d.curl(u_vector) + + # Basic shape assertions - just check that derivatives have correct shapes + assert df_dx_computed.shape == f.shape + assert df_dy_computed.shape == f.shape + assert df_dz_computed.shape == f.shape + assert d2f_dx2_computed.shape == f.shape + assert d2f_dy2_computed.shape == f.shape + assert d2f_dz2_computed.shape == f.shape + assert d2f_dxdy_computed.shape == f.shape + assert d2f_dxdz_computed.shape == f.shape + assert d2f_dydz_computed.shape == f.shape + assert laplacian_computed.shape == f.shape + assert len(derivatives) == 9 + assert gradient.shape == (3, nz, ny, nx) + assert divergence.shape == (nx, ny, nz) + assert curl.shape == (3, nz, ny, nx) diff --git a/sources/neuraloperator/neuralop/models/__init__.py b/sources/neuraloperator/neuralop/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ca3f9dbf4f4b4be5c221d3ec5af65226cce27d --- /dev/null +++ b/sources/neuraloperator/neuralop/models/__init__.py @@ -0,0 +1,16 @@ +from .fno import TFNO, FNO + +# only import SFNO if torch_harmonics is built locally +try: + from .sfno import SFNO + from .local_no import LocalNO +except: + pass +from .uno import UNO +from .uqno import UQNO +from .fnogno import FNOGNO +from .gino import GINO +from .codano import CODANO +from .rno import RNO +from .otno import OTNO +from .base_model import get_model diff --git a/sources/neuraloperator/neuralop/models/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b89b1954fe6415bfece0c28a56a0d006c326385b Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/base_model.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/base_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65b2bf05437a96af5639b243d5fd06ae0da7a026 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/base_model.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/codano.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/codano.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bede8d3b738134f16d574aadeec45d6c57aac9e Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/codano.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/fno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/fno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f650fc32ad5bc8f945242efdbd6f55a8ff187991 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/fno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/fnogno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/fnogno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d95458060eeb985383994485b07cd49779ad622f Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/fnogno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/gino.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/gino.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb4ba8de19f650514d6b8e25e4478679efbd2382 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/gino.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/otno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/otno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7a0d46d672b70cf228ea581521f39e9a4b9303 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/otno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/rno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/rno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a7a96eadfbbabe80e1052bd664e9a44f6dfc79 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/rno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/sfno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/sfno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ee5dfa51869c6b21244b6c9f2eefe46b3d54a4 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/sfno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/uno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/uno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aaf9562b97ec7dbf1a9e798024a5c58de15f3df Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/uno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/__pycache__/uqno.cpython-313.pyc b/sources/neuraloperator/neuralop/models/__pycache__/uqno.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..456fe507893b8db7a08bd1f73573cbc249043403 Binary files /dev/null and b/sources/neuraloperator/neuralop/models/__pycache__/uqno.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/models/base_model.py b/sources/neuraloperator/neuralop/models/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0cd1b90d0e627182609327aa32da19279cfa9f --- /dev/null +++ b/sources/neuraloperator/neuralop/models/base_model.py @@ -0,0 +1,235 @@ +import inspect +import torch +import warnings +from pathlib import Path + +# Author: Jean Kossaifi + + +class BaseModel(torch.nn.Module): + """Based 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 modes 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. + """ + + _models = dict() + _version = "0.1.0" + + def __init_subclass__(cls, name=None, **kwargs): + """When a subclass is created, register it in _models + We look for an existing name attribute. + If not give, then we use the class' name. + """ + super().__init_subclass__(**kwargs) + if name is not None: + BaseModel._models[name.lower()] = cls + cls._name = name + else: + # warnings.warn(f'Creating a subclass of BaseModel {cls.__name__} with no name, initializing with {cls.__name__}.') + BaseModel._models[cls.__name__.lower()] = cls + cls._name = cls.__name__ + + def __new__(cls, *args, **kwargs): + """Verify arguments and save init kwargs for loading/saving + + We inspect the class' signature and check for unused parameters, or + parameters not passed. + + We store all the args and kwargs given so we can duplicate the instance transparently. + """ + sig = inspect.signature(cls) + model_name = cls.__name__ + + verbose = kwargs.get("verbose", False) + # Verify that given parameters are actually arguments of the model + for key in kwargs: + if key not in sig.parameters: + if verbose: + print( + f"Given argument key={key} " + f"that is not in {model_name}'s signature." + ) + + # Check for model arguments not specified in the configuration + for key, value in sig.parameters.items(): + if (value.default is not inspect._empty) and (key not in kwargs): + if verbose: + print( + f"Keyword argument {key} not specified for model {model_name}, " + f"using default={value.default}." + ) + kwargs[key] = value.default + + if hasattr(cls, "_version"): + kwargs["_version"] = cls._version + kwargs["args"] = args + kwargs["_name"] = cls._name + instance = super().__new__(cls) + instance._init_kwargs = kwargs + + return instance + + def state_dict(self, destination: dict=None, prefix: str='', keep_vars: bool=False): + """ + state_dict subclasses nn.Module.state_dict() and adds a metadata field + to track the model version and ensure only compatible saves are loaded. + + Parameters + ---------- + destination : dict, optional + If provided, the state of module will + be updated into the dict and the same object is returned. + Otherwise, an OrderedDict will be created and returned, by default None + prefix : str, optional + a prefix added to parameter and buffer + names to compose the keys in state_dict, by default ``''`` + keep_vars (bool, optional): by default the torch.Tensors + returned in the state dict are detached from autograd. + If True, detaching will not be performed, by default False + + """ + state_dict = super().state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars) + if state_dict.get('_metadata') == None: + state_dict['_metadata'] = self._init_kwargs + else: + warnings.warn("Attempting to update metadata for a module with metadata already in self.state_dict()") + return state_dict + + def load_state_dict(self, state_dict, strict=True, assign=False): + """load_state_dict subclasses nn.Module.load_state_dict() and adds a metadata field + to track the model version and ensure only compatible saves are loaded. + + Parameters + ---------- + state_dict : dict + state dictionary generated by ``nn.Module.state_dict()`` + strict : bool, optional + whether to strictly enforce that the keys in ``state_dict`` + match the keys returned by this module's, by default True. + assign : bool, optional + whether to assign items in the state dict to their corresponding keys + in the module instead of copying them inplace into the module's current + parameters and buffers. When False, the properties of the tensors in the + current module are preserved while when True, the properties of the Tensors + in the state dict are preserved, by default False + + Returns + ------- + _type_ + _description_ + """ + metadata = state_dict.pop("_metadata", None) + + if metadata is not None: + saved_version = metadata.get("_version", None) + if saved_version is None: + warnings.warn(f"Saved instance of {self.__class__} has no stored version attribute.") + if saved_version != self._version: + warnings.warn( + f"Attempting to load a {self.__class__} of version {saved_version}," + f"But current version of {self.__class__} is {self._version}" + ) + # remove state dict metadata at the end to ensure proper loading with PyTorch module + return super().load_state_dict(state_dict, strict=strict, assign=assign) + + def save_checkpoint(self, save_folder, save_name): + """Saves the model state and init param in the given folder under the given name""" + save_folder = Path(save_folder) + if not save_folder.exists(): + save_folder.mkdir(parents=True) + + state_dict_filepath = save_folder.joinpath(f"{save_name}_state_dict.pt").as_posix() + torch.save(self.state_dict(), state_dict_filepath) + metadata_filepath = save_folder.joinpath(f"{save_name}_metadata.pkl").as_posix() + # Objects (e.g. GeLU) are not serializable by json - find a better solution in the future + torch.save(self._init_kwargs, metadata_filepath) + + def load_checkpoint(self, save_folder, save_name, map_location=None): + save_folder = Path(save_folder) + state_dict_filepath = save_folder.joinpath(f'{save_name}_state_dict.pt').as_posix() + self.load_state_dict(torch.load(state_dict_filepath, map_location=map_location, weights_only=False)) + + @classmethod + def from_checkpoint(cls, save_folder, save_name, map_location=None): + save_folder = Path(save_folder) + + metadata_filepath = save_folder.joinpath(f"{save_name}_metadata.pkl").as_posix() + init_kwargs = torch.load(metadata_filepath, weights_only=False) + + version = init_kwargs.pop("_version", None) + if hasattr(cls, "_version") and version != cls._version: + warnings.warn(f'Checkpoint saved for version {version} of model {cls._name} but current code is version {cls._version}') + + # Remove metadata fields that shouldn't be passed to __init__ + init_kwargs.pop("_name", None) + + if "args" in init_kwargs: + init_args = init_kwargs.pop("args") + else: + init_args = [] + instance = cls(*init_args, **init_kwargs) + + instance.load_checkpoint(save_folder, save_name, map_location=map_location) + return instance + + +def available_models(): + """List the available neural operators""" + return list(BaseModel._models.keys()) + + +def get_model(config): + """Returns an instantiated model for the given config + + * Reads the model to be used from config['arch'] + * Adjusts config["arch"]["data_channels"] accordingly if multi-grid patching is used + + Also prints warnings for safety, in case:: + * some given arguments aren't actually used by the model + * some keyword arguments of the models aren't provided by the config + + Parameters + ---------- + config : Bunch or dict-like + configuration, must have + arch = config['arch'] (string) + and the corresponding config[arch] (a subdict with the kwargs of the model) + + Returns + ------- + model : nn.Module + the instanciated module + """ + arch = config.model["model_arch"].lower() + model_config = config.model.copy() + + # Remove model_arch from config as it's not a model parameter + model_config.pop("model_arch", None) + + # Set the number of input channels depending on channels in data + mg patching + data_channels = model_config.pop("data_channels") + try: + patching_levels = config["patching"]["levels"] + except KeyError: + patching_levels = 0 + if patching_levels: + data_channels *= patching_levels + 1 + model_config["in_channels"] = data_channels + + # Dispatch model creation + try: + return BaseModel._models[arch](**model_config) + except KeyError: + raise ValueError(f"Got config.arch={arch}, expected one of {available_models()}.") diff --git a/sources/neuraloperator/neuralop/models/codano.py b/sources/neuraloperator/neuralop/models/codano.py new file mode 100644 index 0000000000000000000000000000000000000000..3f697792206fcc606b73130743fbbd75428f7d72 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/codano.py @@ -0,0 +1,591 @@ +import torch.nn as nn +import torch.nn.functional as F +import torch +import numpy as np +from ..layers.channel_mlp import ChannelMLP +from ..layers.spectral_convolution import SpectralConv +from ..layers.skip_connections import skip_connection +from ..layers.padding import DomainPadding +from ..layers.coda_layer import CODALayer +from ..layers.resample import resample +from ..layers.embeddings import GridEmbedding2D, GridEmbeddingND + + +class CODANO(nn.Module): + """Codomain Attention Neural Operators (CoDA-NO) + + It uses a specialized attention mechanism in the codomain space for data in + infinite dimensional spaces as described in [1]_. The model treats each input channel as a variable of the physical system + and uses attention mechanism to model the interactions between the variables. The model uses lifting and projection modules + to map the input variables to a higher-dimensional space and then back to the output space. The model also supports positional + encoding and static channel information for additional context of the physical system such as external force or inlet condition. + + Parameters + ---------- + n_layers : int + The number of codomain attention layers. Default: 4 + n_modes : list + The number of Fourier modes to use in integral operators in the CoDA-NO block along each dimension. + Example: For a 5-layer 2D CoDA-NO, n_modes=[[16, 16], [16, 16], [16, 16], [16, 16], [16, 16]] + + Other Parameters + ---------------- + output_variable_codimension : int, optional + The number of output channels (or output codomain dimension) corresponding to each input variable (or input channel). + Example: For an input with 3 variables (channels) and output_variable_codimension=2, the output will have 6 channels (3 variables × 2 codimension). Default: 1 + lifting_channels : int, optional + Number of intermediate channels in the lifting block. + The lifting module projects each input variable (i.e., each input channel) into a + higher-dimensional space determined by hidden_variable_codimension. + If lifting_channels is None, lifting is not performed and the input channels are + directly used as tokens for codomain attention. Default: 64 + hidden_variable_codimension : int, optional + The number of hidden channels corresponding to each input variable (or channel). Each input channel is independently lifted + to hidden_variable_codimension channels by the lifting block. Default: 32 + projection_channels : int, optional + The number of intermediate channels in the projection block of the CODANO. + If projection_channels=None, projection is not performed and the output of + the last CoDA block is returned directly. Default: 64 + use_positional_encoding : bool, optional + Indicates whether to use variable-specific positional encoding. If True, a learnable positional encoding is concatenated + to each variable (each input channel) before the lifting operation. + The positional encoding used here is a function space generalization of the learnable positional encoding + used in BERT [2]. In CODANO, the positional encoding is a function on domain which is learned directly + in the Fourier Space. Default: False + positional_encoding_dim : int, optional + The dimension (number of channels) of the positional encoding learned of each input variable + (i.e., input channel). Default: 8 + positional_encoding_modes : list, optional + Number of Fourier modes used in positional encoding along each dimension. The positional embeddings are functions and are directly learned + in Fourier space. This parameter must be specified when use_positional_encoding=True. + Example: For a 2D input, positional_encoding_modes could be [16, 16]. Default: None + static_channel_dim : int, optional + The number of channels for static information, such as boundary conditions in PDEs. These channels are concatenated with + each variable before the lifting operation and used to provide additional information + regarding the physical setup of the system. + When static_channel_dim > 0, additional information must be provided during the forward pass. + For example, static_channel_dim=1 can be used to provide mask of the domain pointing + a hole or obstacle in the domain. Default: 0 + variable_ids : list[str], optional + The names of the variables in the dataset. + This parameter is only required when use_positional_encoding=True to initialize learnable + positional embeddings for each unique physical variable in the dataset. + + For example: + If the dataset consists of only Navier Stokes equations, the variable_ids=['u_x', 'u_y', 'p'], representing the velocity + components in x and y directions and pressure, respectively. Please note that we consider each input channel as a physical + variable of the PDE. + + Please note that the 'velocity' variable is composed of two channels (codimension=2) and we have split the velocity field + into two components, i.e., u_x and u_y. And this is to be done for all variable with codimension > 1. + + If the dataset consists of multiple PDEs, such as Navier Stokes and Heat equation, the variable_ids=['u_x', 'u_y', 'p', 'T'], + where 'T' represents the temperature variable for the Heat equation and 'u_x', 'u_y', 'p' are the velocity components and pressure + for the Navier Stokes equations. This is required when we aim to learn a single solver for multiple different PDEs. + + This parameter is not required when use_positional_encoding=False. Default: None + per_layer_scaling_factors : list, optional + The output scaling factor for each CoDANO_block along each dimension. The output of each of the CoDANO_block + is resampled according to the scaling factor and then passed to the following CoDANO_blocks. + Example: For a 2D input and n_layers=5, per_layer_scaling_factors=[[1, 1], [0.5, 0.5], [1, 1], [2, 2], [1, 1]], + which downsamples the output of the second layer by a factor of 2 and upsamples the output of the fourth layer by a factor of 2. + The resolution of the output of the CODANO model is determined by the product of the scaling factors of all the layers. Default: None + n_heads : list, optional + The number of attention heads for each layer. + Example: For a 4-layer CoDA-NO, n_heads=[2, 2, 2, 2]. Default: None (single attention head for each codomain attention block) + attention_scaling_factors : list, optional + Scaling factors in the codomain attention mechanism to scale the key and query functions. These scaling factors are used to resample + the key and query function before calculating the attention matrix. It does not have any effect on the value functions + in the codomain attention mechanism, i.e., it does not change the output shape of the block. + Example: For a 5-layer CoDA-NO, attention_scaling_factors=[0.5, 0.5, 0.5, 0.5, 0.5], which downsample the key and query functions, + reducing the resolution by a factor of 2. Default: None (no scaling) + conv_module : nn.Module, optional + The convolution module to use in the CoDANO_block. Default: SpectralConv + nonlinear_attention : bool, optional + Indicates whether to use a non-linear attention mechanism, employing non-linear key, query, and value operators. Default: False + non_linearity : callable, optional + The non-linearity to use in the codomain attention block. Default: F.gelu + attention_token_dim : int, optional + The number of channels in each token function. attention_token_dim must divide hidden_variable_codimension. Default: 1 + per_channel_attention : bool, optional + Indicates whether to use a per-channel attention mechanism in Codomain attention layer. Default: False + enable_cls_token : bool, optional + Indicates whether to use a learnable CLASS token during the attention mechanism. We use a function-space generalization of the + learnable [class] token used in vision transformers such as ViT, which is learned directly in Fourier space. + The [class] function is realized on the input grid by performing an inverse Fourier transform of the learned Fourier coefficients. + Then, the [class] token function is added to the set of input token functions before passing to the codomain attention layer. It aggregates + information from all the other tokens through the attention mechanism. The output token corresponding to the [class] token is discarded in the + output of the last CoDA block. Default: False + use_horizontal_skip_connection : bool, optional + Indicates whether to use horizontal skip connections, similar to U-shaped architectures. Default: False + horizontal_skips_map : dict, optional + A mapping that specifies horizontal skip connections between layers. Only required when use_horizontal_skip_connection=True. + Example: For a 5-layer architecture, horizontal_skips_map={4: 0, 3: 1} creates skip connections from layer 0 to layer 4 and layer 1 to layer 3. Default: None + domain_padding : float, optional + The padding factor for each input channel. It zero pads each of the channel. Default: 0.25 + layer_kwargs : dict, optional + Additional arguments for the CoDA blocks. Default: {} + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when the convolution module is :class:`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. + + References + ---------- + .. [1] Rahman, Md Ashiqur, et al. "Pretraining codomain attention neural operators for solving multiphysics pdes." (2024). + NeurIPS 2024. https://arxiv.org/pdf/2403.12553. + + .. [2] Devlin, Jacob, et al. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. + + """ + + def __init__( + self, + output_variable_codimension=1, + lifting_channels: int = 64, + hidden_variable_codimension=32, + projection_channels: int = 64, + use_positional_encoding=False, + positional_encoding_dim=8, + positional_encoding_modes=None, + static_channel_dim=0, + variable_ids=None, + use_horizontal_skip_connection=False, + horizontal_skips_map=None, + n_layers=4, + n_modes=None, + per_layer_scaling_factors=None, + n_heads=None, + attention_scaling_factors=None, + conv_module=SpectralConv, + nonlinear_attention=False, + non_linearity=F.gelu, + attention_token_dim=1, + per_channel_attention=False, + layer_kwargs={}, + domain_padding=0.25, + enable_cls_token=False, + enforce_hermitian_symmetry=True, + ): + super().__init__() + self.n_layers = n_layers + assert len(n_modes) == n_layers, "number of modes for all layers are not given" + assert ( + n_heads is None or len(n_heads) == n_layers + ), "number of Attention head for all layers are not given" + assert ( + per_layer_scaling_factors is None + or len(per_layer_scaling_factors) == n_layers + ), "scaling for all layers are not given" + assert ( + attention_scaling_factors is None + or len(attention_scaling_factors) == n_layers + ), "attention scaling for all layers are not given" + if use_positional_encoding: + assert positional_encoding_dim > 0, "positional encoding dim is not given" + assert ( + positional_encoding_modes is not None + ), "positional encoding modes are not given" + else: + positional_encoding_dim = 0 + + if attention_scaling_factors is None: + attention_scaling_factors = [1] * n_layers + + input_variable_codimension = 1 # each channel is a variable + if lifting_channels is None: + self.lifting = False + else: + lifting_variable_codimension = lifting_channels + self.lifting = True + + if projection_channels is None: + self.projection = False + else: + projection_variable_codimension = projection_channels + self.projection = True + extended_variable_codimemsion = ( + input_variable_codimension + static_channel_dim + positional_encoding_dim + ) + if not self.lifting: + hidden_variable_codimension = extended_variable_codimemsion + + assert ( + hidden_variable_codimension % attention_token_dim == 0 + ), "attention token dim should divide hidden variable codimension" + + self.n_dim = len(n_modes[0]) + + if n_heads is None: + n_heads = [1] * n_layers + if per_layer_scaling_factors is None: + per_layer_scaling_factors = [[1] * self.n_dim] * n_layers + if attention_scaling_factors is None: + attention_scaling_factors = [1] * n_layers + + self.input_variable_codimension = input_variable_codimension + self.hidden_variable_codimension = hidden_variable_codimension + self.n_modes = n_modes + self.per_layer_scale_factors = per_layer_scaling_factors + self.non_linearity = non_linearity + self.n_heads = n_heads + self.enable_cls_token = enable_cls_token + self.positional_encoding_dim = positional_encoding_dim + self.variable_ids = variable_ids + self.attention_scalings = attention_scaling_factors + self.positional_encoding_modes = positional_encoding_modes + self.static_channel_dim = static_channel_dim + self.layer_kwargs = {**layer_kwargs, "enforce_hermitian_symmetry": enforce_hermitian_symmetry} + self.use_positional_encoding = use_positional_encoding + self.use_horizontal_skip_connection = use_horizontal_skip_connection + self.horizontal_skips_map = horizontal_skips_map + self.output_variable_codimension = output_variable_codimension + + if self.positional_encoding_modes is not None: + self.positional_encoding_modes[-1] = self.positional_encoding_modes[-1] // 2 + + # calculating scaling + if self.per_layer_scale_factors is not None: + self.end_to_end_scaling = [1] * len(self.per_layer_scale_factors[0]) + # multiplying scaling factors + for k in self.per_layer_scale_factors: + self.end_to_end_scaling = [ + i * j for (i, j) in zip(self.end_to_end_scaling, k) + ] + else: + self.end_to_end_scaling = [1] * self.n_dim + + if self.n_heads is None: + self.n_heads = [1] * self.n_layers + + # Setting up domain padding for encoder and reconstructor + if domain_padding is not None and domain_padding > 0: + self.domain_padding = DomainPadding( + domain_padding=domain_padding, + resolution_scaling_factor=self.end_to_end_scaling, + ) + else: + self.domain_padding = None + + self.extended_variable_codimemsion = extended_variable_codimemsion + if self.lifting: + self.lifting = ChannelMLP( + in_channels=extended_variable_codimemsion, + out_channels=self.hidden_variable_codimension, + hidden_channels=lifting_variable_codimension, + n_layers=2, + n_dim=self.n_dim, + ) + else: + self.hidden_variable_codimension = self.extended_variable_codimemsion + + self.attention_layers = nn.ModuleList([]) + + for i in range(self.n_layers): + self.attention_layers.append( + CODALayer( + n_modes=self.n_modes[i], + n_heads=self.n_heads[i], + scale=self.attention_scalings[i], + token_codimension=attention_token_dim, + per_channel_attention=per_channel_attention, + nonlinear_attention=nonlinear_attention, + resolution_scaling_factor=self.per_layer_scale_factors[i], + conv_module=conv_module, + non_linearity=self.non_linearity, + **self.layer_kwargs, + ) + ) + + if self.use_horizontal_skip_connection: + # horizontal skip connections + # linear projection of the concated tokens from skip connections + + self.skip_map_module = nn.ModuleDict() + for k in self.horizontal_skips_map.keys(): + self.skip_map_module[str(k)] = ChannelMLP( + in_channels=2 * self.hidden_variable_codimension, + out_channels=self.hidden_variable_codimension, + hidden_channels=None, + n_layers=1, + non_linearity=nn.Identity(), + n_dim=self.n_dim, + ) + + if self.projection: + self.projection = ChannelMLP( + in_channels=self.hidden_variable_codimension, + out_channels=output_variable_codimension, + hidden_channels=projection_variable_codimension, + n_layers=2, + n_dim=self.n_dim, + ) + else: + self.projection = None + + if enable_cls_token: + self.cls_token = nn.Parameter( + torch.randn( + 1, + self.hidden_variable_codimension, + *self.n_modes[0], + dtype=torch.cfloat, + ) + ) + + if use_positional_encoding: + self.positional_encoding = nn.ParameterDict() + for i in self.variable_ids: + self.positional_encoding[i] = nn.Parameter( + torch.randn( + 1, + positional_encoding_dim, + *self.positional_encoding_modes, + dtype=torch.cfloat, + ) + ) + + def _extend_positional_encoding(self, new_var_ids): + """ + Add variable specific positional encoding for new variables. This function is required + while adapting a pre-trained model to a new dataset/PDE with additional new variables. + + Parameters + ---------- + new_var_ids : list[str] + IDs of the new variables to add positional encoding. + """ + for i in new_var_ids: + self.positional_encoding[i] = nn.Parameter( + torch.randn( + 1, + self.positional_encoding_dim, + *self.positional_encoding_modes, + dtype=torch.cfloat, + ) + ) + + self.variable_ids += new_var_ids + + def _get_positional_encoding(self, x, input_variable_ids): + """ + Returns the positional encoding for the input variables. + Parameters + ---------- + x : torch.Tensor + input tensor of shape (batch_size, num_inp_var, H, W, ...) + input_variable_ids : list[str] + The names of the variables corresponding to the channels of input 'x'. + """ + encoding_list = [] + for i in input_variable_ids: + encoding_list.append( + torch.fft.irfftn(self.positional_encoding[i], s=x.shape[-self.n_dim :]) + ) + + return torch.stack(encoding_list, dim=1) + + def _get_cls_token(self, x): + """ + Returns the learnable cls token for the input variables. + Parameters + ---------- + x : torch.Tensor + input tensor of shape (batch_size, num_inp_var, H, W, ...) + This is used to determine the shape of the cls token. + """ + cls_token = torch.fft.irfftn(self.cls_token, s=x.shape[-self.n_dim :]) + repeat_shape = [1 for _ in x.shape] + repeat_shape[0] = x.shape[0] + cls_token = cls_token.repeat(*repeat_shape) + return cls_token + + def _extend_variables(self, x, static_channel, input_variable_ids): + """ + Extend the input variables by concatenating the static channel and positional encoding. + Parameters + ---------- + x : torch.Tensor + input tensor of shape (batch_size, num_inp_var, H, W, ...) + static_channel : torch.Tensor + static channel tensor of shape (batch_size, static_channel_dim, H, W, ...) + input_variable_ids : list[str] + The names of the variables corresponding to the channels of input 'x'. + """ + x = x.unsqueeze(2) + if static_channel is not None: + repeat_shape = [1 for _ in x.shape] + repeat_shape[1] = x.shape[1] + static_channel = static_channel.unsqueeze(1).repeat(*repeat_shape) + x = torch.cat([x, static_channel], dim=2) + if self.use_positional_encoding: + positional_encoding = self._get_positional_encoding(x, input_variable_ids) + repeat_shape = [1 for _ in x.shape] + repeat_shape[0] = x.shape[0] + x = torch.cat([x, positional_encoding.repeat(*repeat_shape)], dim=2) + return x + + def forward(self, x: torch.Tensor, static_channel=None, input_variable_ids=None): + """ + Parameters + ---------- + x : torch.Tensor + input tensor of shape (batch_size, num_inp_var, H, W, ...) + static_channel : torch.Tensor + static channel tensor of shape (batch_size, static_channel_dim, H, W, ...) + These channels provide additional information regarding the physical setup of the system. + Must be provided when `static_channel_dim > 0`. + input_variable_ids : list[str] + The names of the variables corresponding to the channels of input 'x'. + This parameter is required when `use_positional_encoding=True`. + + For example, if input x represents and snapshot of the velocity field of a fluid flow, the variable_ids=['u_x', 'u_y']. + The variable_ids must be in the same order as the channels in the input tensor 'x', i.e., variable_ids[0] corresponds to the + first channel of 'x', i.e., x[:, 0, ...]. + + Returns + ------- + torch.Tensor + output tensor of shape (batch_size, output_variable_codimension*num_inp_var, H, W, ...) + """ + batch, num_inp_var, *spatial_shape = ( + x.shape + ) # num_inp_var is the number of channels in the input + + # input validation + if ( + self.static_channel_dim > 0 + and static_channel is None + and static_channel.shape[1] != self.static_channel_dim + ): + raise ValueError( + f"Epected static channel dimension is {self.static_channel_dim}, but got {static_channel.shape[1]}" + ) + if self.use_positional_encoding: + assert ( + input_variable_ids is not None + ), "variable_ids are not provided for the input" + assert x.shape[1] == len( + input_variable_ids + ), f"Expected number of variables in input is {len(input_variable_ids)}, but got {x.shape[1]}" + + # position encoding and static channels are concatenated with the input + # variables + + x = self._extend_variables(x, static_channel, input_variable_ids) + + # input variables are lifted to a higher-dimensional space + if self.lifting: + x = x.reshape( + batch * num_inp_var, self.extended_variable_codimemsion, *spatial_shape + ) + x = self.lifting(x) + x = x.reshape( + batch, num_inp_var * self.hidden_variable_codimension, *spatial_shape + ) + + # getting the learnable CLASS token + if self.enable_cls_token: + cls_token = self._get_cls_token(x) + x = torch.cat( + [ + cls_token, + x, + ], + dim=1, + ) + num_inp_var += 1 + + # zero padding the domain of the input + if self.domain_padding is not None: + x = self.domain_padding.pad(x) + + # calculating the output shape + output_shape = [ + int(round(i * j)) + for (i, j) in zip(x.shape[-self.n_dim :], self.end_to_end_scaling) + ] + + # forward pass through the Codomain Attention layers + skip_outputs = {} + for layer_idx in range(self.n_layers): + if ( + self.horizontal_skips_map is not None + and layer_idx in self.horizontal_skips_map.keys() + ): + # `horizontal skip connections` + # tokens from skip connections are concatenated with the + # current token and then linearly projected + # to the `hidden_variable_codimension` + skip_val = skip_outputs[self.horizontal_skips_map[layer_idx]] + resolution_scaling_factors = [ + m / n for (m, n) in zip(x.shape, skip_val.shape) + ] + resolution_scaling_factors = resolution_scaling_factors[ + -1 * self.n_dim : + ] + t = resample( + skip_val, + resolution_scaling_factors, + list(range(-self.n_dim, 0)), + output_shape=x.shape[-self.n_dim :], + ) + x = x.reshape( + batch * num_inp_var, + self.hidden_variable_codimension, + *x.shape[-self.n_dim :], + ) + t = t.reshape( + batch * num_inp_var, + self.hidden_variable_codimension, + *t.shape[-self.n_dim :], + ) + x = torch.cat([x, t], dim=1) + x = self.skip_map_module[str(layer_idx)](x) + x = x.reshape( + batch, + num_inp_var * self.hidden_variable_codimension, + *x.shape[-self.n_dim :], + ) + + if layer_idx == self.n_layers - 1: + cur_output_shape = output_shape + else: + cur_output_shape = None + + x = self.attention_layers[layer_idx](x, output_shape=cur_output_shape) + + # storing the outputs for skip connections + if ( + self.horizontal_skips_map is not None + and layer_idx in self.horizontal_skips_map.values() + ): + skip_outputs[layer_idx] = x.clone() + + # removing the padding + if self.domain_padding is not None: + x = self.domain_padding.unpad(x) + + # projecting the hidden variables to the output variables + if self.projection: + x = x.reshape( + batch * num_inp_var, + self.hidden_variable_codimension, + *x.shape[-self.n_dim :], + ) + x = self.projection(x) + x = x.reshape( + batch, + num_inp_var * self.output_variable_codimension, + *x.shape[-self.n_dim :], + ) + else: + return x + + # discarding the CLASS token + if self.enable_cls_token: + x = x[:, self.output_variable_codimension :, ...] + return x diff --git a/sources/neuraloperator/neuralop/models/fno.py b/sources/neuraloperator/neuralop/models/fno.py new file mode 100644 index 0000000000000000000000000000000000000000..53aa834023a7d5c9a015425b21460a57f26ccede --- /dev/null +++ b/sources/neuraloperator/neuralop/models/fno.py @@ -0,0 +1,484 @@ +from functools import partialmethod +from typing import Tuple, List, Union, Literal + +Number = Union[float, int] + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +from ..layers.embeddings import GridEmbeddingND, GridEmbedding2D +from ..layers.spectral_convolution import SpectralConv +from ..layers.padding import DomainPadding +from ..layers.fno_block import FNOBlocks +from ..layers.channel_mlp import ChannelMLP +from ..layers.complex import ComplexValued +from .base_model import BaseModel + + +class FNO(BaseModel, name="FNO"): + """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 + ``neuralop.layers.spectral_convolution``), which is similar to a standard CNN + conv layer but operates in the frequency domain. + + For a deeper dive into the FNO architecture, refer to :ref:`fno_intro`. + + Parameters + ---------- + 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, optional + Number of Fourier Layers. Default: 4 + + Other Parameters + ---------------- + lifting_channel_ratio : Number, optional + 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, optional + 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, nn.Module], optional + 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 :mod:`neuralop.embeddings.GridEmbeddingND` for details). + - GridEmbedding2D: Uses this module directly for 2D cases. + - None: Does nothing. + Default: "grid" + non_linearity : nn.Module, optional + Non-Linear activation function module to use. Default: F.gelu + norm : Literal["ada_in", "group_norm", "instance_norm"], optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + complex_data : bool, optional + Whether the data is complex-valued. If True, initializes complex-valued modules. Default: False + use_channel_mlp : bool, optional + Whether to use an MLP layer after each FNO block. Default: True + channel_mlp_dropout : float, optional + Dropout parameter for ChannelMLP in FNO Block. Default: 0 + channel_mlp_expansion : float, optional + Expansion parameter for ChannelMLP in FNO Block. Default: 0.5 + channel_mlp_skip : Literal["linear", "identity", "soft-gating", None], optional + 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], optional + Type of skip connection to use in FNO layers. Options: "linear", "identity", "soft-gating", None. + Default: "linear" + conv_bias_kernel : int, optional + Kernel size for the local convolutional bias term used when ``fno_skip="linear"``. + ``1`` preserves the default pointwise bias term, while larger kernels add a + local convolution alongside the global spectral convolution. Default: 1 + resolution_scaling_factor : Union[Number, List[Number]], optional + 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]], optional + 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, optional + Precision mode in which to perform spectral convolution. + Options: "full", "half", "mixed". Default: "full". Default: "full" + stabilizer : str, optional + 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, ...], optional + 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, optional + Tensor factorization of the FNO layer weights to use. + Options: "None", "Tucker", "CP", "TT" + Other factorization methods supported by tltorch. Default: None + rank : float, optional + Tensor rank to use in factorization. Default: 1.0 + Set to float <1.0 when using TFNO (i.e. when factorization is not None). + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + implementation : str, optional + Implementation method for factorized tensors. + Options: "factorized", "reconstructed". Default: "factorized" + decomposition_kwargs : dict, optional + Extra kwargs for tensor decomposition (see `tltorch.FactorizedTensor`). Default: {} + separable : bool, optional + Whether to use a separable spectral convolution. Default: False + preactivation : bool, optional + Whether to compute FNO forward pass with resnet-style preactivation. Default: False + conv_module : nn.Module, optional + Module to use for FNOBlock's convolutions. Default: SpectralConv + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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 + -------- + >>> from neuralop.models import FNO + >>> model = FNO(n_modes=(12,12), in_channels=1, out_channels=1, hidden_channels=64) + >>> model + FNO( + (positional_embedding): GridEmbeddingND() + (fno_blocks): FNOBlocks( + (convs): SpectralConv( + (weight): ModuleList( + (0-3): 4 x DenseTensor(shape=torch.Size([64, 64, 12, 7]), rank=None) + ) + ) + ... torch.nn.Module printout truncated ... + + References + ---------- + .. [1] : + + Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential + Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895. + + """ + + def __init__( + self, + n_modes: Tuple[int, ...], + in_channels: int, + out_channels: int, + hidden_channels: int, + n_layers: int = 4, + lifting_channel_ratio: Number = 2, + projection_channel_ratio: Number = 2, + positional_embedding: Union[str, nn.Module] = "grid", + non_linearity: nn.Module = F.gelu, + norm: Literal["ada_in", "group_norm", "instance_norm"] = None, + norm_groups: int = 1, + complex_data: bool = False, + use_channel_mlp: bool = True, + channel_mlp_dropout: float = 0, + channel_mlp_expansion: float = 0.5, + channel_mlp_skip: Literal["linear", "identity", "soft-gating", None] = "soft-gating", + fno_skip: Literal["linear", "identity", "soft-gating", None] = "linear", + conv_bias_kernel: int = 1, + resolution_scaling_factor: Union[Number, List[Number]] = None, + domain_padding: Union[Number, List[Number]] = None, + fno_block_precision: str = "full", + stabilizer: str = None, + max_n_modes: Tuple[int, ...] = None, + factorization: str = None, + rank: float = 1.0, + fixed_rank_modes: bool = False, + implementation: str = "factorized", + decomposition_kwargs: dict = None, + separable: bool = False, + preactivation: bool = False, + conv_module: nn.Module = SpectralConv, + enforce_hermitian_symmetry: bool = True, + ): + if decomposition_kwargs is None: + decomposition_kwargs = {} + super().__init__() + self.n_dim = len(n_modes) + + # n_modes is a special property - see the class' property for underlying mechanism + # When updated, change should be reflected in fno blocks + self._n_modes = n_modes + + self.hidden_channels = hidden_channels + self.in_channels = in_channels + self.out_channels = out_channels + self.n_layers = n_layers + + # init lifting and projection channels using ratios w.r.t hidden channels + self.lifting_channel_ratio = lifting_channel_ratio + self.lifting_channels = int(lifting_channel_ratio * self.hidden_channels) + + self.projection_channel_ratio = projection_channel_ratio + self.projection_channels = int(projection_channel_ratio * self.hidden_channels) + + self.non_linearity = non_linearity + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.fno_skip = (fno_skip,) + self.conv_bias_kernel = conv_bias_kernel + self.channel_mlp_skip = (channel_mlp_skip,) + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + self.complex_data = complex_data + self.fno_block_precision = fno_block_precision + + ## Positional embedding + if positional_embedding == "grid": + spatial_grid_boundaries = [[0.0, 1.0]] * self.n_dim + self.positional_embedding = GridEmbeddingND( + in_channels=self.in_channels, + dim=self.n_dim, + grid_boundaries=spatial_grid_boundaries, + ) + elif isinstance(positional_embedding, GridEmbedding2D): + if self.n_dim == 2: + self.positional_embedding = positional_embedding + else: + raise ValueError( + f"Error: expected {self.n_dim}-d positional embeddings, got {positional_embedding}" + ) + elif isinstance(positional_embedding, GridEmbeddingND): + self.positional_embedding = positional_embedding + elif positional_embedding is None: + self.positional_embedding = None + else: + raise ValueError( + f"Error: tried to instantiate FNO positional embedding with {positional_embedding},\ + expected one of 'grid', GridEmbeddingND" + ) + + ## Domain padding + if domain_padding is not None and ( + (isinstance(domain_padding, list) and sum(domain_padding) > 0) + or (isinstance(domain_padding, (float, int)) and domain_padding > 0) + ): + self.domain_padding = DomainPadding( + domain_padding=domain_padding, + resolution_scaling_factor=resolution_scaling_factor, + ) + else: + self.domain_padding = None + + ## Resolution scaling factor + if resolution_scaling_factor is not None: + if isinstance(resolution_scaling_factor, (float, int)): + resolution_scaling_factor = [resolution_scaling_factor] * self.n_layers + self.resolution_scaling_factor = resolution_scaling_factor + + ## FNO blocks + self.fno_blocks = FNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=self.n_modes, + resolution_scaling_factor=resolution_scaling_factor, + use_channel_mlp=use_channel_mlp, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + stabilizer=stabilizer, + norm=norm, + norm_groups=norm_groups, + preactivation=preactivation, + fno_skip=fno_skip, + conv_bias_kernel=conv_bias_kernel, + channel_mlp_skip=channel_mlp_skip, + complex_data=complex_data, + max_n_modes=max_n_modes, + fno_block_precision=fno_block_precision, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + decomposition_kwargs=decomposition_kwargs, + conv_module=conv_module, + n_layers=n_layers, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ) + + ## Lifting layer + # if adding a positional embedding, add those channels to lifting + lifting_in_channels = self.in_channels + if self.positional_embedding is not None: + lifting_in_channels += self.n_dim + self.lifting = ChannelMLP( + in_channels=lifting_in_channels, + out_channels=self.hidden_channels, + hidden_channels=self.lifting_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + if self.complex_data: + self.lifting = ComplexValued(self.lifting) + + ## Projection layer + self.projection = ChannelMLP( + in_channels=self.hidden_channels, + out_channels=out_channels, + hidden_channels=self.projection_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + if self.complex_data: + self.projection = ComplexValued(self.projection) + + def forward(self, x, output_shape=None, **kwargs): + """FNO's forward pass + + 1. Applies optional positional encoding + + 2. Sends inputs through a lifting layer to a high-dimensional latent space + + 3. Applies optional domain padding to high-dimensional intermediate function representation + + 4. Applies `n_layers` Fourier/FNO layers in sequence (SpectralConvolution + skip connections, nonlinearity) + + 5. If domain padding was applied, domain padding is removed + + 6. Projection of intermediate function representation to the output channels + + Parameters + ---------- + x : tensor + input tensor + + output_shape : {tuple, tuple list, None}, default is None + Gives the option of specifying the exact output shape for odd shaped inputs. + + * If None, don't specify an output shape + + * If tuple, specifies the output-shape of the **last** FNO Block + + * If tuple list, specifies the exact output-shape of each FNO Block + """ + if kwargs: + warnings.warn( + f"FNO.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + if output_shape is None: + output_shape = [None] * self.n_layers + elif isinstance(output_shape, tuple): + output_shape = [None] * (self.n_layers - 1) + [output_shape] + + # append spatial pos embedding if set + if self.positional_embedding is not None: + x = self.positional_embedding(x) + + x = self.lifting(x) + + if self.domain_padding is not None: + x = self.domain_padding.pad(x) + + for layer_idx in range(self.n_layers): + x = self.fno_blocks(x, layer_idx, output_shape=output_shape[layer_idx]) + + if self.domain_padding is not None: + x = self.domain_padding.unpad(x) + + x = self.projection(x) + + return x + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + self.fno_blocks.n_modes = n_modes + self._n_modes = n_modes + + +def partialclass(new_name, cls, *args, **kwargs): + """Create a new class with different default values + + See the Spherical FNO class in neuralop/models/sfno.py for an example. + + Notes + ----- + An obvious alternative would be to use functools.partial + >>> new_class = partial(cls, **kwargs) + + The issue is twofold: + 1. the class doesn't have a name, so one would have to set it explicitly: + >>> new_class.__name__ = new_name + + 2. the new class will be a functools object and one cannot inherit from it. + + Instead, here, we define dynamically a new class, inheriting from the existing one. + """ + __init__ = partialmethod(cls.__init__, *args, **kwargs) + return type( + new_name, + (cls,), + { + "__init__": __init__, + "__doc__": cls.__doc__, + "forward": cls.forward, + }, + ) + + +class TFNO(FNO): + """Tucker Tensorized Fourier Neural Operator (TFNO). + + TFNO is an FNO with Tucker factorization enabled by default. + + It uses Tucker factorization of the weights, making the forward pass efficient by contracting + directly with the factors of the decomposition. + + This results in a fraction of the parameters of an equivalent dense FNO. + + Parameters + ---------- + factorization : str, optional + Tensor factorization method, by default "Tucker" + rank : float, optional + Tensor rank for factorization, by default 0.1. + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + + All other parameters are inherited from FNO with identical defaults. + See FNO class docstring for the complete parameter list. + + Examples + -------- + >>> from neuralop.models import TFNO + >>> # Create a TFNO model with default Tucker factorization + >>> model = TFNO(n_modes=(12, 12), in_channels=1, out_channels=1, hidden_channels=64) + >>> + >>> # Equivalent FNO model with explicit factorization: + >>> model = FNO(n_modes=(12, 12), in_channels=1, out_channels=1, hidden_channels=64, + ... factorization="Tucker", rank=0.1) + """ + + def __init__(self, *args, **kwargs): + kwargs.setdefault("factorization", "Tucker") + kwargs.setdefault("rank", 0.1) + super().__init__(*args, **kwargs) diff --git a/sources/neuraloperator/neuralop/models/fnogno.py b/sources/neuraloperator/neuralop/models/fnogno.py new file mode 100644 index 0000000000000000000000000000000000000000..063921c8190a2a95c2457abeb9d263fea0380b8d --- /dev/null +++ b/sources/neuraloperator/neuralop/models/fnogno.py @@ -0,0 +1,424 @@ +import torch +import torch.nn.functional as F + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +from .base_model import BaseModel + +from ..layers.channel_mlp import ChannelMLP +from ..layers.embeddings import SinusoidalEmbedding +from ..layers.fno_block import FNOBlocks +from ..layers.spectral_convolution import SpectralConv +from ..layers.gno_block import GNOBlock +from ..layers.gno_weighting_functions import dispatch_weighting_fn + + +class FNOGNO(BaseModel, name="FNOGNO"): + """FNOGNO: Fourier/Geometry Neural Operator - maps from a regular N-d grid to an arbitrary query point cloud. + + Parameters + ---------- + in_channels : int + Number of input channels. Determined by the problem. + out_channels : int + Number of output channels. Determined by the problem. + fno_n_modes : tuple, optional + Number of modes to keep along each spectral dimension of FNO block. + Must be larger enough but smaller than max_resolution//2 (Nyquist frequency). Default: (16, 16, 16) + fno_hidden_channels : int, optional + Number of hidden channels of FNO block. Default: 64 + fno_n_layers : int, optional + Number of FNO layers in the block. Default: 4 + + projection_channel_ratio : int, optional + Ratio of pointwise projection channels in the final ChannelMLP to fno_hidden_channels. + The number of projection channels in the final ChannelMLP is computed by + projection_channel_ratio * fno_hidden_channels (i.e. default 256). Default: 4 + gno_coord_dim : int, optional + Dimension of coordinate space where GNO is computed. Determined by the problem. Default: 3 + gno_pos_embed_type : Literal["transformer", "nerf"], optional + Type of optional sinusoidal positional embedding to use in GNOBlock. Default: "transformer" + gno_radius : float, optional + Radius parameter to construct graph. Default: 0.033 + Larger radius means more neighboors so more global interactions, but larger computational cost. + gno_transform_type : str, optional + Type of kernel integral transform to apply in GNO. + Kernel k(x,y): parameterized as ChannelMLP MLP integrated over a neighborhood of x. + + Options: + - "linear_kernelonly": Integrand is k(x, y) + - "linear": Integrand is k(x, y) * f(y) + - "nonlinear_kernelonly": Integrand is k(x, y, f(y)) + - "nonlinear": Integrand is k(x, y, f(y)) * f(y) + Default: "linear" + gno_weighting_function : Literal["half_cos", "bump", "quartic", "quadr", "octic"], optional + Choice of weighting function to use in the output GNO for Mollified Graph Neural Operator-based models. + See neuralop.layers.gno_weighting_functions for more details. Default: None + gno_weight_function_scale : float, optional + Factor by which to scale weights from GNO weighting function. If gno_weighting_function is None, this is not used. Default: 1 + gno_embed_channels : int, optional + Dimension of optional per-channel embedding to use in GNOBlock. Default: 32 + gno_embed_max_positions : int, optional + Max positions of optional per-channel embedding to use in GNOBlock. If gno_pos_embed_type != 'transformer', value is unused. Default: 10000 + gno_channel_mlp_hidden_layers : list, optional + Dimension of hidden ChannelMLP layers of GNO. Default: [512, 256] + gno_channel_mlp_non_linearity : nn.Module, optional + Nonlinear activation function between layers. Default: F.gelu + gno_use_open3d : bool, optional + Whether to use Open3D functionality. If False, uses simple fallback neighbor search. Default: True + gno_use_torch_scatter : bool, optional + Whether to use torch-scatter to perform grouped reductions in the IntegralTransform. + If False, uses native Python reduction in neuralop.layers.segment_csr. + + .. warning:: + torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch, + so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency` + for more information. + + Default: True + gno_batched : bool, optional + Whether to use IntegralTransform/GNO layer in "batched" mode. If False, sets batched=False. Default: False + fno_lifting_channel_ratio : int, optional + Ratio of lifting channels to FNO hidden channels. Default: 4 + fno_resolution_scaling_factor : float, optional + Factor by which to rescale output predictions in the original domain. Default: None + fno_block_precision : str, optional + Data precision to compute within FNO block. Options: "full", "half", "mixed". Default: "full" + fno_use_channel_mlp : bool, optional + Whether to use a ChannelMLP layer after each FNO block. Default: True + fno_channel_mlp_dropout : float, optional + Dropout parameter of above ChannelMLP. Default: 0 + fno_channel_mlp_expansion : float, optional + Expansion parameter of above ChannelMLP. Default: 0.5 + fno_non_linearity : nn.Module, optional + Nonlinear activation function between each FNO layer. Default: F.gelu + fno_stabilizer : nn.Module, optional + By default None, otherwise tanh is used before FFT in the FNO block. Default: None + fno_norm : str, optional + Normalization layer to use in FNO. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + fno_norm_groups : int, optional + Number of groups for GroupNorm in FNO, by default 1 + fno_ada_in_features : int, optional + If an adaptive mesh is used, number of channels of its positional embedding. Default: None + fno_ada_in_dim : int, optional + Dimensions of above FNO adaptive mesh. Default: 1 + fno_preactivation : bool, optional + Whether to use ResNet-style preactivation. Default: False + fno_skip : str, optional + Type of skip connection to use. Options: "linear", "identity", "soft-gating", None. Default: "linear" + fno_channel_mlp_skip : str, optional + Type of skip connection to use in the FNO. + + Options: + - "linear": Conv layer + - "soft-gating": Weights the channels of the input + - "identity": nn.Identity + - None: No skip connection + + Default: "soft-gating" + fno_separable : bool, optional + Whether to use a depthwise separable spectral convolution. Default: False + fno_factorization : str, optional + Tensor factorization of the parameters weight to use. Options: "tucker", "tt", "cp", None. Default: None + fno_rank : float, optional + Rank of the tensor factorization of the Fourier weights. Default: 1.0 + fno_fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + fno_implementation : str, optional + If factorization is not None, forward mode to use. + + Options: + - "reconstructed": The full weight tensor is reconstructed from the factorization and used for the forward pass + - "factorized": The input is directly contracted with the factors of the decomposition + + Default: "factorized" + fno_decomposition_kwargs : dict, optional + Additional parameters to pass to the tensor decomposition. Default: {} + fno_conv_module : nn.Module, optional + Spectral convolution module to use. Default: SpectralConv + fno_enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data in the FNO branch. Only used in :class:`SpectralConv`; + 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. + """ + + def __init__( + self, + in_channels, + out_channels, + projection_channel_ratio=4, + gno_coord_dim=3, + gno_pos_embed_type="transformer", + gno_transform_type="linear", + fno_n_modes=(16, 16, 16), + fno_hidden_channels=64, + fno_lifting_channel_ratio=4, + fno_n_layers=4, + # Other GNO params + gno_embed_channels=32, + gno_embed_max_positions=10000, + gno_radius=0.033, + gno_weighting_function=None, + gno_weight_function_scale=1.0, + gno_channel_mlp_hidden_layers=[512, 256], + gno_channel_mlp_non_linearity=F.gelu, + gno_use_open3d=True, + gno_use_torch_scatter=True, + gno_batched=False, + # Other FNO params + fno_resolution_scaling_factor=None, + fno_block_precision="full", + fno_use_channel_mlp=True, + fno_channel_mlp_dropout=0, + fno_channel_mlp_expansion=0.5, + fno_non_linearity=F.gelu, + fno_stabilizer=None, + fno_norm=None, + fno_norm_groups=1, + fno_ada_in_features=None, + fno_ada_in_dim=1, + fno_preactivation=False, + fno_skip="linear", + fno_channel_mlp_skip="soft-gating", + fno_separable=False, + fno_factorization=None, + fno_rank=1.0, + fno_fixed_rank_modes=False, + fno_implementation="factorized", + fno_decomposition_kwargs=dict(), + fno_conv_module=SpectralConv, + fno_enforce_hermitian_symmetry=True, + ): + super().__init__() + + self.gno_coord_dim = gno_coord_dim + if self.gno_coord_dim != 3 and gno_use_open3d: + warnings.warn( + f"GNO expects {self.gno_coord_dim}-d data but Open3d expects 3-d data", + UserWarning, + stacklevel=2, + ) + + self.in_coord_dim = len(fno_n_modes) + if self.in_coord_dim != self.gno_coord_dim: + warnings.warn( + f"FNO expects {self.in_coord_dim}-d data while GNO expects {self.gno_coord_dim}-d data", + UserWarning, + stacklevel=2, + ) + + # these lists contain the interior dimensions of the input + # in order to reshape without explicitly providing dims + self.in_coord_dim_forward_order = list(range(self.in_coord_dim)) + self.in_coord_dim_reverse_order = [ + j + 1 for j in self.in_coord_dim_forward_order + ] + + self.gno_batched = gno_batched # used in forward call to GNO + + # if batched, we must account for the extra batch dim + # which causes previous dims to be incremented by 1 + if self.gno_batched: + self.in_coord_dim_forward_order = [ + j + 1 for j in self.in_coord_dim_forward_order + ] + self.in_coord_dim_reverse_order = [ + j + 1 for j in self.in_coord_dim_reverse_order + ] + + if fno_norm == "ada_in": + if fno_ada_in_features is not None: + self.adain_pos_embed = SinusoidalEmbedding( + in_channels=fno_ada_in_dim, + num_frequencies=fno_ada_in_features, + embedding_type="transformer", + ) + # if ada_in positional embedding is provided, set the input dimension + # of the ada_in norm to the output channels of positional embedding + self.ada_in_dim = self.adain_pos_embed.out_channels + else: + self.ada_in_dim = fno_ada_in_dim + else: + self.adain_pos_embed = None + self.ada_in_dim = None + + # Create lifting for FNOBlock separately + fno_lifting_channels = fno_lifting_channel_ratio * fno_hidden_channels + self.lifting = ChannelMLP( + in_channels=in_channels + self.in_coord_dim, + hidden_channels=fno_lifting_channels, + out_channels=fno_hidden_channels, + n_layers=3, + ) + + self.fno_hidden_channels = fno_hidden_channels + self.fno_blocks = FNOBlocks( + n_modes=fno_n_modes, + in_channels=fno_hidden_channels, + out_channels=fno_hidden_channels, + n_layers=fno_n_layers, + resolution_scaling_factor=fno_resolution_scaling_factor, + fno_block_precision=fno_block_precision, + use_channel_mlp=fno_use_channel_mlp, + channel_mlp_expansion=fno_channel_mlp_expansion, + channel_mlp_dropout=fno_channel_mlp_dropout, + non_linearity=fno_non_linearity, + stabilizer=fno_stabilizer, + norm=fno_norm, + norm_groups=fno_norm_groups, + ada_in_features=self.ada_in_dim, + preactivation=fno_preactivation, + fno_skip=fno_skip, + channel_mlp_skip=fno_channel_mlp_skip, + separable=fno_separable, + factorization=fno_factorization, + rank=fno_rank, + fixed_rank_modes=fno_fixed_rank_modes, + implementation=fno_implementation, + decomposition_kwargs=fno_decomposition_kwargs, + conv_module=fno_conv_module, + enforce_hermitian_symmetry=fno_enforce_hermitian_symmetry, + ) + + self.gno_radius = gno_radius + + if gno_weighting_function is not None: + weight_fn = dispatch_weighting_fn( + gno_weighting_function, + sq_radius=gno_radius**2, + scale=gno_weight_function_scale, + ) + else: + weight_fn = None + + self.gno = GNOBlock( + in_channels=fno_hidden_channels, + out_channels=fno_hidden_channels, + radius=gno_radius, + weighting_fn=weight_fn, + coord_dim=self.gno_coord_dim, + pos_embedding_type=gno_pos_embed_type, + pos_embedding_channels=gno_embed_channels, + pos_embedding_max_positions=gno_embed_max_positions, + channel_mlp_layers=gno_channel_mlp_hidden_layers, + channel_mlp_non_linearity=gno_channel_mlp_non_linearity, + transform_type=gno_transform_type, + use_open3d_neighbor_search=gno_use_open3d, + use_torch_scatter_reduce=gno_use_torch_scatter, + ) + + projection_channels = projection_channel_ratio * fno_hidden_channels + self.projection = ChannelMLP( + in_channels=fno_hidden_channels, + out_channels=out_channels, + hidden_channels=projection_channels, + n_layers=2, + n_dim=1, + non_linearity=fno_non_linearity, + ) + + # out_p : (n_out, gno_coord_dim) + # in_p : (n_1, n_2, ..., n_k, k) + # if batched shape is the same because this is just geometry + # that remains constant across the entire batch + # f : (n_1, n_2, ..., n_k, in_channels) + # if batched, (b, n_1, n_2, ..., n_k, in_channels) + # ada_in : (fno_ada_in_dim, ) + + # returns: (fno_hidden_channels, n_1, n_2, ...) + def latent_embedding(self, in_p, f, ada_in=None): + if self.gno_batched: + batch_size = f.shape[0] + # repeat in_p along the batch dimension for latent embedding + in_p = in_p.repeat([batch_size] + [1] * (in_p.ndim)) + in_p = torch.cat((f, in_p), dim=-1) + + if self.gno_batched: + # shape: (b, k, n_1, n_2, ... n_k) + in_p = in_p.permute(0, -1, *self.in_coord_dim_forward_order) + else: + in_p = in_p.permute(-1, *self.in_coord_dim_forward_order).unsqueeze(0) + + # Update Ada IN embedding + if ada_in is not None: + if self.adain_pos_embed is not None: + ada_in_embed = self.adain_pos_embed(ada_in.unsqueeze(0)).squeeze(0) + else: + ada_in_embed = ada_in + + self.fno_blocks.set_ada_in_embeddings(ada_in_embed) + + # Apply FNO blocks + + in_p = self.lifting(in_p) + for layer_idx in range(self.fno_blocks.n_layers): + in_p = self.fno_blocks(in_p, layer_idx) + + if self.gno_batched: + return in_p + else: + return in_p.squeeze(0) + + def integrate_latent(self, in_p, out_p, latent_embed): + """ + Compute integration region for each output point + """ + + # (n_1*n_2*..., fno_hidden_channels) + # if batched, (b, n1*n2*..., fno_hidden_channels) + + if self.gno_batched: + batch_size = latent_embed.shape[0] + latent_embed = latent_embed.permute( + 0, *self.in_coord_dim_reverse_order, 1 + ).reshape((batch_size, -1, self.fno_hidden_channels)) + else: + latent_embed = latent_embed.permute( + *self.in_coord_dim_reverse_order, 0 + ).reshape((-1, self.fno_hidden_channels)) + + # (n_out, fno_hidden_channels) + + out = self.gno( + y=in_p.reshape(-1, in_p.shape[-1]), + x=out_p, + f_y=latent_embed, + ) + + # if self.gno is variable and not batched + if out.ndim == 2: + out = out.unsqueeze(0) + out = out.permute(0, 2, 1) # b, c, n_out + + # Project pointwise to out channels + out = self.projection(out) + + if self.gno_batched: + out = out.permute(0, 2, 1) + else: + out = out.squeeze(0).permute(1, 0) + + return out + + def forward(self, in_p, out_p, f, ada_in=None, **kwargs): + if kwargs: + warnings.warn( + f"FNOGNO.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + # Compute latent space embedding + latent_embed = self.latent_embedding(in_p=in_p, f=f, ada_in=ada_in) + # Integrate latent space + out = self.integrate_latent(in_p=in_p, out_p=out_p, latent_embed=latent_embed) + + return out diff --git a/sources/neuraloperator/neuralop/models/gino.py b/sources/neuraloperator/neuralop/models/gino.py new file mode 100644 index 0000000000000000000000000000000000000000..483fada108f26c6e9aad40f508981fdef21e947d --- /dev/null +++ b/sources/neuraloperator/neuralop/models/gino.py @@ -0,0 +1,562 @@ +from functools import partial +import torch +import torch.nn.functional as F +import time + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +from .base_model import BaseModel + +from ..layers.channel_mlp import ChannelMLP +from ..layers.embeddings import SinusoidalEmbedding +from ..layers.fno_block import FNOBlocks +from ..layers.spectral_convolution import SpectralConv +from ..layers.gno_block import GNOBlock +from ..layers.gno_weighting_functions import dispatch_weighting_fn + + +class GINO(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 for use in a Mollified Graph Neural Operator scheme, as introduced in [2]_. + + Parameters + ---------- + 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, optional + Number of modes along each dimension to use in FNO. Default: (16, 16, 16) + Must be larger enough but smaller than max_resolution//2 (Nyquist frequency) on the latent grid + fno_hidden_channels : int, optional + Hidden channels for use in FNO. Default: 64 + fno_n_layers : int, optional + Number of layers in FNO. Default: 4 + latent_feature_channels : int, optional + Number of channels in optional latent feature map to concatenate onto latent embeddings + before the FNO's forward pass. Default: None + projection_channel_ratio : int, optional + Ratio of pointwise projection channels in the final ChannelMLP to fno_hidden_channels. + The number of projection channels in the final ChannelMLP is computed by + projection_channel_ratio * fno_hidden_channels (i.e. default 256). Default: 4 + gno_coord_dim : int, optional + Geometric dimension of input/output queries. Determined by the problem. Default: 3 + in_gno_radius : float, optional + Radius in input space for GNO neighbor search. Default: 0.033 + Larger radius means more neighboors so more global interactions, but larger computational cost. + out_gno_radius : float, optional + Radius in output space for GNO neighbor search. Default: 0.033 + Larger radius means more neighboors so more global interactions, but larger computational cost. + gno_weighting_function : Literal["half_cos", "bump", "quartic", "quadr", "octic"], optional + Choice of weighting function to use in the output GNO for Mollified Graph Neural Operator-based models. + See neuralop.layers.gno_weighting_functions for more details. Default: None + gno_weight_function_scale : float, optional + Factor by which to scale weights from GNO weighting function. + If gno_weighting_function is None, this is not used. Default: 1 + in_gno_transform_type : str, optional + Transform type parameter for input GNO. Default: "linear" + See neuralop.layers.gno_block for more details. + See neuralop.layers.gno_block for more details. + out_gno_transform_type : str, optional + Transform type parameter for output GNO. + Options: "linear", "nonlinear", "nonlinear_kernelonly". Default: "linear" + See neuralop.layers.gno_block for more details. + Type of optional sinusoidal positional embedding to use in input GNOBlock. Default: "transformer" + Type of optional sinusoidal positional embedding to use in input GNOBlock. + Options: "transformer", "nerf". Default: "transformer" + Type of optional sinusoidal positional embedding to use in output GNOBlock. Default: "transformer" + fno_in_channels : int, optional + Number of input channels for FNO. Default: 3 + fno_lifting_channel_ratio : int, optional + Ratio of lifting channels to fno_hidden_channels. + The number of lifting channels in the lifting block of the FNO is + fno_lifting_channel_ratio * hidden_channels (i.e. default 128). Default: 2 + gno_embed_channels : int, optional + Dimension of optional per-channel embedding to use in GNOBlock. Default: 32 + gno_embed_max_positions : int, optional + Max positions of optional per-channel embedding to use in GNOBlock. + If gno_pos_embed_type != 'transformer', this is not used. Default: 10000 + in_gno_channel_mlp_hidden_layers : list, optional + Widths of hidden layers in input GNO. Default: [80, 80, 80] + out_gno_channel_mlp_hidden_layers : list, optional + Widths of hidden layers in output GNO. Default: [512, 256] + gno_channel_mlp_non_linearity : nn.Module, optional + Nonlinearity to use in GNO ChannelMLP. Default: F.gelu + gno_use_open3d : bool, optional + Whether to use Open3D neighbor search. + If False, uses pure-PyTorch fallback neighbor search. Default: True + gno_use_torch_scatter : bool, optional + Whether to use torch-scatter to perform grouped reductions in the IntegralTransform. + If False, uses native Python reduction in neuralop.layers.segment_csr. Default: True + + .. warning:: + torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch, + so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency` + for more information. + out_gno_tanh : bool, optional + Whether to use tanh to stabilize outputs of the output GNO. Default: False + fno_resolution_scaling_factor : float, optional + Factor by which to scale output of FNO. Default: None + fno_block_precision : str, optional + Data precision to compute within FNO block. Options: "full", "half", "mixed". Default: "full" + fno_use_channel_mlp : bool, optional + Whether to use a ChannelMLP layer after each FNO block. Default: True + fno_channel_mlp_dropout : float, optional + Dropout parameter of above ChannelMLP. Default: 0 + fno_channel_mlp_expansion : float, optional + Expansion parameter of above ChannelMLP. Default: 0.5 + fno_non_linearity : nn.Module, optional + Nonlinear activation function between each FNO layer. Default: F.gelu + fno_stabilizer : nn.Module, optional + By default None, otherwise tanh is used before FFT in the FNO block. Default: None + fno_norm : str, optional + Normalization layer to use in FNO. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + fno_norm_groups : int, optional + Number of groups for GroupNorm in FNO, by default 1 + fno_ada_in_features : int, optional + If an adaptive mesh is used, number of channels of its positional embedding. + If None, adaptive mesh embedding is not used. Default: 4 + fno_ada_in_dim : int, optional + Dimensions of above FNO adaptive mesh. Default: 1 + fno_preactivation : bool, optional + Whether to use ResNet-style preactivation. Default: False + fno_skip : str, optional + Type of skip connection to use. Options: "linear", "identity", "soft-gating", None. Default: "linear" + fno_channel_mlp_skip : str, optional + Type of skip connection to use in the FNO. + Options: "linear", "identity", "soft-gating", None. Default: "soft-gating" + fno_separable : bool, optional + Whether to use a separable spectral convolution. Default: False + fno_factorization : str, optional + Tensor factorization of the parameters weight to use. + Options: "tucker", "tt", "cp", None. Default: None + fno_rank : float, optional + Rank of the tensor factorization of the Fourier weights. Default: 1.0 + Set to float <1.0 when using TFNO (i.e. when factorization is not None). + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + fno_fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + fno_implementation : str, optional + If factorization is not None, forward mode to use. + Options: "reconstructed", "factorized". Default: "factorized" + fno_decomposition_kwargs : dict, optional + Additional parameters to pass to the tensor decomposition. Default: {} + fno_conv_module : nn.Module, optional + Spectral convolution module to use. Default: SpectralConv + fno_enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data in the FNO branch. Only used in :class:`SpectralConv`; + 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. + + 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, + https://proceedings.neurips.cc/paper_files/paper/2023/hash/70518ea42831f02afc3a2828993935ad-Abstract-Conference.html + .. [2] : Lin, R. et al. Placeholder reference for Mollified Graph Neural Operators. + """ + + def __init__( + self, + in_channels, + out_channels, + latent_feature_channels=None, + projection_channel_ratio=4, + gno_coord_dim=3, + in_gno_radius=0.033, + out_gno_radius=0.033, + in_gno_transform_type="linear", + out_gno_transform_type="linear", + gno_weighting_function=None, + gno_weight_function_scale=1, + in_gno_pos_embed_type="transformer", + out_gno_pos_embed_type="transformer", + fno_in_channels=3, + fno_n_modes=(16, 16, 16), + fno_hidden_channels=64, + fno_lifting_channel_ratio=2, + fno_n_layers=4, + # Other GNO Params + gno_embed_channels=32, + gno_embed_max_positions=10000, + in_gno_channel_mlp_hidden_layers=[80, 80, 80], + out_gno_channel_mlp_hidden_layers=[512, 256], + gno_channel_mlp_non_linearity=F.gelu, + gno_use_open3d=True, + gno_use_torch_scatter=True, + out_gno_tanh=None, + # Other FNO Params + fno_resolution_scaling_factor=None, + fno_block_precision="full", + fno_use_channel_mlp=True, + fno_channel_mlp_dropout=0, + fno_channel_mlp_expansion=0.5, + fno_non_linearity=F.gelu, + fno_stabilizer=None, + fno_norm=None, + fno_norm_groups=1, + fno_ada_in_features=4, + fno_ada_in_dim=1, + fno_preactivation=False, + fno_skip="linear", + fno_channel_mlp_skip="soft-gating", + fno_separable=False, + fno_factorization=None, + fno_rank=1.0, + fno_fixed_rank_modes=False, + fno_implementation="factorized", + fno_decomposition_kwargs=dict(), + fno_conv_module=SpectralConv, + fno_enforce_hermitian_symmetry=True, + ): + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.latent_feature_channels = latent_feature_channels + self.gno_coord_dim = gno_coord_dim + self.fno_hidden_channels = fno_hidden_channels + + self.lifting_channels = fno_lifting_channel_ratio * fno_hidden_channels + + # If the input GNO performs a nonlinear kernel, the GNO's output + # features must be the same dimension as its input. + # otherwise the kernel's MLP will perform a lifting operation to + # lift the inputs to ``fno_in_channels`` channels + if in_gno_transform_type in ["nonlinear", "nonlinear_kernelonly"]: + in_gno_out_channels = self.in_channels + else: + in_gno_out_channels = fno_in_channels + + # The actual input channels to the FNO are computed here. + self.fno_in_channels = in_gno_out_channels + + if latent_feature_channels is not None: + self.fno_in_channels += latent_feature_channels + + if self.gno_coord_dim != 3 and gno_use_open3d: + warnings.warn( + f'GNO expects {self.gno_coord_dim}-d data but Open3d expects 3-d data', + UserWarning, + stacklevel=2, + ) + gno_use_open3d = False + + self.in_coord_dim = len(fno_n_modes) + self.gno_out_coord_dim = len(fno_n_modes) # gno output and fno will use same dimensions + if self.in_coord_dim != self.gno_coord_dim: + warnings.warn( + f'FNO expects {self.in_coord_dim}-d data while input GNO expects {self.gno_coord_dim}-d data', + UserWarning, + stacklevel=2, + ) + + self.in_coord_dim_forward_order = list(range(self.in_coord_dim)) + + # tensor indices starting at 2 to permute everything after channel and batch dims + self.in_coord_dim_reverse_order = [j + 2 for j in self.in_coord_dim_forward_order] + + self.fno_norm = fno_norm + if self.fno_norm == "ada_in": + if fno_ada_in_features is not None and out_gno_pos_embed_type is not None: + self.adain_pos_embed = SinusoidalEmbedding( + in_channels=fno_ada_in_dim, + num_frequencies=fno_ada_in_features, + max_positions=10000, + embedding_type=out_gno_pos_embed_type, + ) + self.ada_in_dim = self.adain_pos_embed.out_channels + else: + self.ada_in_dim = fno_ada_in_dim + self.adain_pos_embed = None + else: + self.adain_pos_embed = None + self.ada_in_dim = None + + self.in_gno_radius = in_gno_radius + self.out_gno_radius = out_gno_radius + + self.out_gno_tanh = out_gno_tanh + + ### input GNO + # input to the first GNO ChannelMLP: `x` pos encoding, + # `y` (integrand) pos encoding, potentially `f_y` + + self.gno_in = GNOBlock( + in_channels=in_channels, + out_channels=in_gno_out_channels, + coord_dim=self.gno_coord_dim, + pos_embedding_type=in_gno_pos_embed_type, + pos_embedding_channels=gno_embed_channels, + pos_embedding_max_positions=gno_embed_max_positions, + radius=in_gno_radius, + reduction="mean", + weighting_fn=None, + channel_mlp_layers=in_gno_channel_mlp_hidden_layers, + channel_mlp_non_linearity=gno_channel_mlp_non_linearity, + transform_type=in_gno_transform_type, + use_torch_scatter_reduce=gno_use_torch_scatter, + use_open3d_neighbor_search=gno_use_open3d, + ) + + ### Lifting layer before FNOBlocks + self.lifting = ChannelMLP( + in_channels=self.fno_in_channels, + hidden_channels=self.lifting_channels, + out_channels=fno_hidden_channels, + n_layers=2, + ) # CHANGED RECENTLY FOR THIS PAPER + + ### FNOBlocks in latent space + # input: `in_p` intermediate embeddings, + # possibly concatenated feature channels `latent_features` + self.fno_blocks = FNOBlocks( + n_modes=fno_n_modes, + in_channels=fno_hidden_channels, + out_channels=fno_hidden_channels, + n_layers=fno_n_layers, + resolution_scaling_factor=fno_resolution_scaling_factor, + fno_block_precision=fno_block_precision, + use_channel_mlp=fno_use_channel_mlp, + channel_mlp_expansion=fno_channel_mlp_expansion, + channel_mlp_dropout=fno_channel_mlp_dropout, + non_linearity=fno_non_linearity, + stabilizer=fno_stabilizer, + norm=fno_norm, + norm_groups=fno_norm_groups, + ada_in_features=self.ada_in_dim, + preactivation=fno_preactivation, + fno_skip=fno_skip, + channel_mlp_skip=fno_channel_mlp_skip, + separable=fno_separable, + factorization=fno_factorization, + rank=fno_rank, + fixed_rank_modes=fno_fixed_rank_modes, + implementation=fno_implementation, + decomposition_kwargs=fno_decomposition_kwargs, + conv_module=fno_conv_module, + enforce_hermitian_symmetry=fno_enforce_hermitian_symmetry, + ) + + ### output GNO + if gno_weighting_function is not None: # sq radius**2? + weight_fn = dispatch_weighting_fn( + gno_weighting_function, + sq_radius=out_gno_radius**2, + scale=gno_weight_function_scale, + ) + else: + weight_fn = None + self.gno_out = GNOBlock( + in_channels=fno_hidden_channels, # number of channels in f_y + out_channels=fno_hidden_channels, + coord_dim=self.gno_coord_dim, + radius=self.out_gno_radius, + reduction="sum", + weighting_fn=weight_fn, + pos_embedding_type=out_gno_pos_embed_type, + pos_embedding_channels=gno_embed_channels, + pos_embedding_max_positions=gno_embed_max_positions, + channel_mlp_layers=out_gno_channel_mlp_hidden_layers, + channel_mlp_non_linearity=gno_channel_mlp_non_linearity, + transform_type=out_gno_transform_type, + use_torch_scatter_reduce=gno_use_torch_scatter, + use_open3d_neighbor_search=gno_use_open3d, + ) + + projection_channels = projection_channel_ratio * fno_hidden_channels + self.projection = ChannelMLP( + in_channels=fno_hidden_channels, + out_channels=self.out_channels, + hidden_channels=projection_channels, + n_layers=2, + n_dim=1, + non_linearity=fno_non_linearity, + ) + + # returns: (fno_hidden_channels, n_1, n_2, ...) + def latent_embedding(self, in_p, ada_in=None): + # in_p : (batch, n_1 , ... , n_k, in_channels + k) + # ada_in : (fno_ada_in_dim, ) + + # permute (b, n_1, ..., n_k, c) -> (b,c, n_1,...n_k) + in_p = in_p.permute(0, len(in_p.shape) - 1, *list(range(1,len(in_p.shape)-1))) + #Update Ada IN embedding + if ada_in is not None: + if ada_in.ndim == 2: + ada_in = ada_in.squeeze(0) + if self.adain_pos_embed is not None: + ada_in_embed = self.adain_pos_embed(ada_in.unsqueeze(0)).squeeze(0) + else: + ada_in_embed = ada_in + if self.fno_norm == "ada_in": + self.fno_blocks.set_ada_in_embeddings(ada_in_embed) + + # Apply FNO blocks + in_p = self.lifting(in_p) + + for idx in range(self.fno_blocks.n_layers): + in_p = self.fno_blocks(in_p, idx) + + return in_p + + def forward( + self, + input_geom, + latent_queries, + output_queries, + x=None, + latent_features=None, + ada_in=None, + **kwargs, + ): + if kwargs: + warnings.warn( + f"GINO.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + """The GINO's forward call: + Input GNO --> FNOBlocks --> output GNO + projection to output queries. + + .. note :: + GINO currently supports batching **only in cases where the geometry of + inputs and outputs is shared across the entire batch**. Inputs can have a batch dim + in ``x`` and ``latent_features``, but it must be shared for both. + + Parameters + ---------- + input_geom : torch.Tensor + input domain coordinate mesh + shape (1, n_in, gno_coord_dim) + latent_queries : torch.Tensor + latent geometry on which to compute FNO latent embeddings + a grid on [0,1] x [0,1] x .... + shape (1, n_gridpts_1, .... n_gridpts_n, gno_coord_dim) + output_queries : torch.Tensor | dict[torch.Tensor] + points at which to query the final GNO layer to get output. + + shape (1, n_out, gno_coord_dim) per tensor. + + * if a tensor, the model will output a tensor. + + * if a dict of tensors, the model will return a dict of outputs, so + that ``output[key]`` corresponds to the model queried at + ``output_queries[key]``. + x : torch.Tensor, optional + input function a defined on the input domain `input_geom` + shape (batch, n_in, in_channels). Default None + latent_features : torch.Tensor, optional + optional feature map to concatenate onto latent embedding + before being passed into the latent FNO, default None + if `latent_feature_channels` is set, must be passed + ada_in : torch.Tensor, optional + adaptive scalar instance parameter, defaults to None + + Returns + ------- + out : torch.Tensor | dict[torch.Tensor] + Function over the output query coordinates + * tensor if if ``output_queries`` is a tensor + * dict if if ``output_queries`` is a dict + """ + + # Ensure input functions on the input geom and latent geom + # have compatible batch sizes + if x is None: + batch_size = 1 + else: + batch_size = x.shape[0] + + if latent_features is not None: + assert ( + self.latent_feature_channels is not None + ), "if passing latent features, latent_feature_channels must be set." + assert latent_features.shape[-1] == self.latent_feature_channels + + # batch, n_gridpts_1, .... n_gridpts_n, gno_coord_dim + assert ( + latent_features.ndim == self.gno_coord_dim + 2 + ), f"Latent features must be of shape (batch, n_gridpts_1, ...n_gridpts_n, gno_coord_dim), got {latent_features.shape}" + # latent features must have the same shape (except channels) as latent_queries + if latent_features.shape[0] != batch_size: + if latent_features.shape[0] == 1: + latent_features = latent_features.repeat(batch_size, *[1]*(latent_features.ndim-1)) + + input_geom = input_geom.squeeze(0) + latent_queries = latent_queries.squeeze(0) + + # Pass through input GNOBlock + in_p = self.gno_in( + y=input_geom, x=latent_queries.view((-1, latent_queries.shape[-1])), f_y=x + ) + + grid_shape = latent_queries.shape[:-1] # disregard positional encoding dim + + # shape (batch_size, grid1, ...gridn, -1) + in_p = in_p.view((batch_size, *grid_shape, -1)) + + if latent_features is not None: + in_p = torch.cat((in_p, latent_features), dim=-1) + # take apply fno in latent space + latent_embed = self.latent_embedding(in_p=in_p, ada_in=ada_in) + + # Integrate latent space to output queries + # latent_embed shape (b, c, n_1, n_2, ..., n_k) + batch_size = latent_embed.shape[0] + # permute to (b, n_1, n_2, ...n_k, c) + # then reshape to (b, n_1 * n_2 * ...n_k, out_channels) + latent_embed = latent_embed.permute(0, *self.in_coord_dim_reverse_order, 1).reshape(batch_size, -1, self.fno_hidden_channels) + + if self.out_gno_tanh in ["latent_embed", "both"]: + latent_embed = torch.tanh(latent_embed) + + # integrate over the latent space + # if output queries is a dict, query the output gno separately + # with each tensor of query points + if isinstance(output_queries, dict): + out = {} + for key, out_p in output_queries.items(): + out_p = out_p.squeeze(0) + + sub_output = self.gno_out( + y=latent_queries.reshape((-1, latent_queries.shape[-1])), + x=out_p, + f_y=latent_embed, + ) + sub_output = sub_output.permute(0, 2, 1) + + # Project pointwise to out channels + # (b, n_in, out_channels) + sub_output = self.projection(sub_output).permute(0, 2, 1) + + out[key] = sub_output + else: + output_queries = output_queries.squeeze(0) + + # latent queries is of shape (d_1 x d_2 x... d_n x n), reshape to n_out x n + out = self.gno_out( + y=latent_queries.reshape((-1, latent_queries.shape[-1])), + x=output_queries, + f_y=latent_embed, + ) + out = out.permute(0, 2, 1) + + # Project pointwise to out channels + # (b, n_in, out_channels) + out = self.projection(out).permute(0, 2, 1) + + return out diff --git a/sources/neuraloperator/neuralop/models/local_no.py b/sources/neuraloperator/neuralop/models/local_no.py new file mode 100644 index 0000000000000000000000000000000000000000..233102aa017e0ff7baed8b80abb9f71c5811878b --- /dev/null +++ b/sources/neuraloperator/neuralop/models/local_no.py @@ -0,0 +1,455 @@ +from typing import Tuple, List, Union + +Number = Union[float, int] + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + + +from ..layers.embeddings import GridEmbeddingND, GridEmbedding2D +from ..layers.spectral_convolution import SpectralConv +from ..layers.padding import DomainPadding +from neuralop.layers.local_no_block import LocalNOBlocks +from ..layers.channel_mlp import ChannelMLP +from ..layers.complex import ComplexValued +from .base_model import BaseModel + + +class LocalNO(BaseModel, name="LocalNO"): + """N-Dimensional Local Fourier Neural Operator. The LocalNO shares + its forward pass and architecture with the standard FNO, with the key difference + that its Fourier convolution layers are replaced with LocalNOBlocks that place + differential kernel layers and local integral layers in parallel to its + Fourier layers as detailed in [1]_. + + Parameters + ---------- + n_modes : Tuple[int] + Number of modes to keep in Fourier Layer, along each dimension. + The dimensionality of the Local NO is inferred from len(n_modes). + No default value (required parameter). + 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 Local NO (i.e. number of channels). + This significantly affects the number of parameters of the LocalNO. + 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. + default_in_shape : Tuple[int] + Default input shape on spatiotemporal dimensions for structured DISCO convolutions. + No default value (required parameter). + n_layers : int, optional + Number of Local NO block layers. Default: 4 + disco_layers : Union[bool, List[bool]], optional + Must be same length as n_layers, dictates whether to include a + local integral kernel parallel connection at each layer. If a single + bool, shared for all layers. Default: True + disco_kernel_shape : Union[int, List[int]], optional + Kernel shape for local integral. Expects either a single integer for isotropic kernels + or two integers for anisotropic kernels. Default: [2, 4] + domain_length : List[int], optional + Extent/length of the physical domain. Assumes square domain [-1, 1]^2 by default. Default: [2, 2] + disco_groups : int, optional + Number of groups in the local integral convolution. Default: 1 + disco_bias : bool, optional + Whether to use a bias for the integral kernel. Default: True + radius_cutoff : float, optional + Cutoff radius (with respect to domain_length) for the local integral kernel. Default: None + diff_layers : Union[bool, List[bool]], optional + Must be same length as n_layers, dictates whether to include a + differential kernel parallel connection at each layer. If a single + bool, shared for all layers. Default: True + conv_padding_mode : str, optional + Padding mode for spatial convolution kernels. Options: "periodic", "circular", "replicate", "reflect", "zeros". + Default: "periodic" + fin_diff_kernel_size : int, optional + Conv kernel size for finite difference convolution. Default: 3 + mix_derivatives : bool, optional + Whether to mix derivatives across channels. Default: True + lifting_channel_ratio : Number, optional + Ratio of lifting channels to hidden_channels. + The number of lifting channels in the lifting block of the Local NO is + lifting_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels). Default: 2 + projection_channel_ratio : Number, optional + Ratio of projection channels to hidden_channels. + The number of projection channels in the projection block of the Local NO is + projection_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels). Default: 2 + positional_embedding : Union[str, nn.Module], optional + Positional embedding to apply to last channels of raw input before being passed through the Local 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. + - GridEmbedding2D: Uses this module directly for 2D cases. + - GridEmbeddingND: Uses this module directly (see neuralop.embeddings.GridEmbeddingND for details). + - None: Does nothing. + Default: "grid" + non_linearity : nn.Module, optional + Non-linear activation function module to use. Default: F.gelu + norm : str, optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + complex_data : bool, optional + Whether data is complex-valued. If True, initializes complex-valued modules. Default: False + use_channel_mlp : bool, optional + Whether to use an MLP layer after each LocalNO block. Default: False + channel_mlp_dropout : float, optional + Dropout parameter for ChannelMLP in LocalNO Block. Default: 0 + channel_mlp_expansion : float, optional + Expansion parameter for ChannelMLP in LocalNO Block. Default: 0.5 + channel_mlp_skip : str, optional + Type of skip connection to use in channel-mixing MLP. Options: "linear", "identity", "soft-gating", None. + Default: "soft-gating" + local_no_skip : str, optional + Type of skip connection to use in LocalNO layers. Options: "linear", "identity", "soft-gating", None. + Default: "linear" + resolution_scaling_factor : Union[Number, List[Number]], optional + 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]], optional + Percentage of padding to use. If not None, percentage of padding to use. + To vary the percentage of padding used along each input dimension, + pass in a list of percentages e.g. [p1, p2, ..., pN] such that + p1 corresponds to the percentage of padding along dim 1, etc. Default: None + local_no_block_precision : str, optional + Precision mode in which to perform spectral convolution. Options: "full", "half", "mixed". Default: "full" + stabilizer : str, optional + Whether to use a stabilizer in LocalNO block. Options: "tanh", None. Default: None + Note: stabilizer greatly improves performance in the case local_no_block_precision='mixed'. + max_n_modes : Tuple[int], optional + 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. Default: None + factorization : str, optional + Tensor factorization of the Local NO layer weights to use. + Options: "None", "Tucker", "CP", "TT" + Other factorization methods supported by tltorch. Default: None + rank : float, optional + Tensor rank to use in factorization. Default: 1.0 + Set to float <1.0 when using TFNO (i.e. when factorization is not None). + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + implementation : str, optional + Implementation method for factorized tensors. + Options: "factorized", "reconstructed". Default: "factorized" + decomposition_kwargs : dict, optional + Extra kwargs for tensor decomposition (see tltorch.FactorizedTensor). Default: {} + separable : bool, optional + Whether to use a separable spectral convolution. Default: False + preactivation : bool, optional + Whether to compute LocalNO forward pass with ResNet-style preactivation. Default: False + conv_module : nn.Module, optional + Module to use for LocalNOBlock's convolutions. Default: SpectralConv + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when ``conv_module`` is :class:`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 + -------- + + >>> from neuralop.models import LocalNO + >>> model = LocalNO(n_modes=(12,12), in_channels=1, out_channels=1, hidden_channels=64) + >>> model + FNO( + (positional_embedding): GridEmbeddingND() + (local_no_blocks): LocalNOBlocks( + (convs): SpectralConv( + (weight): ModuleList( + (0-3): 4 x DenseTensor(shape=torch.Size([64, 64, 12, 7]), rank=None) + ) + ) + ... torch.nn.Module printout truncated ... + + References + ---------- + .. [1] Liu-Schiaffini M., Berner J., Bonev B., Kurth T., Azizzadenesheli K., Anandkumar A.; + "Neural Operators with Localized Integral and Differential Kernels" (2024). + ICML 2024, https://arxiv.org/pdf/2402.16845. + + """ + + def __init__( + self, + n_modes: Tuple[int], + in_channels: int, + out_channels: int, + hidden_channels: int, + default_in_shape, + n_layers: int = 4, + disco_layers: Union[bool, List[bool]] = True, + disco_kernel_shape: List[int] = [2, 4], + radius_cutoff: bool = None, + domain_length: List[int] = [2, 2], + disco_groups: int = 1, + disco_bias: bool = True, + diff_layers: Union[bool, List[bool]] = True, + conv_padding_mode: str = "periodic", + fin_diff_kernel_size: int = 3, + mix_derivatives: bool = True, + lifting_channel_ratio: Number = 2, + projection_channel_ratio: Number = 2, + positional_embedding: Union[str, nn.Module] = "grid", + non_linearity: nn.Module = F.gelu, + norm: str = None, + norm_groups: int = 1, + complex_data: bool = False, + use_channel_mlp: bool = False, + channel_mlp_dropout: float = 0, + channel_mlp_expansion: float = 0.5, + channel_mlp_skip: str = "soft-gating", + local_no_skip: str = "linear", + resolution_scaling_factor: Union[Number, List[Number]] = None, + domain_padding: Union[Number, List[Number]] = None, + local_no_block_precision: str = "full", + stabilizer: str = None, + max_n_modes: Tuple[int] = None, + factorization: str = None, + rank: float = 1.0, + fixed_rank_modes: bool = False, + implementation: str = "factorized", + decomposition_kwargs: dict = dict(), + separable: bool = False, + preactivation: bool = False, + conv_module: nn.Module = SpectralConv, + enforce_hermitian_symmetry: bool = True, + ): + super().__init__() + self.n_dim = len(n_modes) + + # n_modes is a special property - see the class' property for underlying mechanism + # When updated, change should be reflected in local_no blocks + self._n_modes = n_modes + + self.hidden_channels = hidden_channels + self.in_channels = in_channels + self.out_channels = out_channels + self.n_layers = n_layers + + # init lifting and projection channels using ratios w.r.t hidden channels + self.lifting_channel_ratio = lifting_channel_ratio + self.lifting_channels = int(lifting_channel_ratio * self.hidden_channels) + + self.projection_channel_ratio = projection_channel_ratio + self.projection_channels = int(projection_channel_ratio * self.hidden_channels) + + self.non_linearity = non_linearity + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.local_no_skip = (local_no_skip,) + self.channel_mlp_skip = (channel_mlp_skip,) + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + self.complex_data = complex_data + self.local_no_block_precision = local_no_block_precision + + if positional_embedding == "grid": + spatial_grid_boundaries = [[0.0, 1.0]] * self.n_dim + self.positional_embedding = GridEmbeddingND( + in_channels=self.in_channels, + dim=self.n_dim, + grid_boundaries=spatial_grid_boundaries, + ) + elif isinstance(positional_embedding, GridEmbedding2D): + if self.n_dim == 2: + self.positional_embedding = positional_embedding + else: + raise ValueError( + f"Error: expected {self.n_dim}-d positional embeddings, got {positional_embedding}" + ) + elif isinstance(positional_embedding, GridEmbeddingND): + self.positional_embedding = positional_embedding + elif positional_embedding == None: + self.positional_embedding = None + else: + raise ValueError( + f"Error: tried to instantiate positional embedding with {positional_embedding},\ + expected one of 'grid', GridEmbeddingND" + ) + + if domain_padding is not None and ( + (isinstance(domain_padding, list) and sum(domain_padding) > 0) + or (isinstance(domain_padding, (float, int)) and domain_padding > 0) + ): + self.domain_padding = DomainPadding( + domain_padding=domain_padding, + resolution_scaling_factor=resolution_scaling_factor, + ) + else: + self.domain_padding = None + + if resolution_scaling_factor is not None: + if isinstance(resolution_scaling_factor, (float, int)): + resolution_scaling_factor = [resolution_scaling_factor] * self.n_layers + self.resolution_scaling_factor = resolution_scaling_factor + + self.local_no_blocks = LocalNOBlocks( + in_channels=hidden_channels, + out_channels=hidden_channels, + n_modes=self.n_modes, + default_in_shape=default_in_shape, + resolution_scaling_factor=resolution_scaling_factor, + disco_layers=disco_layers, + disco_kernel_shape=disco_kernel_shape, + radius_cutoff=radius_cutoff, + domain_length=domain_length, + disco_groups=disco_groups, + disco_bias=disco_bias, + diff_layers=diff_layers, + conv_padding_mode=conv_padding_mode, + fin_diff_kernel_size=fin_diff_kernel_size, + mix_derivatives=mix_derivatives, + use_channel_mlp=use_channel_mlp, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + stabilizer=stabilizer, + norm=norm, + norm_groups=norm_groups, + preactivation=preactivation, + local_no_skip=local_no_skip, + channel_mlp_skip=channel_mlp_skip, + max_n_modes=max_n_modes, + local_no_block_precision=local_no_block_precision, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + decomposition_kwargs=decomposition_kwargs, + conv_module=conv_module, + n_layers=n_layers, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ) + + # if adding a positional embedding, add those channels to lifting + lifting_in_channels = self.in_channels + if self.positional_embedding is not None: + lifting_in_channels += self.n_dim + # if lifting_channels is passed, make lifting a Channel-Mixing MLP + # with a hidden layer of size lifting_channels + if self.lifting_channels: + self.lifting = ChannelMLP( + in_channels=lifting_in_channels, + out_channels=self.hidden_channels, + hidden_channels=self.lifting_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + # otherwise, make it a linear layer + else: + self.lifting = ChannelMLP( + in_channels=lifting_in_channels, + hidden_channels=self.hidden_channels, + out_channels=self.hidden_channels, + n_layers=1, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + # Convert lifting to a complex ChannelMLP if self.complex_data==True + if self.complex_data: + self.lifting = ComplexValued(self.lifting) + + self.projection = ChannelMLP( + in_channels=self.hidden_channels, + out_channels=out_channels, + hidden_channels=self.projection_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + if self.complex_data: + self.projection = ComplexValued(self.projection) + + def forward(self, x, output_shape=None, **kwargs): + """FNO's forward pass + + 1. Applies optional positional encoding + + 2. Sends inputs through a lifting layer to a high-dimensional latent + space + + 3. Applies optional domain padding to high-dimensional intermediate function representation + + 4. Applies `n_layers` Local NO layers in sequence (Differential + optional DISCO + skip connections, nonlinearity) + + 5. If domain padding was applied, domain padding is removed + + 6. Projection of intermediate function representation to the output channels + + Parameters + ---------- + x : tensor + input tensor + + output_shape : {tuple, tuple list, None}, default is None + Gives the option of specifying the exact output shape for odd shaped inputs. + + * If None, don't specify an output shape + + * If tuple, specifies the output-shape of the **last** FNO Block + + * If tuple list, specifies the exact output-shape of each FNO Block + """ + if kwargs: + warnings.warn( + f"LocalNO.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + if output_shape is None: + output_shape = [None] * self.n_layers + elif isinstance(output_shape, tuple): + output_shape = [None] * (self.n_layers - 1) + [output_shape] + + # append spatial pos embedding if set + if self.positional_embedding is not None: + x = self.positional_embedding(x) + + x = self.lifting(x) + + if self.domain_padding is not None: + x = self.domain_padding.pad(x) + + for layer_idx in range(self.n_layers): + x = self.local_no_blocks(x, layer_idx, output_shape=output_shape[layer_idx]) + + if self.domain_padding is not None: + x = self.domain_padding.unpad(x) + + x = self.projection(x) + + return x + + @property + def n_modes(self): + return self._n_modes + + @n_modes.setter + def n_modes(self, n_modes): + self.local_no_blocks.n_modes = n_modes + self._n_modes = n_modes diff --git a/sources/neuraloperator/neuralop/models/otno.py b/sources/neuraloperator/neuralop/models/otno.py new file mode 100644 index 0000000000000000000000000000000000000000..29ac37054dc410dea064f7376a2e7d4516618778 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/otno.py @@ -0,0 +1,111 @@ +import torch +import torch.nn as nn + +from neuralop.models import FNO + + +class OTNO(FNO): + """ + Optimal Transport Neural Operator + + The architecture is described in [1]_. + + OTNO integrates optimal transport (OT) into operator learning for partial + differential equations (PDEs) on complex geometries. + + Parameters + ---------- + All arguments are the same as :class:`neuralop.models.FNO`. + + See the FNO documentation for detailed descriptions. + + References + ---------- + .. [1] Li, X., Li, Z., Kovachki, N., & Anandkumar, A. "Geometric Operator + Learning with Optimal Transport" (2025). arXiv preprint arXiv:2507.20065. + https://arxiv.org/pdf/2507.20065 + """ + + def __init__( + self, + n_modes, + hidden_channels, + in_channels=4, + out_channels=1, + lifting_channel_ratio=2, + projection_channel_ratio=2, + n_layers=4, + positional_embedding=None, + use_channel_mlp=False, + channel_mlp_expansion=None, + channel_mlp_dropout=0, + norm="group_norm", + norm_groups=1, + factorization=None, + rank=1, + domain_padding=None, + **kwargs, + ): + super().__init__( + n_modes=n_modes, + hidden_channels=hidden_channels, + in_channels=in_channels, + out_channels=out_channels, + lifting_channel_ratio=lifting_channel_ratio, + projection_channel_ratio=projection_channel_ratio, + n_layers=n_layers, + positional_embedding=positional_embedding, + use_channel_mlp=use_channel_mlp, + channel_mlp_expansion=channel_mlp_expansion, + channel_mlp_dropout=channel_mlp_dropout, + norm=norm, + norm_groups=norm_groups, + factorization=factorization, + rank=rank, + domain_padding=domain_padding, + **kwargs, + ) + + @property + def device(self): + """Returns the device that the model is on.""" + return self.device_indicator_param.device + + # x: (1, in_channels, n_s_sqrt, n_s_sqrt) + # Transport features containing concatenated data: + # - Source mesh coordinates X_s + # - Transported mesh coordinates T(X_s) + # - Additional features (e.g., normals) + # where n_s_sqrt * n_s_sqrt = n_s (total number of source vertices) + # + # ind_dec: (n_t,) + # Index decoder for mapping from latent grid to target mesh vertices + # where n_t is the number of target vertices + def forward(self, x, ind_dec, **kwargs): + """OTNO's forward pass""" + # Append spatial positional embedding if set (mirrors FNO.forward) + if self.positional_embedding is not None: + x = self.positional_embedding(x) + + x = self.lifting(x) # (1, hidden_channels, n_s_sqrt, n_s_sqrt) + + # Apply domain padding if specified + if self.domain_padding is not None: + x = self.domain_padding.pad(x) + + # Apply FNO layers + for layer_idx in range(self.n_layers): + x = self.fno_blocks(x, layer_idx) + + # Remove domain padding if applied + if self.domain_padding is not None: + x = self.domain_padding.unpad(x) # (1, hidden_channels, n_s_sqrt, n_s_sqrt) + + # Use ind_dec to transport back to target mesh + x = x.reshape(self.hidden_channels, -1).permute(1, 0) # (n_s, hidden_channels) + out = x[ind_dec].permute(1, 0) # (hidden_channels, n_t) + + out = out.unsqueeze(0) + out = self.projection(out) # (1, out_channels, n_t) + out = out.squeeze(0) # (out_channels, n_t) + return out diff --git a/sources/neuraloperator/neuralop/models/rno.py b/sources/neuraloperator/neuralop/models/rno.py new file mode 100644 index 0000000000000000000000000000000000000000..82d7b22053a0b140407aeceea937f6d87c597380 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/rno.py @@ -0,0 +1,532 @@ +from typing import Tuple, List, Union, Literal + +Number = Union[float, int] + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + +from ..layers.rno_block import RNOBlock +from ..layers.padding import DomainPadding +from ..layers.fno_block import FNOBlocks +from ..layers.channel_mlp import ChannelMLP +from ..layers.spectral_convolution import SpectralConv +from ..layers.complex import ComplexValued +from ..layers.embeddings import GridEmbeddingND, GridEmbedding2D +from .base_model import BaseModel + + +class RNO(BaseModel, name="RNO"): + """ + N-Dimensional Recurrent Neural Operator. + + The RNO has an identical architecture to the finite-dimensional GRU, with + the exception that linear matrix-vector multiplications are replaced by + Fourier layers (Li et al., 2021), and for regression problems, the output + nonlinearity is replaced by a SELU activation. + + The operation of the GRU is as follows: + z_t = sigmoid(W_z x + U_z h_{t-1} + b_z) + r_t = sigmoid(W_r x + U_r h_{t-1} + b_r) + \hat h_t = selu(W_h x_t + U_h (r_t * h_{t-1}) + b_h) + h_t = (1 - z_t) * h_{t-1} + z_t * \hat h_t, + + where * is element-wise, the b_i's are bias functions, and W_i, U_i are + linear Fourier layers. + + References + ---------- + .. [RNO] Liu-Schiaffini, M., Singer, C. E., Kovachki, N., Schneider, T., + Azizzadenesheli, K., & Anandkumar, A. (2023). Tipping point forecasting + in non-stationary dynamics on function spaces. arXiv preprint + arXiv:2308.08794. + + Parameters + ---------- + n_modes : Tuple[int, ...] + Number of modes to keep in Fourier Layer, along each dimension. + The dimensionality of the RNO 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 input channels in input function. Determined by the problem. + out_channels : int + Number of output channels in output function. Determined by the problem. + hidden_channels : int + Width of the RNO (i.e. number of channels). + This significantly affects the number of parameters of the RNO. + For 1D problems, 24-48 channels are typically sufficient. For 2D/3D problems + without Tucker/CP/TT factorization, start with 16-32 channels to avoid + excessive parameters. Increase if more expressivity is needed. + Update lifting_channel_ratio and projection_channel_ratio accordingly since they are proportional to hidden_channels. + n_layers : int, optional + Number of RNO layers to use. Default: 4 + rno_skip : bool, optional + Whether to use skip connections between RNO layers. When True, adds + the input to each layer's output: x_{l+1} = x_l + RNOBlock(x_l). + Default: False. Unlike FNO where skip connections improve gradient flow, + RNO's recurrent structure already provides temporal gradient pathways, + so skip connections are optional and may not always improve performance. + + Other Parameters + ---------------- + lifting_channel_ratio : Number, optional + Ratio of lifting channels to hidden_channels. + The number of lifting channels in the lifting block of the RNO is + lifting_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels). + projection_channel_ratio : Number, optional + Ratio of projection channels to hidden_channels. + The number of projection channels in the projection block of the RNO is + projection_channel_ratio * hidden_channels (e.g. default 2 * hidden_channels). + positional_embedding : Union[str, nn.Module], optional + Type of positional embedding to use. Options: + - "grid": Use default grid-based positional embedding + - GridEmbeddingND: Custom N-dimensional grid embedding + - GridEmbedding2D: Custom 2D grid embedding (only for 2D problems) + - None: No positional embedding + Default: None + non_linearity : nn.Module, optional + Non-Linear activation function module to use. Default: F.gelu + norm : Literal["ada_in", "group_norm", "instance_norm"], optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + complex_data : bool, optional + Whether the data is complex-valued. If True, initializes complex-valued modules. Default: False + use_channel_mlp : bool, optional + Whether to use an MLP layer after each FNO block. Default: True + channel_mlp_dropout : float, optional + Dropout parameter for ChannelMLP in FNO Block. Default: 0 + channel_mlp_expansion : float, optional + Expansion parameter for ChannelMLP in FNO Block. Default: 0.5 + channel_mlp_skip : Literal["linear", "identity", "soft-gating", None], optional + 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], optional + Type of skip connection to use in FNO layers. Options: "linear", "identity", "soft-gating", None. + Default: "linear" + return_sequences : bool, optional + Whether the final RNO layer returns the full sequence of hidden states or just the final state. + Intermediate layers always return sequences. Default: False + resolution_scaling_factor : Union[Number, List[Number]], optional + 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]], optional + 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, optional + Precision mode in which to perform spectral convolution. + Options: "full", "half", "mixed". Default: "full". + stabilizer : str, optional + 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, ...], optional + 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, optional + Tensor factorization of the FNO layer weights to use. + Options: "None", "Tucker", "CP", "TT" + Other factorization methods supported by tltorch. Default: None + rank : float, optional + Tensor rank to use in factorization. Default: 1.0 + Set to float <1.0 when using TFNO (i.e. when factorization is not None). + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + implementation : str, optional + Implementation method for factorized tensors. + Options: "factorized", "reconstructed". Default: "factorized" + decomposition_kwargs : dict, optional + Extra kwargs for tensor decomposition (see `tltorch.FactorizedTensor`). Default: {} + separable : bool, optional + Whether to use a separable spectral convolution. Default: False + preactivation : bool, optional + Whether to compute FNO forward pass with resnet-style preactivation. Default: False + conv_module : nn.Module, optional + Module to use for FNOBlock's convolutions. Default: SpectralConv + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used in :class:`SpectralConv`; 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. + """ + + def __init__( + self, + n_modes: Tuple[int, ...], + in_channels: int, + out_channels: int, + hidden_channels: int, + n_layers: int = 4, + rno_skip: bool = False, + lifting_channel_ratio: Number = 2, + projection_channel_ratio: Number = 2, + positional_embedding: Union[str, nn.Module] = "grid", + non_linearity: nn.Module = F.gelu, + norm: Literal["ada_in", "group_norm", "instance_norm"] = None, + norm_groups: int = 1, + complex_data: bool = False, + use_channel_mlp: bool = True, + channel_mlp_dropout: float = 0, + channel_mlp_expansion: float = 0.5, + channel_mlp_skip: Literal["linear", "identity", "soft-gating", None] = "soft-gating", + fno_skip: Literal["linear", "identity", "soft-gating", None] = "linear", + return_sequences: bool = False, + resolution_scaling_factor: Union[Number, List[Number]] = None, + domain_padding: Union[Number, List[Number]] = None, + fno_block_precision: str = "full", + stabilizer: str = None, + max_n_modes: Tuple[int, ...] = None, + factorization: str = None, + rank: float = 1.0, + fixed_rank_modes: bool = False, + implementation: str = "factorized", + decomposition_kwargs: dict = None, + separable: bool = False, + preactivation: bool = False, + conv_module: nn.Module = SpectralConv, + enforce_hermitian_symmetry: bool = True, + ): + if decomposition_kwargs is None: + decomposition_kwargs = {} + super().__init__() + self.n_dim = len(n_modes) + + # n_modes is a special property - see the class' property for underlying mechanism + # When updated, change should be reflected in fno blocks + self.n_modes = n_modes + + self.hidden_channels = hidden_channels + self.in_channels = in_channels + self.out_channels = out_channels + self.n_layers = n_layers + self.rno_skip = rno_skip + + # init lifting and projection channels using ratios w.r.t hidden channels + self.lifting_channel_ratio = lifting_channel_ratio + self.lifting_channels = int(lifting_channel_ratio * self.hidden_channels) + + self.projection_channel_ratio = projection_channel_ratio + self.projection_channels = int(projection_channel_ratio * self.hidden_channels) + + self.non_linearity = non_linearity + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.fno_skip = (fno_skip,) + self.channel_mlp_skip = (channel_mlp_skip,) + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + self.complex_data = complex_data + self.fno_block_precision = fno_block_precision + + ## Domain padding + if domain_padding is not None and ( + (isinstance(domain_padding, list) and sum(domain_padding) > 0) + or (isinstance(domain_padding, (float, int)) and domain_padding > 0) + ): + self.domain_padding = DomainPadding( + domain_padding=domain_padding, + resolution_scaling_factor=resolution_scaling_factor, + ) + else: + self.domain_padding = None + + ## Positional embedding + if positional_embedding == "grid": + spatial_grid_boundaries = [[0.0, 1.0]] * self.n_dim + self.positional_embedding = GridEmbeddingND( + in_channels=self.in_channels, + dim=self.n_dim, + grid_boundaries=spatial_grid_boundaries, + ) + elif isinstance(positional_embedding, GridEmbedding2D): + if self.n_dim == 2: + self.positional_embedding = positional_embedding + else: + raise ValueError( + f"Error: expected {self.n_dim}-d positional embeddings, got {positional_embedding}" + ) + elif isinstance(positional_embedding, GridEmbeddingND): + self.positional_embedding = positional_embedding + elif positional_embedding is None: + self.positional_embedding = None + else: + raise ValueError( + f"Error: tried to instantiate RNO positional embedding with {positional_embedding}, " + f"expected one of 'grid', GridEmbeddingND, GridEmbedding2D, or None" + ) + + ## Resolution scaling factor + if resolution_scaling_factor: + if isinstance(resolution_scaling_factor, (float, int)): + resolution_scaling_factor = [resolution_scaling_factor] * self.n_layers + else: + resolution_scaling_factor = [None] * self.n_layers + self.resolution_scaling_factor = resolution_scaling_factor + + ## Return sequences configuration + # Intermediate layers always return sequences, only last layer is configurable + return_sequences_list = [True] * (self.n_layers - 1) + [return_sequences] + self.return_sequences = return_sequences_list + + module_list = [ + RNOBlock( + n_modes=self.n_modes, + hidden_channels=hidden_channels, + return_sequences=return_sequences_list[i], + resolution_scaling_factor=self.resolution_scaling_factor[i], + use_channel_mlp=use_channel_mlp, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + stabilizer=stabilizer, + norm=norm, + norm_groups=norm_groups, + preactivation=preactivation, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + complex_data=complex_data, + max_n_modes=max_n_modes, + fno_block_precision=fno_block_precision, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + decomposition_kwargs=decomposition_kwargs, + conv_module=conv_module, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ) + for i in range(n_layers) + ] + self.layers = nn.ModuleList(module_list) + + ## Lifting layer + # if adding a positional embedding, add those channels to lifting + lifting_in_channels = self.in_channels + if self.positional_embedding is not None: + lifting_in_channels += self.n_dim + # if lifting_channels is set, make lifting a Channel-Mixing MLP + # with a hidden layer of size lifting_channels + if self.lifting_channels: + self.lifting = ChannelMLP( + in_channels=lifting_in_channels, + out_channels=self.hidden_channels, + hidden_channels=self.lifting_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + # otherwise, make it a linear layer + else: + self.lifting = ChannelMLP( + in_channels=lifting_in_channels, + hidden_channels=self.hidden_channels, + out_channels=self.hidden_channels, + n_layers=1, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + # Convert lifting to a complex ChannelMLP if self.complex_data==True + if self.complex_data: + self.lifting = ComplexValued(self.lifting) + + ## Projection layer + self.projection = ChannelMLP( + in_channels=self.hidden_channels, + out_channels=out_channels, + hidden_channels=self.projection_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + if self.complex_data: + self.projection = ComplexValued(self.projection) + + def forward( + self, + x, + init_hidden_states=None, + return_hidden_states=False, + keep_states_padded=False, + ): + """ + Forward pass for the Recurrent Neural Operator. + + Parameters + ---------- + x : torch.Tensor + Input tensor with shape (batch, timesteps, in_channels, *spatial_dims), + where len(spatial_dims) == self.n_dim. The channel dimension MUST be at + index 2 and the time dimension MUST be at index 1. + init_hidden_states : list[torch.Tensor] | None + Optional list of per-layer initial hidden states. Each tensor should have + shape (batch, hidden_channels, *spatial_dims_h), where spatial_dims_h are + the unpadded spatial dimensions at each layer (accounting for resolution + scaling). If domain_padding is enabled, hidden states will be automatically + padded like the input x, unless keep_states_padded is True. + If None, all hidden states are initialized internally. + return_hidden_states : bool, optional + Whether to return the final hidden states for each layer in addition to + the prediction. Default: False + keep_states_padded : bool, optional + If True, treats provided init_hidden_states as already padded (no additional + padding applied) and returns final_hidden_states in padded form (no unpadding). + Use this for efficient autoregressive loops to preserve boundary information. + Default: False + + Returns + ------- + pred : torch.Tensor + Output tensor with shape (batch, out_channels, *spatial_dims_out). + final_hidden_states : list[torch.Tensor], optional + Returned only if return_hidden_states=True. + """ + # Strict input validation to avoid silent errors from resolution invariance + expected_rank = 3 + self.n_dim + if x.ndim != expected_rank: + raise ValueError( + f"RNO.forward expected input of rank {expected_rank} = " + f"(batch, timesteps, channels, {self.n_dim} spatial dims), got rank {x.ndim} with shape {tuple(x.shape)}" + ) + if x.shape[2] != self.in_channels: + raise ValueError( + f"RNO.forward expected x.shape[2] == in_channels ({self.in_channels}); " + f"got {x.shape[2]}. Input must be shaped as (batch, timesteps, in_channels, *spatial_dims)." + ) + # x shape (batch, timesteps, in_channels, *spatial_dims) + batch_size, timesteps = x.shape[:2] + dom_sizes = x.shape[3 : 3 + self.n_dim] + + if init_hidden_states is None: + init_hidden_states = [None] * self.n_layers + else: + # If domain padding is enabled AND states are not already padded (keep_states_padded=False), pad them. + if self.domain_padding and not keep_states_padded: + padded_hidden_states = [] + for h in init_hidden_states: + if h is not None: + h = self.domain_padding.pad(h) + padded_hidden_states.append(h) + init_hidden_states = padded_hidden_states + + # Reshape for processing: (batch*timesteps, channels, *spatial_dims) + x = x.reshape(batch_size * timesteps, *x.shape[2:]) + + # append spatial pos embedding if set + if self.positional_embedding is not None: + x = self.positional_embedding(x) + + x = self.lifting(x) + x = x.reshape(batch_size, timesteps, *x.shape[1:]) + + if self.domain_padding: + # DomainPadding expects (batch, channels, *spatial_dims), so reshape to remove timestep dim + x = x.reshape(batch_size * timesteps, *x.shape[2:]) + x = self.domain_padding.pad(x) + x = x.reshape(batch_size, timesteps, *x.shape[1:]) + + final_hidden_states = [] + for i in range(self.n_layers): + pred_x = self.layers[i](x, init_hidden_states[i]) + if i < self.n_layers - 1: + if self.rno_skip: + x = x + pred_x + else: + x = pred_x + final_hidden_states.append(x[:, -1]) + else: + x = pred_x + final_hidden_states.append(x) + h = final_hidden_states[-1] + + if self.domain_padding: + # DomainPadding.unpad expects (batch, channels, *spatial_dims) + # h comes from the last layer, which is padded logic. + + # We ALWAYS unpad 'h' for the projection layer to produce the correct output size + # (Computation continues in unpadded space for projection) + h = self.domain_padding.unpad(h) + + # For final_hidden_states, we unpad UNLESS explicitly told to keep them padded + if return_hidden_states and not keep_states_padded: + unpadded_states = [] + for state in final_hidden_states: + unpadded_states.append(self.domain_padding.unpad(state)) + final_hidden_states = unpadded_states + + pred = self.projection(h) + + if return_hidden_states: + return pred, final_hidden_states + else: + return pred + + def predict(self, x, num_steps, grid_function=None): + """Autoregressively predict future time steps. + + Performs autoregressive rollout by iteratively feeding predictions back as input. + At each step, the model predicts the next time step from the current input, + then uses that prediction as input for the subsequent prediction. + + Parameters + ---------- + x : torch.Tensor + Initial input sequence with shape (batch, timesteps, in_channels, *spatial_dims). + The last time step of this sequence serves as the starting point for predictions. + num_steps : int + Number of future time steps to predict autoregressively. + grid_function : callable, optional + Function that generates positional embeddings (e.g., spatial coordinates) to + concatenate with predictions before feeding them back as input. Should have + signature grid_function(shape, device) -> torch.Tensor, where the returned + tensor has shape matching the input requirements. Use this when your model + was trained with concatenated positional information. Default: None + + Returns + ------- + torch.Tensor + Predicted sequence with shape (batch, num_steps, out_channels, *spatial_dims), + containing the autoregressively generated future states. + + Notes + ----- + This method maintains hidden states across prediction steps, enabling the RNO + to leverage its recurrent structure during autoregressive generation. + """ + output = [] + states = [None] * self.n_layers + + for _ in range(num_steps): + pred, states = self.forward( + x, states, return_hidden_states=True, keep_states_padded=True + ) + + output.append(pred) + x = pred.reshape((pred.shape[0], 1, *pred.shape[1:])) + if grid_function: + grid = grid_function( + (x.shape[0], x.shape[1], 1, x.shape[-2], x.shape[-1]), x.device + ) + x = torch.cat((x, grid), dim=2) + + return torch.stack(output, dim=1) diff --git a/sources/neuraloperator/neuralop/models/sfno.py b/sources/neuraloperator/neuralop/models/sfno.py new file mode 100644 index 0000000000000000000000000000000000000000..3a78e109b830c36d3ad7d47728718a0581543652 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/sfno.py @@ -0,0 +1,14 @@ +""" +SFNO - Spherical Fourier Neural Operator +Replaces the default SpectralConv (a convolution in the frequency domain +over Fourier basis functions) with a SphericalConv (a convolution over the +spherical harmonic basis functions) +""" +from ..layers.spherical_convolution import SphericalConv +from .fno import FNO, partialclass + +SFNO = partialclass("SFNO", FNO, factorization="dense", conv_module=SphericalConv) +SFNO.__doc__ = SFNO.__doc__.replace("Fourier", "Spherical Fourier", 1) +SFNO.__doc__ = SFNO.__doc__.replace("FNO", "SFNO") +SFNO.__doc__ = SFNO.__doc__.replace("fno", "sfno") +SFNO.__doc__ = SFNO.__doc__.replace(":ref:`sfno_intro`", ":ref:`fno_intro`") diff --git a/sources/neuraloperator/neuralop/models/tests/__init__.py b/sources/neuraloperator/neuralop/models/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/models/tests/test_codano.py b/sources/neuraloperator/neuralop/models/tests/test_codano.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bc4c779b61ef6c4f713ae3d1cb4157207725a1 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_codano.py @@ -0,0 +1,97 @@ +import torch +from ..codano import CODANO +import pytest + + +@pytest.mark.parametrize("hidden_variable_codimension", [1, 2]) +@pytest.mark.parametrize("lifting_channels", [2, None]) +@pytest.mark.parametrize("use_positional_encoding", [True, False]) +@pytest.mark.parametrize("n_variables", [3, 4]) +@pytest.mark.parametrize("positional_encoding_dim", [4, 8]) +@pytest.mark.parametrize("positional_encoding_modes", [[8, 8], [16, 16]]) +@pytest.mark.parametrize("static_channel_dim", [0, 2]) +@pytest.mark.parametrize("use_cls_token", [True, False]) +def test_CODANO( + hidden_variable_codimension, + lifting_channels, + use_positional_encoding, + n_variables, + positional_encoding_dim, + positional_encoding_modes, + static_channel_dim, + use_cls_token, +): + output_variable_codimension = 1 + n_layers = 5 + n_heads = [2] * n_layers + n_modes = [[16, 16]] * n_layers + attention_scalings = [0.5] * n_layers + scalings = [[1, 1], [0.5, 0.5], [1, 1], [2, 2], [1, 1]] + use_horizontal_skip_connection = True + horizontal_skips_map = {3: 1, 4: 0} + if use_positional_encoding: + variable_ids = ["a" * (i + 1) for i in range(n_variables)] + else: + variable_ids = None + + model = CODANO( + output_variable_codimension=output_variable_codimension, + hidden_variable_codimension=hidden_variable_codimension, + lifting_channels=lifting_channels, + use_positional_encoding=use_positional_encoding, + positional_encoding_dim=positional_encoding_dim, + positional_encoding_modes=positional_encoding_modes, + use_horizontal_skip_connection=use_horizontal_skip_connection, + static_channel_dim=static_channel_dim, + horizontal_skips_map=horizontal_skips_map, + variable_ids=variable_ids, + n_layers=n_layers, + n_heads=n_heads, + n_modes=n_modes, + attention_scaling_factors=attention_scalings, + per_layer_scaling_factors=scalings, + enable_cls_token=use_cls_token, + ) + + in_data = torch.randn(2, n_variables, 32, 32) + + if static_channel_dim > 0: + static_channels = torch.randn(2, static_channel_dim, 32, 32) + else: + static_channels = None + + # Test forward pass + out = model(in_data, static_channels, variable_ids) + + # Check output size + assert list(out.shape) == [2, n_variables, 32, 32] + + # test different resolutions + # also different sets of variables + + new_n_var = n_variables // 2 + if use_positional_encoding: + input_var_ids = variable_ids[:new_n_var] + else: + input_var_ids = None + + in_data = torch.randn(2, new_n_var, 64, 64) + if static_channel_dim > 0: + static_channels = torch.randn(2, static_channel_dim, 64, 64) + else: + static_channels = None + + out = model(in_data, static_channels, input_var_ids) + assert list(out.shape) == [2, new_n_var, 64, 64] + + # Test backward pass + out.sum().backward() + + # testing for new varibales + if use_positional_encoding: + model._extend_positional_encoding("T") + input_var_ids = input_var_ids + ["T"] + + in_data = torch.randn(2, new_n_var + 1, 64, 64) + out = model(in_data, static_channels, input_var_ids) + assert list(out.shape) == [2, new_n_var + 1, 64, 64] diff --git a/sources/neuraloperator/neuralop/models/tests/test_fno.py b/sources/neuraloperator/neuralop/models/tests/test_fno.py new file mode 100644 index 0000000000000000000000000000000000000000..fc63edd2d5b652e89ac060bc94cda202c59b6ca9 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_fno.py @@ -0,0 +1,318 @@ +from math import prod + +import pytest +import torch +import torch.nn.functional as F +from tensorly import tenalg + +from neuralop.models import FNO + +tenalg.set_backend("einsum") + + +@pytest.mark.parametrize("n_dim", [1, 2, 3, 4]) +@pytest.mark.parametrize("fno_block_precision", ["full"]) +@pytest.mark.parametrize("stabilizer", [None, "tanh"]) +@pytest.mark.parametrize("lifting_channel_ratio", [1, 2]) +@pytest.mark.parametrize("preactivation", [False, True]) +@pytest.mark.parametrize("complex_data", [True, False]) +@pytest.mark.parametrize("enforce_hermitian_symmetry", [True, False]) +def test_fno( + n_dim, + fno_block_precision, + stabilizer, + lifting_channel_ratio, + preactivation, + complex_data, + enforce_hermitian_symmetry, +): + if torch.has_cuda: + device = "cuda" + s = 12 + modes = 8 + width = 12 + batch_size = 4 + n_layers = 4 + else: + device = "cpu" + fno_block_precision = "full" + s = 12 + modes = 5 + width = 9 + batch_size = 3 + n_layers = 2 + + dtype = torch.cfloat if complex_data else torch.float32 + rank = 0.2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + model = FNO( + in_channels=3, + out_channels=1, + hidden_channels=width, + n_modes=n_modes, + rank=rank, + fixed_rank_modes=False, + n_layers=n_layers, + stabilizer=stabilizer, + lifting_channel_ratio=lifting_channel_ratio, + preactivation=preactivation, + complex_data=complex_data, + fno_block_precision=fno_block_precision, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size, dtype=dtype).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Check backward pass + loss = out.sum() + # take the modulus if data is complex-valued to create grad + if dtype == torch.cfloat: + loss = (loss.real**2 + loss.imag**2) ** 0.5 + loss.backward() + + n_unused_params = 0 + for param in model.parameters(): + if param.grad is None: + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + + +@pytest.mark.parametrize( + "resolution_scaling_factor", + [ + [2, 1, 1], + [1, 2, 1], + [1, 1, 2], + [1, 2, 2], + [1, 0.5, 1], + ], +) +def test_fno_superresolution(resolution_scaling_factor): + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 9 + batch_size = 3 + n_layers = 3 + n_dim = 2 + rank = 0.2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + factorization="cp", + implementation="reconstructed", + rank=rank, + resolution_scaling_factor=resolution_scaling_factor, + n_layers=n_layers, + ).to(device) + + print(f"{model.resolution_scaling_factor=}") + + in_data = torch.randn(batch_size, 3, *size).to(device) + # Test forward pass + out = model(in_data) + + # Check output size + factor = prod(resolution_scaling_factor) + + assert list(out.shape) == [batch_size, 1] + [int(round(factor * s)) for s in size] + + +@pytest.mark.parametrize("norm", [None, "group_norm", "instance_norm"]) +@pytest.mark.parametrize("use_channel_mlp", [True, False]) +@pytest.mark.parametrize("channel_mlp_skip", ["linear", "identity", "soft-gating", None]) +@pytest.mark.parametrize("fno_skip", ["linear", "identity", "soft-gating", None]) +@pytest.mark.parametrize("complex_data", [True, False]) +def test_fno_advanced_params(norm, use_channel_mlp, channel_mlp_skip, fno_skip, complex_data): + """Test FNO with various advanced parameter combinations.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 9 + batch_size = 3 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + + dtype = torch.cfloat if complex_data else torch.float32 + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + norm=norm, + use_channel_mlp=use_channel_mlp, + channel_mlp_skip=channel_mlp_skip, + fno_skip=fno_skip, + complex_data=complex_data, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size, dtype=dtype).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Test backward pass + loss = out.sum() + # take the modulus if data is complex-valued to create grad + if dtype == torch.cfloat: + loss = (loss.real**2 + loss.imag**2) ** 0.5 + loss.backward() + + +def test_fno_group_norm(): + """Test FNO with group_norm and custom norm_groups""" + device = "cuda" if torch.cuda.is_available() else "cpu" + modes = 5 + hidden_channels = 16 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (12,) * n_dim + n_modes = (modes,) * n_dim + norm_groups = 4 + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + norm="group_norm", + norm_groups=norm_groups, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Verify norm_groups propagation + for norm_layer in model.fno_blocks.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + + +@pytest.mark.parametrize("positional_embedding", ["grid", None]) +@pytest.mark.parametrize("domain_padding", [None, 0.1, [0.1, 0.2]]) +def test_fno_embedding_and_padding(positional_embedding, domain_padding): + """Test FNO with different positional embeddings and domain padding.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 9 + projection_channel_ratio = 2 + lifting_channel_ratio = 2 + batch_size = 3 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + positional_embedding=positional_embedding, + domain_padding=domain_padding, + projection_channel_ratio=projection_channel_ratio, + lifting_channel_ratio=lifting_channel_ratio, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + +@pytest.mark.parametrize("channel_mlp_dropout", [0.0, 0.1, 0.5]) +@pytest.mark.parametrize("channel_mlp_expansion", [0.25, 0.5, 1.0]) +@pytest.mark.parametrize("non_linearity", [F.gelu, F.relu, F.tanh]) +def test_fno_channel_mlp_params(channel_mlp_dropout, channel_mlp_expansion, non_linearity): + """Test FNO with different channel MLP parameters.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 9 + batch_size = 3 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + +def test_fno_conv_bias_kernel(): + """Test FNO with a local convolutional bias kernel.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 9 + batch_size = 3 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + conv_bias_kernel = 3 + + model = FNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + conv_bias_kernel=conv_bias_kernel, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + out = model(in_data) + + assert list(out.shape) == [batch_size, 1, *size] + assert model.conv_bias_kernel == conv_bias_kernel + assert model.fno_blocks.conv_bias_kernel == conv_bias_kernel + + out.sum().backward() diff --git a/sources/neuraloperator/neuralop/models/tests/test_fnogno.py b/sources/neuraloperator/neuralop/models/tests/test_fnogno.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8f11fd218ecd4caf2583c03c33cf2a2bf19d6a --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_fnogno.py @@ -0,0 +1,119 @@ +import torch +from torch.autograd import grad +import pytest +from tensorly import tenalg + +tenalg.set_backend("einsum") + +from ..fnogno import FNOGNO + +# Parameterize use of torch_scatter if it is built +try: + from torch_scatter import segment_csr + + use_torch_scatter = [True, False] +except: + use_torch_scatter = [False] + + +@pytest.mark.parametrize( + "gno_transform_type", ["linear", "nonlinear_kernelonly", "nonlinear"] +) +@pytest.mark.parametrize("fno_n_modes", [(8,), (8, 8), (8, 8, 8)]) +@pytest.mark.parametrize("gno_batched", [False, True]) +@pytest.mark.parametrize("gno_pos_embed_type", [None, "transformer"]) +@pytest.mark.parametrize("fno_norm", [None, "ada_in"]) +@pytest.mark.parametrize("use_torch_scatter", use_torch_scatter) +def test_fnogno(gno_transform_type, fno_n_modes, gno_batched, gno_pos_embed_type, fno_norm, use_torch_scatter): + if torch.has_cuda: + device = torch.device("cuda:0") + else: + device = torch.device("cpu:0") + + in_channels = 3 + out_channels = 2 + batch_size = 4 + n_dim = len(fno_n_modes) + + model = FNOGNO( + in_channels=in_channels, + out_channels=out_channels, + gno_radius=0.2, + gno_coord_dim=n_dim, + gno_pos_embed_type=gno_pos_embed_type, + gno_transform_type=gno_transform_type, + gno_batched=gno_batched, + fno_n_modes=fno_n_modes, + fno_norm=fno_norm, + fno_ada_in_features=4, + gno_use_open3d=False, + gno_use_torch_scatter=use_torch_scatter, + ).to(device) + + in_p_shape = [ + 32, + ] * n_dim + in_p_shape.append(n_dim) + in_p = torch.randn(*in_p_shape, device=device) + + out_p = torch.randn(100, n_dim, device=device) + + f_shape = [ + 32, + ] * n_dim + f_shape.append(in_channels) + + # repeat along batch dim if batched + if gno_batched: + f_shape = [batch_size] + f_shape + + f = torch.randn(*f_shape, device=device) + # require and retain grad to check for backprop + f.requires_grad_(True) + # f.retain_grad() + + ada_in = torch.randn(1, device=device) + + # Test forward pass + out = model(in_p, out_p, f, ada_in) + + # Check output size + if gno_batched: + assert list(out.shape) == [batch_size, 100, out_channels] + else: + assert list(out.shape) == [100, out_channels] + + # Check backward pass + if gno_batched: + loss = out[0].sum() + else: + loss = out.sum() + loss.backward() + n_unused_params = 0 + for param in model.parameters(): + if param.grad is None: + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + if gno_batched: + # assert f[1:] accumulates no grad + assert not f.grad[1:].nonzero().any() + + +def test_fnogno_group_norm(): + """Test FNOGNO with group_norm and custom fno_norm_groups""" + fno_norm_groups = 4 + model = FNOGNO( + in_channels=3, + out_channels=2, + gno_radius=0.2, + gno_coord_dim=2, + fno_n_modes=(8, 8), + fno_hidden_channels=16, + fno_norm="group_norm", + fno_norm_groups=fno_norm_groups, + gno_use_open3d=False, + ) + + for norm_layer in model.fno_blocks.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == fno_norm_groups diff --git a/sources/neuraloperator/neuralop/models/tests/test_gino.py b/sources/neuraloperator/neuralop/models/tests/test_gino.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd3f049019da3fd81bf4b397a63de991383eb4d --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_gino.py @@ -0,0 +1,142 @@ +import torch +import pytest +from tensorly import tenalg + +tenalg.set_backend("einsum") + +# Parameterize use of torch_scatter if it is built +try: + from torch_scatter import segment_csr + + use_torch_scatter = [True, False] +except: + use_torch_scatter = [False] + +from ..gino import GINO + +# Fixed variables +in_channels = 3 +out_channels = 2 +projection_channels = 16 +lifting_channels = 16 +fno_n_modes = (8, 8, 8) + +# data parameters +n_in = 100 +n_out = 100 +latent_density = 8 +fno_ada_in_dim = 1 +fno_ada_in_features = 4 + + +@pytest.mark.parametrize("batch_size", [1, 4]) +@pytest.mark.parametrize("gno_coord_dim", [2, 3]) +@pytest.mark.parametrize("gno_pos_embed_type", [None, "transformer"]) +@pytest.mark.parametrize( + "gno_transform_type", ["linear", "nonlinear_kernelonly", "nonlinear"] +) +@pytest.mark.parametrize("latent_feature_dim", [None, 2]) +@pytest.mark.parametrize("use_torch_scatter", use_torch_scatter) +def test_gino(gno_transform_type, latent_feature_dim, gno_coord_dim, gno_pos_embed_type, batch_size, use_torch_scatter): + if torch.backends.cuda.is_built(): + device = torch.device("cuda:0") + else: + device = torch.device("cpu:0") + + model = GINO( + in_channels=in_channels, + out_channels=out_channels, + latent_feature_channels=latent_feature_dim, + in_gno_radius=0.3, # make this large to ensure neighborhoods overlap with queries on the domain + out_gno_radius=0.3, + gno_use_torch_scatter=use_torch_scatter, + projection_channel_ratio=projection_channels, + gno_coord_dim=gno_coord_dim, + in_gno_pos_embed_type=gno_pos_embed_type, + out_gno_pos_embed_type=gno_pos_embed_type, + in_gno_channel_mlp_hidden_layers=[16, 16], + out_gno_channel_mlp_hidden_layers=[16, 16], + in_gno_transform_type=gno_transform_type, + out_gno_transform_type=gno_transform_type, + fno_n_modes=fno_n_modes[:gno_coord_dim], + fno_ada_in_dim=fno_ada_in_dim, + fno_ada_in_features=fno_ada_in_features, + # keep the FNO model small for runtime + fno_lifting_channel_ratio=lifting_channels, + ).to(device) + + # create grid of latent queries on the unit cube + latent_geom = torch.stack( + torch.meshgrid( + [torch.linspace(0, 1, latent_density)] * gno_coord_dim, indexing="xy" + ) + ) + latent_geom = latent_geom.permute(*list(range(1, gno_coord_dim + 1)), 0).to(device) + + if latent_feature_dim is not None: + latent_features_shape = [batch_size, *latent_geom.shape[:-1], latent_feature_dim] + latent_features = torch.randn(*latent_features_shape, device=device) + else: + latent_features = None + # create input geometry and output queries + input_geom_shape = [n_in, gno_coord_dim] + input_geom = torch.randn(*input_geom_shape, device=device) + output_queries_shape = [n_out, gno_coord_dim] + output_queries = torch.randn(*output_queries_shape, device=device) + + # create data and features + x_shape = [batch_size, n_in, in_channels] + x = torch.randn(*x_shape, device=device) + # require and retain grad to check for backprop + x.requires_grad_(True) + + # Test forward pass + out = model( + x=x, + input_geom=input_geom, + latent_queries=latent_geom, + output_queries=output_queries, + latent_features=latent_features, + ada_in=None, + ) + + # Check output size + assert list(out.shape) == [batch_size, n_out, out_channels] + + # Check backward pass + assert out.isfinite().all() + if batch_size > 1: + loss = out[0].sum() + else: + loss = out.sum() + loss.backward() + n_unused_params = 0 + for name, param in model.named_parameters(): + if param.grad is None: + print(name) + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + if batch_size > 1: + # assert f[1:] accumulates no grad + assert not x.grad[1:].nonzero().any() + + +def test_gino_group_norm(): + """Test GINO with group_norm and custom fno_norm_groups""" + fno_norm_groups = 4 + model = GINO( + in_channels=in_channels, + out_channels=out_channels, + gno_coord_dim=3, + in_gno_radius=0.3, + out_gno_radius=0.3, + fno_n_modes=fno_n_modes, + fno_hidden_channels=16, + fno_norm="group_norm", + fno_norm_groups=fno_norm_groups, + gno_use_open3d=False, + ) + + for norm_layer in model.fno_blocks.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == fno_norm_groups diff --git a/sources/neuraloperator/neuralop/models/tests/test_local_no.py b/sources/neuraloperator/neuralop/models/tests/test_local_no.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad4d82e3adc474ecaebdabdc9164e47b3d3f598 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_local_no.py @@ -0,0 +1,166 @@ +from math import prod + +import pytest +import torch +from tensorly import tenalg + +try: + import torch_harmonics +except ModuleNotFoundError: + pytest.skip("Skipping because torch_harmonics is not installed", allow_module_level=True) + +from neuralop.models import LocalNO + +tenalg.set_backend("einsum") + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +@pytest.mark.parametrize("mix_derivatives", [True, False]) +def test_local_no_without_disco( + n_dim, + mix_derivatives, +): + if torch.cuda.is_available(): + device = "cuda" + s = 32 + modes = 8 + width = 16 + batch_size = 4 + n_layers = 4 + else: + device = "cpu" + fno_block_precision = "full" + s = 32 + modes = 5 + width = 15 + batch_size = 3 + n_layers = 2 + + rank = 0.2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + conv_padding_mode = "zeros" + model = LocalNO( + in_channels=3, + out_channels=1, + default_in_shape=size, + diff_layers=True, + mix_derivatives=mix_derivatives, + disco_layers=False, + conv_padding_mode=conv_padding_mode, + hidden_channels=width, + n_modes=n_modes, + rank=rank, + fixed_rank_modes=False, + n_layers=n_layers, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Check backward pass + loss = out.sum() + loss.backward() + + n_unused_params = 0 + for param in model.parameters(): + if param.grad is None: + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + +@pytest.mark.parametrize('disco_layers', [ + True, + [True, False, True, False], + [False, False, False, True] +]) +@pytest.mark.parametrize('disco_kernel_shape', [ + [2,4], + [3,3], +]) +def test_local_no_with_disco( + disco_layers, + disco_kernel_shape +): + + n_dim = 2 + if torch.cuda.is_available(): + device = "cuda" + s = 32 + modes = 8 + width = 16 + batch_size = 4 + n_layers = 4 + else: + device = "cpu" + s = 32 + modes = 5 + width = 15 + batch_size = 3 + n_layers = 2 + + if isinstance(disco_layers, list): + disco_layers = disco_layers[:n_layers] + rank = 0.2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + + model = LocalNO( + in_channels=3, + out_channels=1, + default_in_shape=size, + disco_layers=disco_layers, + disco_kernel_shape=disco_kernel_shape, + hidden_channels=width, + n_modes=n_modes, + rank=rank, + fixed_rank_modes=False, + n_layers=n_layers, + ).to(device) + + in_data = torch.randn(batch_size, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Check backward pass + loss = out.sum() + loss.backward() + + n_unused_params = 0 + for param in model.parameters(): + if param.grad is None: + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + + +def test_local_no_group_norm(): + """Test LocalNO with group_norm and custom norm_groups""" + norm_groups = 4 + hidden_channels = 16 + size = (12, 12) + model = LocalNO( + in_channels=3, + out_channels=1, + default_in_shape=size, + hidden_channels=hidden_channels, + n_modes=(5, 5), + n_layers=2, + diff_layers=True, + disco_layers=False, + conv_padding_mode="zeros", + norm="group_norm", + norm_groups=norm_groups, + ) + + for norm_layer in model.local_no_blocks.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + assert norm_layer.num_channels == hidden_channels diff --git a/sources/neuraloperator/neuralop/models/tests/test_otno.py b/sources/neuraloperator/neuralop/models/tests/test_otno.py new file mode 100644 index 0000000000000000000000000000000000000000..e90d6f8188090b5714f1201e1a699957d9f63580 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_otno.py @@ -0,0 +1,126 @@ +import torch +import pytest + +from ..otno import OTNO + +# Fixed variables +in_channels = 9 +out_channels = 1 +hidden_channels = 16 +n_modes = [16, 16] +lifting_channel_ratio = 3 +projection_channel_ratio = 3 +n_layers = 4 + +# data parameters +n_s_sqrt = 18 +n_target_points = 100 + + +@pytest.mark.parametrize("positional_embedding", [None, "grid"]) +@pytest.mark.parametrize("use_channel_mlp", [True, False]) +@pytest.mark.parametrize("domain_padding", [None, 0.2]) +def test_otno(positional_embedding, use_channel_mlp, domain_padding): + """Test OTNO forward/backward with various constructor options.""" + if torch.cuda.is_available(): + device = torch.device("cuda:0") + else: + device = torch.device("cpu:0") + + # OTNO is designed for batch_size = 1 + batch_size = 1 + + model = OTNO( + n_modes=n_modes, + hidden_channels=hidden_channels, + in_channels=in_channels, + out_channels=out_channels, + lifting_channel_ratio=lifting_channel_ratio, + projection_channel_ratio=projection_channel_ratio, + use_channel_mlp=use_channel_mlp, + channel_mlp_expansion=1.0 if use_channel_mlp else None, + channel_mlp_dropout=0, + norm="group_norm", + n_layers=n_layers, + positional_embedding=positional_embedding, + domain_padding=domain_padding, + ).to(device) + + # Create input data + x_shape = [batch_size, in_channels, n_s_sqrt, n_s_sqrt] + x = torch.randn(*x_shape, device=device) + x.requires_grad_(True) + + # Create decoding indices + n_latent_points = n_s_sqrt * n_s_sqrt + ind_dec = torch.randint(0, n_latent_points, (n_target_points,), device=device) + + # Test forward pass + out = model(x=x, ind_dec=ind_dec) + + # Check output size (batch_size fixed to 1) + assert list(out.shape) == [batch_size, n_target_points] + + # Check backward pass + assert out.isfinite().all() + loss = out.sum() + loss.backward() + n_unused_params = 0 + for name, param in model.named_parameters(): + if param.grad is None: + print(name) + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + + +@pytest.mark.parametrize("n_s_sqrt", [8, 12, 18]) +@pytest.mark.parametrize("n_target_points", [10, 50, 100]) +def test_otno_output_shape(n_s_sqrt, n_target_points): + """Test OTNO output shape for different grid sizes and target point counts.""" + if torch.cuda.is_available(): + device = torch.device("cuda:0") + else: + device = torch.device("cpu:0") + + batch_size = 1 + n_latent_points = n_s_sqrt * n_s_sqrt + # ensure we don't request more target points than latent points + n_target_points = min(n_target_points, n_latent_points) + + model = OTNO( + n_modes=[min(8, n_s_sqrt)] * 2, + hidden_channels=8, + in_channels=4, + out_channels=1, + lifting_channel_ratio=2, + projection_channel_ratio=2, + n_layers=2, + use_channel_mlp=False, + norm="group_norm", + ).to(device) + + x = torch.randn(batch_size, 4, n_s_sqrt, n_s_sqrt, device=device) + ind_dec = torch.randint(0, n_latent_points, (n_target_points,), device=device) + + out = model(x=x, ind_dec=ind_dec) + + assert list(out.shape) == [batch_size, n_target_points] + assert out.isfinite().all() + + +def test_otno_group_norm(): + """Test OTNO with group_norm and custom norm_groups""" + norm_groups = 4 + model = OTNO( + n_modes=n_modes, + hidden_channels=hidden_channels, + in_channels=in_channels, + out_channels=out_channels, + n_layers=n_layers, + norm="group_norm", + norm_groups=norm_groups, + ) + + for norm_layer in model.fno_blocks.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups diff --git a/sources/neuraloperator/neuralop/models/tests/test_rno.py b/sources/neuraloperator/neuralop/models/tests/test_rno.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f30a532e968fa596a68774e6719c60f11119cc --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_rno.py @@ -0,0 +1,333 @@ +import torch +import torch.nn.functional as F +from neuralop.models import RNO +import pytest +from math import prod + + +@pytest.mark.parametrize("n_dim", [1, 2, 3]) +@pytest.mark.parametrize("fno_block_precision", ["full"]) +@pytest.mark.parametrize("stabilizer", [None, "tanh"]) +@pytest.mark.parametrize("lifting_channel_ratio", [1, 2]) +@pytest.mark.parametrize("preactivation", [False, True]) +def test_rno( + n_dim, + fno_block_precision, + stabilizer, + lifting_channel_ratio, + preactivation, +): + if torch.cuda.is_available(): + device = "cuda" + s = 16 + modes = 8 + width = 16 + batch_size = 4 + n_layers = 4 + else: + device = "cpu" + fno_block_precision = "full" + s = 12 + modes = 5 + width = 15 + batch_size = 2 + n_layers = 2 + + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + model = RNO( + in_channels=3, + out_channels=1, + hidden_channels=width, + n_modes=n_modes, + n_layers=n_layers, + stabilizer=stabilizer, + lifting_channel_ratio=lifting_channel_ratio, + preactivation=preactivation, + fno_block_precision=fno_block_precision, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Check backward pass + loss = out.sum() + loss.backward() + + n_unused_params = 0 + for param in model.parameters(): + if param.grad is None: + n_unused_params += 1 + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + + +@pytest.mark.parametrize( + "resolution_scaling_factor", + [ + [2, 1, 1], + [1, 2, 1], + [1, 1, 2], + [1, 2, 2], + [1, 0.5, 1], + ], +) +def test_rno_superresolution(resolution_scaling_factor): + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + batch_size = 2 + n_layers = 3 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + + model = RNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + resolution_scaling_factor=resolution_scaling_factor, + n_layers=n_layers, + ).to(device) + + print(f"{model.resolution_scaling_factor=}") + + in_data = torch.randn(batch_size, num_time_steps, 3, *size).to(device) + # Test forward pass + out = model(in_data) + + # Check output size + factor = prod(resolution_scaling_factor) + + assert list(out.shape) == [batch_size, 1] + [int(round(factor * s)) for s in size] + + +@pytest.mark.parametrize("norm", [None, "group_norm", "instance_norm"]) +@pytest.mark.parametrize("complex_data", [False, True]) +@pytest.mark.parametrize("channel_mlp_skip", ["linear", "soft-gating", None]) +def test_rno_channel_mlp_params_advanced(norm, complex_data, channel_mlp_skip): + """Test RNO with channel MLP and various advanced parameter combinations.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + + dtype = torch.cfloat if complex_data else torch.float32 + + model = RNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + norm=norm, + complex_data=complex_data, + use_channel_mlp=True, + channel_mlp_skip=channel_mlp_skip, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size, dtype=dtype).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Test backward pass + loss = out.sum() + # take the modulus if data is complex-valued to create grad + if dtype == torch.cfloat: + loss = (loss.real**2 + loss.imag**2) ** 0.5 + loss.backward() + + +@pytest.mark.parametrize("norm", [None, "group_norm"]) +@pytest.mark.parametrize("complex_data", [False, True]) +@pytest.mark.parametrize("fno_skip", ["linear", "soft-gating", None]) +def test_rno_fno_skip_params(norm, complex_data, fno_skip): + """Test RNO with FNO skip connections and various parameter combinations.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + + dtype = torch.cfloat if complex_data else torch.float32 + + model = RNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + norm=norm, + complex_data=complex_data, + use_channel_mlp=False, + fno_skip=fno_skip, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size, dtype=dtype).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + # Test backward pass + loss = out.sum() + # take the modulus if data is complex-valued to create grad + if dtype == torch.cfloat: + loss = (loss.real**2 + loss.imag**2) ** 0.5 + loss.backward() + + +@pytest.mark.parametrize("positional_embedding", ["grid", None]) +@pytest.mark.parametrize("domain_padding", [None, 0.1, [0.1, 0.2]]) +def test_rno_embedding_and_padding(positional_embedding, domain_padding): + """Test RNO with different positional embeddings and domain padding.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + projection_channel_ratio = 2 + lifting_channel_ratio = 2 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + + model = RNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + positional_embedding=positional_embedding, + domain_padding=domain_padding, + projection_channel_ratio=projection_channel_ratio, + lifting_channel_ratio=lifting_channel_ratio, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + +@pytest.mark.parametrize("channel_mlp_dropout", [0.0, 0.1]) +@pytest.mark.parametrize("channel_mlp_expansion", [0.5, 1.0]) +@pytest.mark.parametrize("non_linearity", [F.gelu, F.relu, F.tanh]) +def test_rno_channel_mlp_params(channel_mlp_dropout, channel_mlp_expansion, non_linearity): + """Test RNO with different channel MLP parameters.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + + model = RNO( + in_channels=3, + out_channels=1, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + non_linearity=non_linearity, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size).to(device) + + # Test forward pass + out = model(in_data) + + # Check output size + assert list(out.shape) == [batch_size, 1, *size] + + +def test_rno_predict(): + """Test RNO prediction functionality.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + s = 12 + modes = 5 + hidden_channels = 15 + batch_size = 2 + n_layers = 2 + n_dim = 2 + size = (s,) * n_dim + n_modes = (modes,) * n_dim + num_time_steps = 3 + num_steps = 1 + + model = RNO( + in_channels=3, + out_channels=3, + n_modes=n_modes, + hidden_channels=hidden_channels, + n_layers=n_layers, + ).to(device) + + in_data = torch.randn(batch_size, num_time_steps, 3, *size).to(device) + + # Test predict method + predictions = model.predict(in_data, num_steps) + + # Check output size + expected_shape = [batch_size, num_steps, 3] + list(size) + assert list(predictions.shape) == expected_shape + + +def test_rno_group_norm(): + """Test RNO with group_norm and custom norm_groups""" + norm_groups = 4 + width = 16 + model = RNO( + in_channels=3, + out_channels=1, + hidden_channels=width, + n_modes=(5, 5), + n_layers=2, + norm="group_norm", + norm_groups=norm_groups, + ) + + # RNO stacks RNOBlocks; each contains an RNOCell with input/hidden FNOBlocks + for rno_block in model.layers: + cell = rno_block.cell + for fno_block in [*cell.input_gates, *cell.hidden_gates]: + assert fno_block.norm is not None + for norm_layer in fno_block.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups + assert norm_layer.num_channels == width diff --git a/sources/neuraloperator/neuralop/models/tests/test_sfno.py b/sources/neuraloperator/neuralop/models/tests/test_sfno.py new file mode 100644 index 0000000000000000000000000000000000000000..d3cf9bdc6157423a2744f5d567a322e1a5000427 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_sfno.py @@ -0,0 +1,93 @@ +"""Quick tests for SFNO (Spherical FNO). SFNO is FNO with SphericalConv; 2D only.""" +import pytest +import torch + +try: + from neuralop.models import SFNO +except ImportError: + SFNO = None + +@pytest.mark.skipif(SFNO is None, reason="SFNO not available (torch_harmonics required)") +@pytest.mark.parametrize("n_modes", [(4, 4), (5, 5), (4, 6), (5, 6)]) +@pytest.mark.parametrize( + "implementation,factorization,resolution_scaling_factor,rank,fixed_rank_modes", + [ + ("factorized", "dense", None, 0.3, False), + ("reconstructed", "cp", 1.0, 0.5, False), + ("factorized", "tucker", None, 0.5, True), + ("reconstructed", "tt", 1.0, 0.2, True), + ], +) +def test_sfno_forward( + n_modes, implementation, factorization, resolution_scaling_factor, rank, fixed_rank_modes +): + """SFNO forward over n_modes, implementation, factorization, resolution scaling, rank, fixed_rank_modes.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + batch_size = 2 + size = (12, 12) + + model = SFNO( + in_channels=3, + out_channels=1, + hidden_channels=8, + n_modes=n_modes, + n_layers=2, + implementation=implementation, + factorization=factorization, + resolution_scaling_factor=resolution_scaling_factor, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + ).to(device) + x = torch.randn(batch_size, 3, *size, dtype=torch.float32).to(device) + out = model(x) + + assert out.shape == (batch_size, 1, *size) + +@pytest.mark.skipif(SFNO is None, reason="SFNO not available (torch_harmonics required)") +@pytest.mark.parametrize("n_modes", [(4, 4), (5, 5), (4, 6), (5, 6)]) +@pytest.mark.parametrize("resolution_scaling_factor,expected_scale", [(0.5, 0.5), (2.0, 2.0)]) +def test_sfno_forward_superresolution(n_modes, resolution_scaling_factor, expected_scale): + """SFNO with single layer and resolution scaling; output spatial size scales accordingly.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + batch_size = 2 + size = (12, 12) + + model = SFNO( + in_channels=3, + out_channels=1, + hidden_channels=8, + n_modes=n_modes, + n_layers=1, + resolution_scaling_factor=resolution_scaling_factor, + ).to(device) + x = torch.randn(batch_size, 3, *size, dtype=torch.float32).to(device) + out = model(x) + + expected_h = round(size[0] * expected_scale) + expected_w = round(size[1] * expected_scale) + assert out.shape == (batch_size, 1, expected_h, expected_w) + +@pytest.mark.skipif(SFNO is None, reason="SFNO not available (torch_harmonics required)") +@pytest.mark.parametrize("n_modes", [(4, 4), (5, 5), (4, 6), (5, 6)]) +@pytest.mark.parametrize("n_layers", [1, 2]) +def test_sfno_backward(n_modes, n_layers): + """SFNO backward pass runs and all parameters receive gradients.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + batch_size = 2 + size = (12, 12) + + model = SFNO( + in_channels=2, + out_channels=1, + hidden_channels=4, + n_modes=n_modes, + n_layers=n_layers, + ).to(device) + + x = torch.randn(batch_size, 2, *size, dtype=torch.float32).to(device) + out = model(x) + loss = out.sum() + loss.backward() + + for param in model.parameters(): + assert param.grad is not None, "All parameters should receive gradients" \ No newline at end of file diff --git a/sources/neuraloperator/neuralop/models/tests/test_uno.py b/sources/neuraloperator/neuralop/models/tests/test_uno.py new file mode 100644 index 0000000000000000000000000000000000000000..8795cd8c6145920b95d8632bcb21e002f3b331dd --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_uno.py @@ -0,0 +1,97 @@ +import time +from ..uno import UNO +import torch +import pytest + + +@pytest.mark.parametrize( + "input_shape", [(32, 3, 64, 55), (32, 3, 100, 105), (32, 3, 133, 95)] +) +def test_UNO(input_shape): + horizontal_skips_map = {4: 0, 3: 1} + model = UNO( + 3, + 3, + 5, + uno_out_channels=[32, 64, 64, 64, 32], + uno_n_modes=[[5, 5], [5, 5], [5, 5], [5, 5], [5, 5]], + uno_scalings=[[1.0, 1.0], [0.5, 0.25], [1, 1], [1, 1], [2, 4]], + horizontal_skips_map=horizontal_skips_map, + n_layers=5, + domain_padding=0.2, + channel_mlp_skip="linear", + ) + + t1 = time.time() + in_data = torch.randn(input_shape) + out = model(in_data) + t = time.time() - t1 + print(f"Output of size {out.shape} in {t}.") + for i in range(len(out.shape)): + assert in_data.shape[i] == out.shape[i] + loss = out.sum() + t1 = time.time() + loss.backward() + t = time.time() - t1 + print(f"Gradient Calculated in {t}.") + n_unused_params = 0 + + for name, param in model.named_parameters(): + if param.grad is None: + n_unused_params += 1 + + model = UNO( + 3, + 3, + 5, + uno_out_channels=[32, 64, 64, 64, 32], + uno_n_modes=[[5, 5], [5, 5], [5, 5], [5, 5], [5, 5]], + uno_scalings=[[1.0, 1.0], [0.5, 0.5], [1, 1], [1, 1], [2, 2]], + horizontal_skips_map=None, + n_layers=5, + domain_padding=0.2, + channel_mlp_skip="linear", + ) + + t1 = time.time() + in_data = torch.randn(input_shape) + out = model(in_data) + t = time.time() - t1 + print(f"Output of size {out.shape} in {t}.") + + loss = out.sum() + t1 = time.time() + loss.backward() + t = time.time() - t1 + print(f"Gradient Calculated in {t}.") + n_unused_params = 0 + + for name, param in model.named_parameters(): + if param.grad is None: + n_unused_params += 1 + + assert n_unused_params == 0, f"{n_unused_params} parameters were unused!" + + +def test_uno_group_norm(): + """Test UNO with group_norm and custom norm_groups""" + norm_groups = 4 + model = UNO( + in_channels=3, + out_channels=3, + hidden_channels=16, + uno_out_channels=[16, 16, 16], + uno_n_modes=[[5, 5], [5, 5], [5, 5]], + uno_scalings=[[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]], + n_layers=3, + norm="group_norm", + norm_groups=norm_groups, + channel_mlp_skip="linear", + ) + + # UNO stores one operator block per layer in self.fno_blocks + for fno_block in model.fno_blocks: + assert fno_block.norm is not None + for norm_layer in fno_block.norm: + assert isinstance(norm_layer, torch.nn.GroupNorm) + assert norm_layer.num_groups == norm_groups diff --git a/sources/neuraloperator/neuralop/models/tests/test_uqno.py b/sources/neuraloperator/neuralop/models/tests/test_uqno.py new file mode 100644 index 0000000000000000000000000000000000000000..edd46f032c5308c95a7753db64291ad78775332c --- /dev/null +++ b/sources/neuraloperator/neuralop/models/tests/test_uqno.py @@ -0,0 +1,33 @@ +from pathlib import Path +import shutil + +from neuralop.tests.test_utils import DummyModel +from ..uqno import UQNO + + +def test_uqno_train_eval(): + dummy_uq = UQNO(base_model=DummyModel(50), residual_model=DummyModel(50)) + + dummy_uq.train() + assert dummy_uq.base_model.training + assert dummy_uq.residual_model.training + + dummy_uq.eval() + assert not dummy_uq.base_model.training + assert not dummy_uq.residual_model.training + + +def test_uqno_checkpoint(): + dummy_uq = UQNO(base_model=DummyModel(50), residual_model=DummyModel(50)) + + checkpoint_path = Path("./test_checkpoints") + dummy_uq.save_checkpoint(save_folder=checkpoint_path, save_name="uqno") + save_path = checkpoint_path / "uqno_state_dict.pt" + assert save_path.exists() + + metadata_path = checkpoint_path / "uqno_metadata.pkl" + assert metadata_path.exists + + dummy_uq = UQNO.from_checkpoint(checkpoint_path, "uqno") + + shutil.rmtree(checkpoint_path) diff --git a/sources/neuraloperator/neuralop/models/uno.py b/sources/neuraloperator/neuralop/models/uno.py new file mode 100644 index 0000000000000000000000000000000000000000..fc85cf68fc021fc7aaafff57d16a1fcaa4d1f1a6 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/uno.py @@ -0,0 +1,371 @@ +import torch.nn as nn +import torch.nn.functional as F +import torch + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + +from ..layers.channel_mlp import ChannelMLP +from ..layers.spectral_convolution import SpectralConv +from ..layers.skip_connections import skip_connection +from ..layers.padding import DomainPadding +from ..layers.fno_block import FNOBlocks +from ..layers.resample import resample +from ..layers.embeddings import GridEmbedding2D, GridEmbeddingND + + +class UNO(nn.Module): + """U-Shaped Neural Operator + + The architecture is described in [1]_. + + Parameters + ---------- + in_channels : int + Number of input channels. Determined by the problem. + out_channels : int + Number of output channels. Determined by the problem. + hidden_channels : int + Initial width of the UNO. This significantly affects the number of parameters of the UNO. + Good starting point can be 64, and then increased if more expressivity is needed. + Update lifting_channels and projection_channels accordingly since they are proportional to hidden_channels. + uno_out_channels : list + Number of output channels of each Fourier layer. + Example: For a five layer UNO uno_out_channels can be [32,64,64,64,32] + uno_n_modes : list + Number of Fourier modes to use in integral operation of each Fourier layer (along each dimension). + Example: For a five layer UNO with 2D input the uno_n_modes can be: [[5,5],[5,5],[5,5],[5,5],[5,5]] + uno_scalings : list + Scaling factors for each Fourier layer. + Example: For a five layer UNO with 2D input, the uno_scalings can be: [[1.0,1.0],[0.5,0.5],[1,1],[1,1],[2,2]] + n_layers : int, optional + Number of Fourier layers. Default: 4 + lifting_channels : int, optional + Number of hidden channels of the lifting block of the FNO. Default: 256 + projection_channels : int, optional + Number of hidden channels of the projection block of the FNO. Default: 256 + positional_embedding : Union[str, GridEmbedding2D, GridEmbeddingND, None], optional + Positional embedding to apply to last channels of raw input before being passed through the UNO. + 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. + - GridEmbedding2D: Uses this module directly for 2D cases. + - GridEmbeddingND: Uses this module directly (see `neuralop.embeddings.GridEmbeddingND` for details). + - None: Does nothing. + Default: "grid" + horizontal_skips_map : Dict, optional + A dictionary {b: a, ...} denoting horizontal skip connection from a-th layer to b-th layer. + If None, default skip connection is applied. + Example: For a 5 layer UNO architecture, the skip connections can be horizontal_skips_map = {4:0,3:1} + Default: None + channel_mlp_dropout : float, optional + Dropout parameter for ChannelMLP after each FNO block. Default: 0 + channel_mlp_expansion : float, optional + Expansion parameter for ChannelMLP after each FNO block. Default: 0.5 + non_linearity : nn.Module, optional + Non-linearity module to use. Default: F.gelu + norm : str, optional + Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", None. Default: None + norm_groups : int, optional + Number of groups for GroupNorm, by default 1 + preactivation : bool, optional + Whether to use ResNet-style preactivation. Default: False + fno_skip : str, optional + Type of skip connection to use in FNO layers. Options: "linear", "identity", "soft-gating", None. + Default: "linear" + horizontal_skip : str, optional + Type of skip connection to use in horizontal connections. Options: "linear", "identity", "soft-gating", None. + Default: "linear" + channel_mlp_skip : str, optional + Type of skip connection to use in channel-mixing MLP. Options: "linear", "identity", "soft-gating", None. + Default: "soft-gating" + separable : bool, optional + Whether to use a separable spectral convolution. Default: False + factorization : str, optional + Tensor factorization of the parameters weight to use. + Options: "None", "Tucker", "CP", "TT" + Other factorization methods supported by tltorch. Default: None + rank : float, optional + Rank of the tensor factorization of the Fourier weights. Default: 1.0. + Set to float <1.0 when using TFNO (i.e. when factorization is not None). + A TFNO with rank 0.1 has roughly 10% of the parameters of a dense FNO. + fixed_rank_modes : bool, optional + Whether to not factorize certain modes. Default: False + implementation : str, optional + If factorization is not None, forward mode to use. + Options: "reconstructed", "factorized". Default: "factorized" + decomposition_kwargs : dict, optional + Additional parameters to pass to the tensor decomposition. Default: {} + domain_padding : Union[float, List[float], None], optional + Percentage of padding to use. If not None, percentage of padding to use. Default: None + fft_norm : str, optional + FFT normalization mode. Default: "forward" + enforce_hermitian_symmetry : bool, optional + Whether to enforce Hermitian symmetry conditions when performing inverse FFT + for real-valued data. Only used when the convolution module is :class:`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. + + References + ---------- + .. [1] : + + Rahman, M.A., Ross, Z., Azizzadenesheli, K. "U-NO: U-shaped + Neural Operators" (2022). TMLR 2022, https://arxiv.org/pdf/2204.11127. + """ + + def __init__( + self, + in_channels, + out_channels, + hidden_channels, + lifting_channels=256, + projection_channels=256, + positional_embedding="grid", + n_layers=4, + uno_out_channels=None, + uno_n_modes=None, + uno_scalings=None, + horizontal_skips_map=None, + channel_mlp_dropout=0, + channel_mlp_expansion=0.5, + non_linearity=F.gelu, + norm=None, + norm_groups=1, + preactivation=False, + fno_skip="linear", + horizontal_skip="linear", + channel_mlp_skip="soft-gating", + separable=False, + factorization=None, + rank=1.0, + fixed_rank_modes=False, + integral_operator=SpectralConv, + operator_block=FNOBlocks, + implementation="factorized", + decomposition_kwargs=dict(), + domain_padding=None, + verbose=False, + enforce_hermitian_symmetry=True, + ): + super().__init__() + self.n_layers = n_layers + assert uno_out_channels is not None, "uno_out_channels can not be None" + assert uno_n_modes is not None, "uno_n_modes can not be None" + assert uno_scalings is not None, "uno_scalings can not be None" + assert ( + len(uno_out_channels) == n_layers + ), "Output channels for all layers are not given" + assert ( + len(uno_n_modes) == n_layers + ), "number of modes for all layers are not given" + assert ( + len(uno_scalings) == n_layers + ), "Scaling factor for all layers are not given" + + self.n_dim = len(uno_n_modes[0]) + self.uno_out_channels = uno_out_channels + self.uno_n_modes = uno_n_modes + self.uno_scalings = uno_scalings + self.hidden_channels = hidden_channels + self.lifting_channels = lifting_channels + self.projection_channels = projection_channels + self.in_channels = in_channels + self.out_channels = out_channels + self.horizontal_skips_map = horizontal_skips_map + self.non_linearity = non_linearity + self.rank = rank + self.factorization = factorization + self.fixed_rank_modes = fixed_rank_modes + self.decomposition_kwargs = decomposition_kwargs + self.fno_skip = (fno_skip,) + self.channel_mlp_skip = (channel_mlp_skip,) + self.implementation = implementation + self.separable = separable + self.preactivation = preactivation + + self.operator_block = operator_block + self.integral_operator = integral_operator + + # create positional embedding at the beginning of the model + if positional_embedding == "grid": + spatial_grid_boundaries = [[0.0, 1.0]] * self.n_dim + self.positional_embedding = GridEmbeddingND( + in_channels=self.in_channels, + dim=self.n_dim, + grid_boundaries=spatial_grid_boundaries, + ) + elif isinstance(positional_embedding, GridEmbedding2D): + if self.n_dim == 2: + self.positional_embedding = positional_embedding + else: + raise ValueError(f'Error: expected {self.n_dim}-d positional embeddings, got {positional_embedding}') + elif isinstance(positional_embedding, GridEmbeddingND): + self.positional_embedding = positional_embedding + elif positional_embedding == None: + self.positional_embedding = None + else: + raise ValueError( + f"Error: tried to instantiate FNO positional embedding with {positional_embedding},\ + expected one of 'grid', GridEmbeddingND" + ) + + if self.positional_embedding is not None: + in_channels += self.n_dim + + # constructing default skip maps + if self.horizontal_skips_map is None: + self.horizontal_skips_map = {} + for i in range( + 0, + n_layers // 2, + ): + # example, if n_layers = 5, then 4:0, 3:1 + self.horizontal_skips_map[n_layers - i - 1] = i + # self.uno_scalings may be a 1d list specifying uniform scaling factor at each layer + # or a 2d list, where each row specifies scaling factors along each dimention. + # To get the final (end to end) scaling factors we need to multiply + # the scaling factors (a list) of all layer. + + self.end_to_end_scaling_factor = [1] * len(self.uno_scalings[0]) + # multiplying scaling factors + for k in self.uno_scalings: + self.end_to_end_scaling_factor = [ + i * j for (i, j) in zip(self.end_to_end_scaling_factor, k) + ] + + # list with a single element is replaced by the scaler. + if len(self.end_to_end_scaling_factor) == 1: + self.end_to_end_scaling_factor = self.end_to_end_scaling_factor[0] + + if isinstance(self.end_to_end_scaling_factor, (float, int)): + self.end_to_end_scaling_factor = [ + self.end_to_end_scaling_factor + ] * self.n_dim + + if verbose: + print("calculated out factor", self.end_to_end_scaling_factor) + + if domain_padding is not None and ( + (isinstance(domain_padding, list) and sum(domain_padding) > 0) + or (isinstance(domain_padding, (float, int)) and domain_padding > 0) + ): + self.domain_padding = DomainPadding( + domain_padding=domain_padding, + resolution_scaling_factor=self.end_to_end_scaling_factor, + ) + else: + self.domain_padding = None + + self.lifting = ChannelMLP( + in_channels=in_channels, + out_channels=self.hidden_channels, + hidden_channels=self.lifting_channels, + n_layers=2, + n_dim=self.n_dim, + ) + self.fno_blocks = nn.ModuleList([]) + self.horizontal_skips = torch.nn.ModuleDict({}) + prev_out = self.hidden_channels + + for i in range(self.n_layers): + if i in self.horizontal_skips_map.keys(): + prev_out = ( + prev_out + self.uno_out_channels[self.horizontal_skips_map[i]] + ) + + self.fno_blocks.append( + self.operator_block( + in_channels=prev_out, + out_channels=self.uno_out_channels[i], + n_modes=self.uno_n_modes[i], + channel_mlp_dropout=channel_mlp_dropout, + channel_mlp_expansion=channel_mlp_expansion, + resolution_scaling_factor=[self.uno_scalings[i]], + non_linearity=non_linearity, + norm=norm, + norm_groups=norm_groups, + preactivation=preactivation, + fno_skip=fno_skip, + channel_mlp_skip=channel_mlp_skip, + rank=rank, + fixed_rank_modes=fixed_rank_modes, + implementation=implementation, + separable=separable, + factorization=factorization, + decomposition_kwargs=decomposition_kwargs, + conv_module=self.integral_operator, + enforce_hermitian_symmetry=enforce_hermitian_symmetry, + ) + ) + + if i in self.horizontal_skips_map.values(): + self.horizontal_skips[str(i)] = skip_connection( + self.uno_out_channels[i], + self.uno_out_channels[i], + skip_type=horizontal_skip, + n_dim=self.n_dim, + ) + + prev_out = self.uno_out_channels[i] + + self.projection = ChannelMLP( + in_channels=prev_out, + out_channels=out_channels, + hidden_channels=self.projection_channels, + n_layers=2, + n_dim=self.n_dim, + non_linearity=non_linearity, + ) + + def forward(self, x, **kwargs): + if kwargs: + warnings.warn( + f"UNO.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + + if self.positional_embedding is not None: + x = self.positional_embedding(x) + + x = self.lifting(x) + + if self.domain_padding is not None: + x = self.domain_padding.pad(x) + output_shape = [ + int(round(i * j)) + for (i, j) in zip(x.shape[-self.n_dim :], self.end_to_end_scaling_factor) + ] + + skip_outputs = {} + cur_output = None + for layer_idx in range(self.n_layers): + if layer_idx in self.horizontal_skips_map.keys(): + skip_val = skip_outputs[self.horizontal_skips_map[layer_idx]] + resolution_scaling_factors = [ + m / n for (m, n) in zip(x.shape, skip_val.shape) + ] + resolution_scaling_factors = resolution_scaling_factors[-1 * self.n_dim :] + t = resample( + skip_val, resolution_scaling_factors, list(range(-self.n_dim, 0)) + ) + x = torch.cat([x, t], dim=1) + + if layer_idx == self.n_layers - 1: + cur_output = output_shape + x = self.fno_blocks[layer_idx](x, output_shape=cur_output) + + if layer_idx in self.horizontal_skips_map.values(): + skip_outputs[layer_idx] = self.horizontal_skips[str(layer_idx)](x) + + if self.domain_padding is not None: + x = self.domain_padding.unpad(x) + + x = self.projection(x) + return x diff --git a/sources/neuraloperator/neuralop/models/uqno.py b/sources/neuraloperator/neuralop/models/uqno.py new file mode 100644 index 0000000000000000000000000000000000000000..bad45b1ecbdead28344981b3b3a40e186e66ad73 --- /dev/null +++ b/sources/neuraloperator/neuralop/models/uqno.py @@ -0,0 +1,60 @@ +from copy import deepcopy + +import torch +import torch.nn as nn + + +from .base_model import BaseModel + + +class UQNO(BaseModel, name="UQNO"): + """Uncertainty Quantification Neural Operator + + General N-dim (alpha, delta) Risk-Controlling Neural Operator, as described in [1]_. + + The UQNO is trained to map input functions to a residual function + E(a, x) that describes the predicted error between the ground truth + and the outputs of a trained model. E(a, x) is then used in combination + with a calibrated scaling factor to predict calibrated uncertainty bands + around the predictions of the trained model. + + Parameters + ---------- + base_model : nn.Module + Pre-trained solution operator. Determined by the problem. + residual_model : nn.Module, optional + Architecture to train as the UQNO's quantile model. + If None, a deep copy of base_model is used. Default: None + + References + ---------- + .. [1] : + + Ma, Z., Pitt, D., Azizzadenesheli, K., and Anandkumar, A. (2024). + "Calibrated Uncertainty Quantification for Operator Learning + via Conformal Prediction". TMLR, https://openreview.net/pdf?id=cGpegxy12T. + """ + + def __init__( + self, base_model: nn.Module, residual_model: nn.Module = None, **kwargs + ): + super().__init__() + + self.base_model = base_model + if residual_model is None: + residual_model = deepcopy(base_model) + self.residual_model = residual_model + + def forward(self, *args, **kwargs): + """ + Forward pass returns the solution u(a,x) + and the uncertainty ball E(a,x) as a pair + for pointwise quantile loss + """ + self.base_model.eval() # base-model weights are frozen + # another way to handle this would be to use LoRA, or similar + # ie freeze the weights, and train a low-rank matrix of weight perturbations + with torch.no_grad(): + solution = self.base_model(*args, **kwargs) + quantile = self.residual_model(*args, **kwargs) + return (solution, quantile) diff --git a/sources/neuraloperator/neuralop/mpu/__init__.py b/sources/neuraloperator/neuralop/mpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/mpu/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/mpu/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43d31b6e37af5ee091b1b5dbdf8f4c2bf649d093 Binary files /dev/null and b/sources/neuraloperator/neuralop/mpu/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/mpu/__pycache__/comm.cpython-313.pyc b/sources/neuraloperator/neuralop/mpu/__pycache__/comm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6a2b02299ab944a8390d4c5729ac9bcc9f5bf4 Binary files /dev/null and b/sources/neuraloperator/neuralop/mpu/__pycache__/comm.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/mpu/__pycache__/helpers.cpython-313.pyc b/sources/neuraloperator/neuralop/mpu/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c1164a9edb8a86ab64b0a7536793241cc7d3235 Binary files /dev/null and b/sources/neuraloperator/neuralop/mpu/__pycache__/helpers.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/mpu/__pycache__/mappings.cpython-313.pyc b/sources/neuraloperator/neuralop/mpu/__pycache__/mappings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8948e1ee2d08757048fd219210313f18e46497b5 Binary files /dev/null and b/sources/neuraloperator/neuralop/mpu/__pycache__/mappings.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/mpu/comm.py b/sources/neuraloperator/neuralop/mpu/comm.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5ecb1db3606548729b371bf0140e7e13e65ad3 --- /dev/null +++ b/sources/neuraloperator/neuralop/mpu/comm.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +import logging +import torch +import torch.distributed as dist +import datetime as dt + + +class disable_logging(object): + def __init__(self, level=logging.ERROR): + logging.disable(level=level) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + logging.disable(level=logging.NOTSET) + + +# dummy placeholders +_DATA_PARALLEL_GROUP = None +_MODEL_PARALLEL_GROUP = None + + +# world comm +def get_world_size(): + if not dist.is_initialized(): + return 1 + else: + return dist.get_world_size() + + +def get_local_rank(): + if not dist.is_initialized(): + return 0 + else: + return dist.get_rank() + + +def get_global_rank(): + if not dist.is_initialized(): + return 0 + else: + return dist.get_global_rank( + group=_DATA_PARALLEL_GROUP, group_rank=get_local_rank() + ) + + +# data parallel +def get_data_parallel_size(): + if not dist.is_initialized(): + return 1 + else: + return dist.get_world_size(group=_DATA_PARALLEL_GROUP) + + +def get_data_parallel_rank(): + if not dist.is_initialized(): + return 0 + else: + return dist.get_rank(group=_DATA_PARALLEL_GROUP) + + +def get_data_parallel_group(): + assert dist.is_initialized(), "Error, initialize torch.distributed first" + return _DATA_PARALLEL_GROUP + + +# model parallel +def get_model_parallel_size(): + if not dist.is_initialized() or (_MODEL_PARALLEL_GROUP is None): + return 1 + else: + return dist.get_world_size(group=_MODEL_PARALLEL_GROUP) + + +def get_model_parallel_rank(): + if not dist.is_initialized() or (_MODEL_PARALLEL_GROUP is None): + return 0 + else: + return dist.get_rank(group=_MODEL_PARALLEL_GROUP) + + +def get_model_parallel_group(): + assert dist.is_initialized(), "Error, initialize torch.distributed first" + return _MODEL_PARALLEL_GROUP + + +def init(model_parallel_size: int = 1, verbose: bool = False): + """ + Set up global and local communicator. + `torchrun` initializes rank env vars by default and uses its own wireup logic + """ + + local_rank = int(os.getenv("LOCAL_RANK", 0)) + global_rank = int(os.getenv("RANK", 0)) + world_size = torch.cuda.device_count() + + if world_size > 1: + with disable_logging(): + # initialize process groups + dist.init_process_group(backend="nccl", rank=local_rank) + + # once initialized, get true values for rank and size using torch.distributed + world_size = get_world_size() + local_rank = get_local_rank() + + # set a barrier until all processes reach this point + dist.barrier(device_ids=[local_rank]) + + # process 0 is logger + is_logger = get_local_rank() == 0 + + # get model groups + model_group_size = model_parallel_size + + # compute data parallel size + data_group_size = world_size // model_group_size + + if is_logger: + print(f"Using {world_size} in {model_group_size} x {data_group_size} decomposition (#model-ranks x #data-ranks)") + + assert ( (model_group_size <= world_size) and (world_size % model_group_size == 0) ), \ + "Error, please make sure matmul_parallel_size * spatial_parallel_size <= world size and that world size is evenly divisible by matmul_parallel_size * spatial_parallel_size" + + # number of model groups + num_model_groups = world_size // model_group_size + + global _DATA_PARALLEL_GROUP + global _MODEL_PARALLEL_GROUP + + if is_logger: + print("Starting Wireup") + + if world_size > 1: + if model_group_size > 1: + model_groups = [] + for i in range(num_model_groups): + start = i * model_group_size + end = start + model_group_size + model_groups.append(list(range(start, end))) + + data_groups = [sorted(list(i)) for i in zip(*model_groups)] + + if verbose and is_logger: + print("Model Parallel Groups w/ respect to world rank:") + for grp in model_groups: + print(grp) + + if verbose and is_logger: + print("Data Parallel Groups w/ respect to world rank:") + for grp in data_groups: + print(grp) + + # initialize groups + with disable_logging(): + # data groups + for grp in data_groups: + tmp_group = dist.new_group(ranks=grp) + if global_rank in grp: + _DATA_PARALLEL_GROUP = tmp_group + # model groups + for grp in model_groups: + tmp_group = dist.new_group(ranks=grp) + if global_rank in grp: + _MODEL_PARALLEL_GROUP = tmp_group + + else: + # technically unnecessary but we do it to be clean + with disable_logging(): + _MODEL_PARALLEL_GROUP = dist.new_group(ranks=[global_rank]) + _SPATIAL_PARALLEL_GROUP = _MODEL_PARALLEL_GROUP + _MATMUL_PARALLEL_GROUP = _MODEL_PARALLEL_GROUP + _DATA_PARALLEL_GROUP = dist.new_group(ranks=list(range(world_size))) + + # barrier + if dist.is_initialized(): + dist.barrier(device_ids=[local_rank]) + + if is_logger: + print("Finished Wireup") + + return diff --git a/sources/neuraloperator/neuralop/mpu/helpers.py b/sources/neuraloperator/neuralop/mpu/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..92cf7babff2002b4366fc2cbd48ba216139bc773 --- /dev/null +++ b/sources/neuraloperator/neuralop/mpu/helpers.py @@ -0,0 +1,166 @@ +# coding=utf-8 +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn.functional as F +import torch.distributed as dist + + +def get_memory_format(tensor): + if tensor.is_contiguous(memory_format=torch.channels_last): + return torch.channels_last + else: + return torch.contiguous_format + + +def pad_helper(tensor, dim, new_size, mode="zero"): + ndim = tensor.ndim + dim = (dim + ndim) % ndim + ndim_pad = ndim - dim + output_shape = [0 for _ in range(2 * ndim_pad)] + orig_size = tensor.shape[dim] + output_shape[1] = new_size - orig_size + tensor_pad = F.pad(tensor, output_shape, mode="constant", value=0.0) + + if mode == "conj": + lhs_slice = [ + slice(0, x) if idx != dim else slice(orig_size, new_size) + for idx, x in enumerate(tensor.shape) + ] + rhs_slice = [ + slice(0, x) if idx != dim else slice(1, output_shape[1] + 1) + for idx, x in enumerate(tensor.shape) + ] + tensor_pad[lhs_slice] = torch.flip( + torch.conj(tensor_pad[rhs_slice]), dims=[dim] + ) + + return tensor_pad + + +def truncate_helper(tensor, dim, new_size): + input_format = get_memory_format(tensor) + ndim = tensor.ndim + dim = (dim + ndim) % ndim + output_slice = [ + slice(0, x) if idx != dim else slice(0, new_size) + for idx, x in enumerate(tensor.shape) + ] + tensor_trunc = tensor[output_slice].contiguous(memory_format=input_format) + + return tensor_trunc + + +def split_tensor_along_dim(tensor, dim, num_chunks): + assert ( + dim < tensor.dim() + ), f"Error, tensor dimension is {tensor.dim()} which cannot be split along {dim}" + assert ( + tensor.shape[dim] % num_chunks == 0 + ), f"Error, cannot split dim {dim} evenly. Dim size is \ + {tensor.shape[dim]} and requested numnber of splits is {num_chunks}" + chunk_size = tensor.shape[dim] // num_chunks + tensor_list = torch.split(tensor, chunk_size, dim=dim) + + return tensor_list + + +# distributed primitives +def _transpose(tensor, dim0, dim1, group=None, async_op=False): + # get input format + input_format = get_memory_format(tensor) + + # get comm params + comm_size = dist.get_world_size(group=group) + + # split and local transposition + split_size = tensor.shape[dim0] // comm_size + x_send = [ + y.contiguous(memory_format=input_format) + for y in torch.split(tensor, split_size, dim=dim0) + ] + x_recv = [torch.empty_like(x_send[0]) for _ in range(comm_size)] + + # global transposition + req = dist.all_to_all(x_recv, x_send, group=group, async_op=async_op) + + return x_recv, req + + +def _reduce(input_, use_fp32=True, group=None): + """All-reduce the input tensor across model parallel group.""" + + # Bypass the function if we are using only 1 GPU. + if dist.get_world_size(group=group) == 1: + return input_ + + # All-reduce. + if use_fp32: + dtype = input_.dtype + inputf_ = input_.float() + dist.all_reduce(inputf_, group=group) + input_ = inputf_.to(dtype) + else: + dist.all_reduce(input_, group=group) + + return input_ + + +def _split(input_, dim_, group=None): + """Split the tensor along its last dimension and keep the corresponding slice.""" + # get input format + input_format = get_memory_format(input_) + + # Bypass the function if we are using only 1 GPU. + comm_size = dist.get_world_size(group=group) + if comm_size == 1: + return input_ + + # Split along last dimension. + input_list = split_tensor_along_dim(input_, dim_, comm_size) + + # Note: torch.split does not create contiguous tensors by default. + rank = dist.get_rank(group=group) + output = input_list[rank].contiguous(memory_format=input_format) + + return output + + +def _gather(input_, dim_, group=None): + """Gather tensors and concatinate along the last dimension.""" + # get input format + input_format = get_memory_format(input_) + + comm_size = dist.get_world_size(group=group) + # Bypass the function if we are using only 1 GPU. + if comm_size == 1: + return input_ + + # sanity checks + assert ( + dim_ < input_.dim() + ), f"Error, cannot gather along {dim_} for tensor with {input_.dim()} dimensions." + + # Size and dimension. + comm_rank = dist.get_rank(group=group) + + tensor_list = [torch.empty_like(input_) for _ in range(comm_size)] + tensor_list[comm_rank] = input_.contiguous(memory_format=input_format) + dist.all_gather(tensor_list, input_, group=group) + + # Note: torch.cat already creates a contiguous tensor. + output = torch.cat(tensor_list, dim=dim_).contiguous(memory_format=input_format) + + return output diff --git a/sources/neuraloperator/neuralop/mpu/mappings.py b/sources/neuraloperator/neuralop/mpu/mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..b6633b5c976ba5e11951c42fc024c0b1f7891b12 --- /dev/null +++ b/sources/neuraloperator/neuralop/mpu/mappings.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import types +from typing import Any + +import torch +import torch.distributed as dist +from .comm import get_model_parallel_group + +# torch utils +from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors + +# helper functions +from .helpers import split_tensor_along_dim +from .helpers import _reduce +from .helpers import _split +from .helpers import _gather + + +# model parallel +class _CopyToModelParallelRegion(torch.autograd.Function): + """Pass the input to the model parallel region.""" + + @staticmethod + def symbolic(graph, input_): + return input_ + + @staticmethod + def forward(ctx, input_): + return input_ + + @staticmethod + def backward(ctx, grad_output): + return _reduce(grad_output, group=get_model_parallel_group()) + + +class _ReduceFromModelParallelRegion(torch.autograd.Function): + """All-reduce the input from the model parallel region.""" + + @staticmethod + def symbolic(graph, input_): + return _reduce(input_, group=get_model_parallel_group()) + + @staticmethod + def forward(ctx, input_): + return _reduce(input_, group=get_model_parallel_group()) + + @staticmethod + def backward(ctx, grad_output): + return grad_output + + +class _ScatterToModelParallelRegion(torch.autograd.Function): + """Split the input and keep only the corresponding chuck to the rank.""" + + @staticmethod + def symbolic(graph, input_, dim_): + return _split(input_, dim_, group=get_model_parallel_group()) + + @staticmethod + def forward(ctx, input_, dim_): + ctx.dim = dim_ + return _split(input_, dim_, group=get_model_parallel_group()) + + @staticmethod + def backward(ctx, grad_output): + return _gather(grad_output, ctx.dim, group=get_model_parallel_group()), None + + +class _GatherFromModelParallelRegion(torch.autograd.Function): + """Gather the input from model parallel region and concatinate.""" + + @staticmethod + def symbolic(graph, input_, dim_): + return _gather(input_, dim_, group=get_model_parallel_group()) + + @staticmethod + def forward(ctx, input_, dim_): + ctx.dim = dim_ + return _gather(input_, dim_, group=get_model_parallel_group()) + + @staticmethod + def backward(ctx, grad_output): + return _split(grad_output, ctx.dim, group=get_model_parallel_group()), None + + +# ----------------- +# Helper functions. +# ----------------- +# matmul parallel +def copy_to_model_parallel_region(input_): + return _CopyToModelParallelRegion.apply(input_) + + +def reduce_from_model_parallel_region(input_): + return _ReduceFromModelParallelRegion.apply(input_) + + +def scatter_to_model_parallel_region(input_, dim): + return _ScatterToModelParallelRegion.apply(input_, dim) + + +def gather_from_model_parallel_region(input_, dim): + return _GatherFromModelParallelRegion.apply(input_, dim) diff --git a/sources/neuraloperator/neuralop/tests/__init__.py b/sources/neuraloperator/neuralop/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/tests/test_config.py b/sources/neuraloperator/neuralop/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fb526655867831ad9d0e48563bf4dade39a2d3 --- /dev/null +++ b/sources/neuraloperator/neuralop/tests/test_config.py @@ -0,0 +1,23 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from config.distributed import DistributedConfig +from config.models import ModelConfig, FNO_Small2d +from config.opt import OptimizationConfig, PatchingConfig +from config.wandb import WandbConfig + + +class Data(ConfigBase): + train_resolution: int = 128 + batch_size: int = 2 + + +class TestConfig(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Small2d() + data: Data = Data() + opt: OptimizationConfig = OptimizationConfig(n_epochs=10) + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/neuralop/tests/test_config_key.txt b/sources/neuraloperator/neuralop/tests/test_config_key.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6d6f03fa676f33cc4fc3bbef73212829be2ece1 --- /dev/null +++ b/sources/neuraloperator/neuralop/tests/test_config_key.txt @@ -0,0 +1 @@ +my_secret_key \ No newline at end of file diff --git a/sources/neuraloperator/neuralop/tests/test_model_from_config.py b/sources/neuraloperator/neuralop/tests/test_model_from_config.py new file mode 100644 index 0000000000000000000000000000000000000000..58f51bc46829fb83225a1f0823e02d3672dc3170 --- /dev/null +++ b/sources/neuraloperator/neuralop/tests/test_model_from_config.py @@ -0,0 +1,47 @@ +import torch +import time +from tensorly import tenalg + +tenalg.set_backend("einsum") +from pathlib import Path +import sys + +from neuralop import get_model + +# Read the configuration +from zencfg.from_commandline import make_config +import sys +from .test_config import TestConfig + + +def test_from_config(): + """Test forward/backward from a config file""" + # Read the configuration + config = make_config(TestConfig) + config = config.to_dict() + from pprint import pprint + + pprint(config) + + batch_size = config.data.batch_size + size = config.data.train_resolution + + if torch.has_cuda: + device = "cuda" + else: + device = "cpu" + + model = get_model(config) + model = model.to(device) + + in_data = torch.randn(batch_size, 1, size, size).to(device) + print(model.__class__) + print(model) + + t1 = time.time() + out = model(in_data) + t = time.time() - t1 + print(f"Output of size {out.shape} in {t}.") + + loss = out.sum() + loss.backward() diff --git a/sources/neuraloperator/neuralop/tests/test_utils.py b/sources/neuraloperator/neuralop/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..442f0b0c48b40d71983eacc7083f7d48b7617b2c --- /dev/null +++ b/sources/neuraloperator/neuralop/tests/test_utils.py @@ -0,0 +1,160 @@ +from ..utils import get_wandb_api_key, wandb_login +from ..utils import count_model_params, count_tensor_params +from pathlib import Path +import pytest + +# Set warning filter to show each warning only once +import warnings + +warnings.filterwarnings("once", category=UserWarning) + +# Only import wandb and use if installed +wandb_available = False +try: + import wandb + + wandb_available = True +except ModuleNotFoundError: + wandb_available = False + +import os +import torch +from torch import nn +from torch.utils.data import Dataset, DataLoader +from neuralop.models.base_model import BaseModel + + +def test_count_model_params(): + # A nested dummy model to make sure all parameters are counted + class DumyModel(nn.Module): + def __init__(self, n_submodels=0, dtype=torch.float32): + super().__init__() + + self.n_submodels = n_submodels + self.param = nn.Parameter(torch.randn((2, 3, 4), dtype=dtype)) + if n_submodels: + self.model = DumyModel(n_submodels - 1, dtype=dtype) + + n_submodels = 2 + model = DumyModel(n_submodels=n_submodels) + n_params = count_model_params(model) + print(model) + assert n_params == (n_submodels + 1) * 2 * 3 * 4 + + model = DumyModel(n_submodels=n_submodels, dtype=torch.cfloat) + n_params = count_model_params(model) + print(model) + assert n_params == 2 * (n_submodels + 1) * 2 * 3 * 4 + + +def test_count_tensor_params(): + # Case 1 : real tensor + x = torch.randn((2, 3, 4, 5, 6), dtype=torch.float32) + + # dims = None: count all params + n_params = count_tensor_params(x) + assert n_params == 2 * 3 * 4 * 5 * 6 + # Only certain dims + n_params = count_tensor_params(x, dims=[1, 3]) + assert n_params == 3 * 5 + + # Case 2 : complex tensor + x = torch.randn((2, 3, 4, 5, 6), dtype=torch.cfloat) + + # dims = None: count all params + n_params = count_tensor_params(x) + assert n_params == 2 * 3 * 4 * 5 * 6 * 2 + # Only certain dims + n_params = count_tensor_params(x, dims=[1, 3]) + assert n_params == 3 * 5 * 2 + + +def test_get_wandb_api_key(): + # Make sure no env var key set + os.environ.pop("WANDB_API_KEY", None) + + # Read from file + filepath = Path(__file__).parent.joinpath("test_config_key.txt").as_posix() + key = get_wandb_api_key(filepath) + assert key == "my_secret_key" + + # Read from env var + os.environ["WANDB_API_KEY"] = "key_from_env" + key = get_wandb_api_key(filepath) + assert key == "key_from_env" + + # Read from env var with incorrect file + os.environ["WANDB_API_KEY"] = "key_from_env" + key = get_wandb_api_key("wrong_path") + assert key == "key_from_env" + + +def test_ArgparseConfig(monkeypatch): + if wandb_available: + + def login(key): + if key == "my_secret_key": + return True + + raise ValueError("Wrong key") + + monkeypatch.setattr(wandb, "login", login) + + # Make sure no env var key set + os.environ.pop("WANDB_API_KEY", None) + + # Read from file + filepath = Path(__file__).parent.joinpath("test_config_key.txt").as_posix() + assert wandb_login(filepath) is None + + # Read from env var + os.environ["WANDB_API_KEY"] = "my_secret_key" + assert wandb_login() is None + + # Read from env var + os.environ["WANDB_API_KEY"] = "wrong_key" + assert wandb_login(key="my_secret_key") is None + + # Read from env var + os.environ["WANDB_API_KEY"] = "wrong_key" + with pytest.raises(ValueError): + wandb_login() + + +class DummyDataset(Dataset): + # Simple linear regression problem, PyTorch style + + def __init__(self, n_examples): + super().__init__() + + self.X = torch.randn((n_examples, 50)) + self.y = torch.randn((n_examples, 1)) + + def __getitem__(self, idx): + return {"x": self.X[idx], "y": self.y[idx]} + + def __len__(self): + return self.X.shape[0] + + +class DummyModel(BaseModel, name="Dummy"): + """ + Simple linear model to mock-up our model API + """ + + def __init__(self, features): + super().__init__() + self.net = nn.Linear(features, 1) + + def forward(self, x, **kwargs): + """ + Throw out extra args as in FNO and other models + """ + if kwargs: + warnings.warn( + f"SimpleLinearModel.forward() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2, + ) + return self.net(x) diff --git a/sources/neuraloperator/neuralop/training/__init__.py b/sources/neuraloperator/neuralop/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc8f7b0eaea854f8b791fd708dc4937dc664628 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/__init__.py @@ -0,0 +1,9 @@ +from .trainer import Trainer +from .torch_setup import setup +from .training_state import load_training_state, save_training_state +from .incremental import IncrementalFNOTrainer +from .adamw import AdamW +from .tensorgrad import ( + TensorGRaD, + fno_tensorgrad_param_groups, +) diff --git a/sources/neuraloperator/neuralop/training/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac8e286cc0b58250507861ba84bed120b3676e71 Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/adamw.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/adamw.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..624e0c36c3399816e4570918536b156ddacbb33b Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/adamw.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/incremental.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/incremental.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e552a29c2d5233840a4d311d863cd378c7d4229c Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/incremental.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/patching.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/patching.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5bf08dff8daad0262b7b13c62cc6802cd6cfc0e Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/patching.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/tensorgrad.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/tensorgrad.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa4f6c533acb7a5cc3c9c4fab053ae941211cad3 Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/tensorgrad.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/torch_setup.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/torch_setup.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..052d530f8dd98743c808fc55efa58ae889da4324 Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/torch_setup.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/trainer.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/trainer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..811ed23f440805336c7d33526ee996c3ee16a55f Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/trainer.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/__pycache__/training_state.cpython-313.pyc b/sources/neuraloperator/neuralop/training/__pycache__/training_state.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c323b1c881465f5c584ba22ca7502a5dc06d693e Binary files /dev/null and b/sources/neuraloperator/neuralop/training/__pycache__/training_state.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/training/adamw.py b/sources/neuraloperator/neuralop/training/adamw.py new file mode 100644 index 0000000000000000000000000000000000000000..751c24e4f61a66552d597f7d9ee0458194384b5d --- /dev/null +++ b/sources/neuraloperator/neuralop/training/adamw.py @@ -0,0 +1,205 @@ +import math +import warnings +from typing import Callable, Iterable, Tuple, Union + +import torch +from torch import nn +from torch.optim import Optimizer +from .tensorgrad import TensorGRaDProjector + + +class AdamW(Optimizer): + """ + Implements AdamW (Adam with weight decay fix [1]_), and offers + optional GaLore projection (see [2]_) using the TensorGRaD tensor + projector (see [3]_) for memory-efficient training. + + Parameters + ---------- + params: `Iterable[nn.parameter.Parameter]`: + Iterable of parameters to optimize or dictionaries defining parameter groups. + lr : `float`, *optional*, defaults to 0.001: + The learning rate to use. + betas : `Tuple[float,float]`, *optional*, defaults to `(0.9, 0.999)` + Adam's betas parameters (b1, b2). + eps : `float`, *optional*, defaults to 1e-06: + Adam's epsilon for numerical stability. + weight_decay : `float`, *optional*, defaults to 0.0: + Decoupled weight decay to apply. + correct_bias : `bool`, *optional*, defaults to `True`: + Whether or not to correct bias in Adam (for instance, in Bert TF repository they use `False`). + galore_params: `Iterable[nn.parameter.Parameter]`: + Iterable of parameters to optimize in low-rank subspace + galore_rank : float, int or int tuple + Rank of low-rank subspace in which to optimize `galore_params`. + Either a float corresponding to a percentage of params + to preserve, or an list of int ranks corresponding to + each mode of the tensor. If a single int is given, it is used + for all modes (see `neuralop/training/tensorgrad.py`) + galore_update_proj_gap : `int`, defaults to 50 + Number of optimizer steps before projection tensors are recomputed, + galore_scale : `float`, defaults to 1.0 + Additional lr-like scalar by which compressed parameters are multiplied + before update + activation_checkpoint: bool, default False + whether to use activation checkpointing during projection + no_deprecation_warning : `bool`, *optional*, defaults to `False`: + A flag used to disable the deprecation warning (set to `True` to disable the warning). + + References + ---------- + .. _[1] : Loschchilov, I. and Hutter, F. (2019). Decoupled Decay Regularization. + ICLR 2019, https://arxiv.org/pdf/1711.05101. + + .. _[2] : Zhao, J., Zhang, Z., Chen, B., Wang, Z., Anandkumar, A., + Tian, Y. (2024). + GaLore: Memory-Efficient LLM Training by Gradient Low-Rank Projection. + ICML 2024, https://arxiv.org/abs/2403.03507. + + .. _[3] : Loeschcke, S., Pitt, D., George, R., Zhao, J., Luo, C., + Tian, Y., Kossaifi, J., Anandkumar, A. (2025). + TensorGRaD: Tensor Gradient Robust Decomposition for Memory-Efficient + Neural Operator Training. arXiv preprint, + https://arxiv.org/abs/2501.02379. + """ + + def __init__( + self, + params: Iterable[nn.parameter.Parameter], + lr: float = 1e-3, + betas: Tuple[float, float] = (0.9, 0.999), + eps: float = 1e-6, + weight_decay: float = 0.0, + correct_bias: bool = True, + galore_params: Iterable[nn.parameter.Parameter] = None, + galore_rank: Union[float, int, Tuple[int]] = 1.0, + galore_update_proj_gap: int = 50, + galore_scale: float = 1.0, + activation_checkpoint: bool = False, + warm_restart: bool = True, + ): + if lr < 0.0: + raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0") + if not 0.0 <= betas[0] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)") + if not 0.0 <= betas[1] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)") + if not 0.0 <= eps: + raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0") + defaults = { + "lr": lr, + "betas": betas, + "eps": eps, + "weight_decay": weight_decay, + "correct_bias": correct_bias, + } + super().__init__(params, defaults) + + # Keep optional GaLore parameters separate for projection. + if galore_params is not None: + self.add_param_group( + { + "params": galore_params, + "rank": galore_rank, + "lr": lr, + "betas": betas, + "eps": eps, + "weight_decay": weight_decay, + "correct_bias": correct_bias, + "galore": True, + } + ) + self.galore_rank = galore_rank + self.activation_checkpoint = activation_checkpoint + self.warm_restart = warm_restart + self.galore_update_proj_gap = galore_update_proj_gap + self.galore_scale = galore_scale + + @torch.no_grad() + def step(self, closure: Callable = None): + """ + Performs a single optimization step. + + Arguments: + closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss. + """ + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + for p in group["params"]: + if p.grad is None: + continue + grad = p.grad + if grad.is_sparse: + raise RuntimeError("Adam does not support sparse gradients, please consider SparseAdam instead") + + state = self.state[p] + + if "step" not in state: + state["step"] = 0 + + # GaLore projection. + if group.get("galore", False): + if "projector" not in state: + state["projector"] = TensorGRaDProjector( + rank=self.galore_rank, + update_proj_gap=self.galore_update_proj_gap, + scale=self.galore_scale, + activation_checkpoint=self.activation_checkpoint, + warm_restart=self.warm_restart, + ) + + # track tensor shape for projection back + proj_input = grad + grad = state["projector"].project(proj_input, state["step"]) + + # State initialization + if "exp_avg" not in state: + # Exponential moving average of gradient values + state["exp_avg"] = torch.zeros_like(grad) + # Exponential moving average of squared gradient values + state["exp_avg_sq"] = torch.zeros_like(grad) + + exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] + beta1, beta2 = group["betas"] + + state["step"] += 1 + + # Decay the first and second moment running average coefficient + # In-place operations to update the averages at the same time + exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1)) + if torch.is_complex(grad): + exp_avg_sq.mul_(beta2).addcmul_(grad, grad.conj(), value=1.0 - beta2) + else: + exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2) + denom = exp_avg_sq.sqrt().add_(group["eps"]) + + step_size = group["lr"] + if group["correct_bias"]: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state["step"] + bias_correction2 = 1.0 - beta2 ** state["step"] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + + # compute norm gradient + norm_grad = exp_avg / denom + + # GaLore projection back. + if group.get("galore", False): + norm_grad = state["projector"].project_back(norm_grad) + + p.add_(norm_grad, alpha=-step_size) + + # Just adding the square of the weights to the loss function is *not* + # the correct way of using L2 regularization/weight decay with Adam, + # since that will interact with the m and v parameters in strange ways. + # + # Instead we want to decay the weights in a manner that doesn't interact + # with the m/v parameters. This is equivalent to adding the square + # of the weights to the loss with plain (non-momentum) SGD. + # Add weight decay at the end (fixed version) + if group["weight_decay"] > 0.0: + p.add_(p, alpha=(-group["lr"] * group["weight_decay"])) + + return loss diff --git a/sources/neuraloperator/neuralop/training/incremental.py b/sources/neuraloperator/neuralop/training/incremental.py new file mode 100644 index 0000000000000000000000000000000000000000..5538a63ffe0ddbc73975c5e375b4aea7ad240aa8 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/incremental.py @@ -0,0 +1,259 @@ +import torch +from torch import nn + +from .trainer import Trainer +from ..models import FNO, TFNO +from ..utils import compute_explained_variance + + +class IncrementalFNOTrainer(Trainer): + """ + Trainer for the Incremental Fourier Neural Operator (iFNO) + + Implements iFNO approach from [1] that progressively increases + Fourier modes during training. This class supports two algorithms: + + 1. Loss Gap (`incremental_loss_gap=True`): Increases modes when loss + improvement becomes too small + 2. Gradient-based (`incremental_grad=True`): Uses explained variance of + gradient strengths to determine when more modes are needed + + Parameters + ---------- + model : nn.Module + FNO or TFNO model to train. + n_epochs : int + Total number of training epochs. + incremental_grad : bool, optional + Use gradient-based algorithm, by default False. + incremental_loss_gap : bool, optional + Use loss gap algorithm, by default False. + incremental_grad_eps : float, optional + Explained variance threshold for gradient algorithm, by default 0.001. + incremental_loss_eps : float, optional + Loss improvement threshold for loss gap algorithm, by default 0.001. + incremental_grad_max_iter : int, optional + Iterations for gradient accumulation, by default 10. + incremental_buffer : int, optional + Buffer size for gradient accumulation, by default 5. + + Notes + ----- + - Exactly one algorithm must be enabled (not both) + - Gradient algorithm requires multiple iterations for statistics + - Both algorithms respect maximum modes in FNO model + + References + ---------- + .. [1] George, R., Zhao, J., Kossaifi, J., Li, Z., and Anandkumar, A. (2024) + "Incremental Spatial and Spectral Learning of Neural Operators for Solving Large-Scale PDEs". + TMLR, https://openreview.net/pdf?id=xI6cPQObp0. + """ + + def __init__( + self, + model: nn.Module, + n_epochs: int, + wandb_log: bool = False, + device: str = "cpu", + mixed_precision: bool = False, + data_processor: nn.Module = None, + eval_interval: int = 1, + log_output: bool = False, + use_distributed: bool = False, + verbose: bool = False, + incremental_grad: bool = False, + incremental_loss_gap: bool = False, + incremental_grad_eps: float = 0.001, + incremental_buffer: int = 5, + incremental_max_iter: int = 1, + incremental_grad_max_iter: int = 10, + incremental_loss_eps: float = 0.001, + ): + assert isinstance(model, FNO) or isinstance( + model, TFNO + ), f"Error: \ + IncrementalFNOTrainer is designed to work with FNO or TFNO, instead got\ + a model of type {model.__class__.__name__}" + + super().__init__( + model=model, + n_epochs=n_epochs, + wandb_log=wandb_log, + device=device, + mixed_precision=mixed_precision, + data_processor=data_processor, + eval_interval=eval_interval, + log_output=log_output, + use_distributed=use_distributed, + verbose=verbose, + ) + + self.incremental_loss_gap = incremental_loss_gap + self.incremental_grad = incremental_grad + self.incremental = self.incremental_loss_gap or self.incremental_grad + assert ( + self.incremental + ), "Error: IncrementalTrainer expects at least one incremental algorithm to be True." + assert not ( + self.incremental_loss_gap and self.incremental_grad + ), "Error: IncrementalTrainer expects only one incremental algorithm to be True." + + self.incremental_grad_eps = incremental_grad_eps + self.incremental_buffer = incremental_buffer + self.incremental_max_iter = incremental_max_iter + self.incremental_grad_max_iter = incremental_grad_max_iter + self.incremental_loss_eps = incremental_loss_eps + self.loss_list = [] + + def incremental_update(self, loss=None): + """ + Main incremental update function that determines which algorithm to run. + + This method is called after each training epoch to potentially increase the number + of Fourier modes in the FNO model based on the selected incremental algorithm. + + Parameters + ---------- + loss : float or torch.Tensor, optional + Current training loss value. Required for loss gap algorithm. + If None and loss gap algorithm is enabled, no update will occur. + """ + if self.incremental_loss_gap and loss is not None: + self.loss_gap(loss) + if self.incremental_grad: + self.grad_explained() + + def train_one_epoch(self, epoch, train_loader, training_loss): + """ + Train the model for one epoch with incremental learning. + + Extends base trainer by adding incremental learning updates after each epoch. + May increase Fourier modes based on training progress. + + Parameters + ---------- + epoch : int + Current epoch number. + train_loader : torch.utils.data.DataLoader + DataLoader containing training data. + training_loss : callable + Loss function to use for training. + + Returns + ------- + tuple + (train_err, avg_loss, avg_lasso_loss, epoch_train_time) + """ + self.training = True + if self.data_processor: + self.data_processor.epoch = epoch + + # Run base training epoch + train_err, avg_loss, avg_lasso_loss, epoch_train_time = super().train_one_epoch( + epoch, train_loader, training_loss + ) + + # Apply incremental learning updates + self.incremental_update(avg_loss) + + return train_err, avg_loss, avg_lasso_loss, epoch_train_time + + # Algorithm 1: Incremental + def loss_gap(self, loss): + """ + Loss gap algorithm for incremental learning. + + Monitors training loss convergence and increases Fourier modes when loss improvement + becomes too small. Helps escape local minima by increasing model capacity. + + Algorithm: + 1. Track training losses over epochs + 2. Compute difference between consecutive losses + 3. If difference < threshold, increase modes by 1 + 4. Update FNO blocks with new mode count + + Parameters + ---------- + loss : float or torch.Tensor + Current epoch's training loss value. + + """ + self.loss_list.append(loss) + self.ndim = len(self.model.fno_blocks.convs[0].n_modes) + + # method 1: loss_gap + incremental_modes = self.model.fno_blocks.convs[0].n_modes[0] + max_modes = self.model.fno_blocks.convs[0].max_n_modes[0] + if len(self.loss_list) > 1: + loss_difference = abs(self.loss_list[-1] - self.loss_list[-2]) + if loss_difference <= self.incremental_loss_eps: + # Increase modes if we haven't reached the maximum + if incremental_modes < max_modes: + incremental_modes += 1 + + # Update all FNO blocks with the new mode count + modes_list = tuple([incremental_modes] * self.ndim) + self.model.fno_blocks.convs[0].n_modes = modes_list + + def grad_explained(self): + """ + Gradient-based explained variance algorithm for incremental learning. + + Analyzes gradient patterns of FNO weights to determine when additional + Fourier modes are needed by computing explained variance of gradient strengths. + + Algorithm: + 1. Accumulate gradients over multiple iterations + 2. Compute Frobenius norm of gradients for each Fourier mode + 3. Compute explained variance of gradient strengths + 4. If explained variance < threshold, increase modes + 5. Reset accumulation and update model + """ + + if not hasattr(self, "accumulated_grad"): + self.accumulated_grad = torch.zeros_like( + self.model.fno_blocks.convs[0].weight + ) + if not hasattr(self, "grad_iter"): + self.grad_iter = 1 + + self.ndim = len(self.model.fno_blocks.convs[0].n_modes) + + # Accumulate gradients over multiple iterations + if self.grad_iter <= self.incremental_grad_max_iter: + self.grad_iter += 1 + self.accumulated_grad += self.model.fno_blocks.convs[0].weight + else: + incremental_final = [] + + for i in range(self.ndim): + max_modes = self.model.fno_blocks.convs[i].max_n_modes[0] + incremental_modes = self.model.fno_blocks.convs[0].n_modes[0] + weight = self.accumulated_grad + + # Compute gradient strength for each Fourier mode + strength_vector = [] + for mode_index in range(min(weight.shape[1], incremental_modes)): + strength = torch.norm(weight[:, mode_index, :], p="fro") + strength_vector.append(strength) + + # Compute explained variance of gradient strengths + explained_ratio = compute_explained_variance( + incremental_modes - self.incremental_buffer, + torch.Tensor(strength_vector), + ) + + # Increase modes if explained variance is too low + if explained_ratio < self.incremental_grad_eps: + if incremental_modes < max_modes: + incremental_modes += 1 + + incremental_final.append(incremental_modes) + + # update the modes and frequency dimensions + self.grad_iter = 1 + self.accumulated_grad = torch.zeros_like(self.model.fno_blocks.convs[0].weight) + main_modes = incremental_final[0] + modes_list = tuple([main_modes] * self.ndim) + self.model.fno_blocks.convs[0].n_modes = tuple(modes_list) diff --git a/sources/neuraloperator/neuralop/training/patching.py b/sources/neuraloperator/neuralop/training/patching.py new file mode 100644 index 0000000000000000000000000000000000000000..0db09cf5dd3d6730a9af04558223cc1f9fe047b2 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/patching.py @@ -0,0 +1,376 @@ +import math + +import torch +from torch import nn + +import neuralop.mpu.comm as comm +from neuralop.mpu.mappings import ( + gather_from_model_parallel_region, + scatter_to_model_parallel_region, +) + + +class MultigridPatching2D(nn.Module): + """ + MultigridPatching2D wraps a model in multi-grid domain decomposition and patching. + + Parameters + ---------- + model : nn.Module + model to wrap + levels : int, optional + number of levels of patching to use, by default 0 + padding_fraction : float, optional + fraction of input size to add as padding around patches, by default 0 + use_distributed : bool, optional + whether patching is performed in distributed mode, by default False + stitching : bool, optional + whether patches are to be stitched back together + in spatial dimensions during training, by default True. + Stitching is always performed during evaluation. + """ + + def __init__( + self, + model: nn.Module, + levels: int = 0, + padding_fraction: float = 0, + use_distributed: bool = False, + stitching: bool = True, + ): + """Initialize MultigridPatching2D. + + If computation is split into distributed data or model parallel, adds parameter + hooks to account for scattering patches across multiple processes. + """ + + super().__init__() + + self.levels = levels + + if isinstance(padding_fraction, (float, int)): + padding_fraction = [padding_fraction, padding_fraction] + self.padding_fraction = padding_fraction + + n_patches = 2**levels + if isinstance(n_patches, int): + n_patches = [n_patches, n_patches] + self.n_patches = n_patches + + self.model = model + + self.use_distributed = use_distributed + self.stitching = stitching + + if levels > 0: + print( + "MGPatching(" + f"n_patches={self.n_patches}, " + f"padding_fraction={self.padding_fraction}, " + f"levels={self.levels}, " + f"use_distributed={use_distributed}, " + f"stitching={stitching})" + ) + + # If distributed patches are stiched, re-scale gradients to revert DDP averaging + if self.use_distributed and self.stitching: + for param in model.parameters(): + param.register_hook( + lambda grad: grad * float(comm.get_model_parallel_size()) + ) + + def patch(self, x, y): + """use multi-grid domain decomposition to split `x` and `y` into patches. + If in a distributed scheme, scatters patches across processes. + + Parameters + ---------- + x : torch.tensor + model input function + y : _type_ + model output function + """ + # if not stitching in single-device, create patches for y + if not self.stitching: + y = make_patches(y, n=self.n_patches, p=0) + # If not stitching, scatter truth, otherwise keep on every GPU + if self.use_distributed: + y = scatter_to_model_parallel_region(y, 0) + + # Create padded patches in batch dimension (identity if levels=0) + x = self._make_mg_patches(x) + # Split data across processes + if self.use_distributed: + x = scatter_to_model_parallel_region(x, 0) + return x, y + + def unpatch(self, x, y, evaluation=False): + """unpatch tensors created by `self.patch`. Stitch patches together if in + evaluation mode, or if stitching is applied. + + Parameters + ---------- + x : torch.tensor + 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 : torch.tensor + 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, optional + whether in evaluation mode, by default False. + If True, `x` and `y` are both evaluated after stitching, + regardless of other settings. + """ + # Remove padding in the output + if self.padding_height > 0 or self.padding_width > 0: + x = self._unpad(x) + + # Gather patches if they are to be stitched back together + if self.use_distributed and self.stitching: + x = gather_from_model_parallel_region(x, dim=0) + + # Stich patches or patch the truth if output left unstitched + if self.stitching or evaluation: + x = self._stitch(x) + + # if x is not stitched during training, y is patched + # re-stitch y during evaluation only + if evaluation and not self.stitching: + y = self._stitch(y) + + return x, y + + def _stitch(self, x): + """Stitch back together multi-grid patches created by `self._make_mg_patches`. + + Small patches are collated along the batch dimension as different inputs. Unroll + the batch dimension and stick all patches from the same input back together in their + proper locations. + + For an input shape (n * n * n, c, h / n, w / n), + produces an output tensor of shape (b, c, h, w) + + + Parameters + ---------- + x : torch.tensor + input tensor, split into patches and collated along batch dim + shape (batch * n^2, c, h / n, w / n) + + """ + + # Only 1D and 2D supported + assert x.ndim == 4, f"Only 2D patch supported but got input with {x.ndim} dims." + + if self.n_patches[0] <= 1 and self.n_patches[1] <= 1: + return x + + # Size with padding removed + size = x.size() + + # if self.mode == "batch-wise": + B = size[0] // (self.n_patches[0] * self.n_patches[1]) + W = size[3] * self.n_patches[1] + + C = size[1] + H = size[2] * self.n_patches[0] + + # Reshape + x = x.permute(0, 3, 2, 1) + x = x.reshape(B, self.n_patches[0], self.n_patches[1], size[3], size[2], C) + x = x.permute(0, 5, 1, 4, 2, 3) + x = x.reshape(B, C, H, W) + + return x + + def _make_mg_patches(self, x): + """ + Split a tensor `x` into multi-grid patches. The number of + patches into which `x` is split is determined by `2 ** self.levels`. + + Steps: + + 1. Optionally apply padding if self.padding_fraction > 0 + + 2. Split each element in the batch into `2**self.levels` patches of equal size + + 3. For each level L in `self.levels`, subsample all patches by a factor of `2**L` + + 4. Pad the subsampled patches so all level tensors are the same size + + 5. Concatenate the patches along the channel dim and return + + Parameters + ---------- + x : torch.tensor + input tensor to split into patches + shape (batch, c, h, w) + """ + levels = self.levels + if levels <= 0: + return x + + _, _, height, width = x.shape + padding = [ + int(round(v)) + for v in [ + height * self.padding_fraction[0], + width * self.padding_fraction[1], + ] + ] + self.padding_height = padding[0] + self.padding_width = padding[1] + + patched = make_patches(x, n=2**self.levels, p=padding) + s1_patched = patched.size(-2) - 2 * padding[0] + s2_patched = patched.size(-1) - 2 * padding[1] + + for level in range(1, levels + 1): + sub_sample = 2**level + s1_stride = s1_patched // sub_sample + s2_stride = s2_patched // sub_sample + + x_sub = x[:, :, ::sub_sample, ::sub_sample] + + s2_pad = ( + math.ceil( + (s2_patched + (2**levels - 1) * s2_stride - x_sub.size(-1)) / 2.0 + ) + + padding[1] + ) + s1_pad = ( + math.ceil( + (s1_patched + (2**levels - 1) * s1_stride - x_sub.size(-2)) / 2.0 + ) + + padding[0] + ) + + if s2_pad > x_sub.size(-1): + diff = s2_pad - x_sub.size(-1) + x_sub = torch.nn.functional.pad( + x_sub, pad=[x_sub.size(-1), x_sub.size(-1), 0, 0], mode="circular" + ) + x_sub = torch.nn.functional.pad( + x_sub, pad=[diff, diff, 0, 0], mode="circular" + ) + else: + x_sub = torch.nn.functional.pad( + x_sub, pad=[s2_pad, s2_pad, 0, 0], mode="circular" + ) + + if s1_pad > x_sub.size(-2): + diff = s1_pad - x_sub.size(-2) + x_sub = torch.nn.functional.pad( + x_sub, pad=[0, 0, x_sub.size(-2), x_sub.size(-2)], mode="circular" + ) + x_sub = torch.nn.functional.pad( + x_sub, pad=[0, 0, diff, diff], mode="circular" + ) + else: + x_sub = torch.nn.functional.pad( + x_sub, pad=[0, 0, s1_pad, s1_pad], mode="circular" + ) + + x_sub = x_sub.unfold(-1, s2_patched + 2 * padding[1], s2_stride) + x_sub = x_sub.unfold(-3, s1_patched + 2 * padding[0], s1_stride) + + x_sub = x_sub.permute(0, 2, 3, 4, 5, 1) + x_sub = x_sub.reshape( + patched.size(0), + s2_patched + 2 * padding[1], + s1_patched + 2 * padding[0], + -1, + ) + x_sub = x_sub.permute(0, 3, 2, 1) + + patched = torch.cat((patched, x_sub), 1) + + return patched + + def _unpad(self, x): + """Remove padding around the edges (`mode=circular`) of tensor `x`. + + Parameters + ---------- + x : torch.tensor + padded input tensor, shape (b, c, h + self.padding_height * 2, w + self.padding_width * 2) + + Returns + ------- + x : torch.tensor + unpadded tensor, shape (b, c, h, w) + """ + return x[ + ..., + self.padding_height : -self.padding_height, + self.padding_width : -self.padding_width, + ].contiguous() + + +def make_patches(x, n, p=0): + """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) + + + Parameters + ---------- + x : torch.tensor + input tensor, before patching + n : int + number of patches into which to split each example in `x` + p : int, optional + number of pixels to use when padding `x`, by default 0 + """ + + size = x.size() + + # Only 1D and 2D supported + assert len(size) == 3 or len(size) == 4 + + if len(size) == 3: + d = 1 + else: + d = 2 + + if isinstance(p, int): + p = [p, p] + + # Pad + if p[0] > 0 or p[1] > 0: + if d == 1: + x = torch.nn.functional.pad(x, pad=p, mode="circular") + else: + x = torch.nn.functional.pad( + x, pad=[p[1], p[1], p[0], p[0]], mode="circular" + ) + + if isinstance(n, int): + n = [n, n] + + if n[0] <= 1 and n[1] <= 1: + return x + + # Patches must be equally sized + for j in range(d): + assert size[-(j + 1)] % n[-(j + 1)] == 0 + + # Patch + for j in range(d): + patch_size = size[-(j + 1)] // n[-(j + 1)] + x = x.unfold(-(2 * j + 1), patch_size + 2 * p[-(j + 1)], patch_size) + + x = x.permute(0, 2, 3, 4, 5, 1) + x = x.reshape( + size[0] * n[0] * n[1], + size[-1] // n[-1] + 2 * p[-1], + size[-2] // n[-2] + 2 * p[-2], + size[1], + ) + x = x.permute(0, 3, 2, 1) + + return x diff --git a/sources/neuraloperator/neuralop/training/tensorgrad.py b/sources/neuraloperator/neuralop/training/tensorgrad.py new file mode 100644 index 0000000000000000000000000000000000000000..c83cceabab363a61d9a53548f1e57bbb937ee4af --- /dev/null +++ b/sources/neuraloperator/neuralop/training/tensorgrad.py @@ -0,0 +1,472 @@ +import math +from typing import Callable, Iterable, Optional + +import torch +from tensorly import tenalg +from tensorly.decomposition import tucker +from torch import nn +from torch.optim import Optimizer +from torch.utils.checkpoint import checkpoint +from tensorly.tucker_tensor import validate_tucker_rank + + +class TensorGRaDProjector: + """Low-rank gradient projector used by TensorGRaD. + + The original tensor is projected into a low-rank subspace using low-rank + mode-wise factors obtained by Tucker decomposition. The parameters are + optimized in this space to save memory and are then projected back into the + full-rank space for use in a model. + + Parameters + ---------- + rank : float, int or tuple[int, ...] + Goal rank of the transformed gradient tensor. A float is interpreted as + a target fraction of parameters to preserve. + update_proj_gap : int, optional + Number of optimizer steps between projection-tensor updates. + scale : float, optional + Scalar applied after projecting low-rank updates back to full size. + warm_restart : bool, optional + If ``True``, uses the previous projection tensor as the initializer for + the next Tucker decomposition. + activation_checkpoint : bool, optional + Whether to use activation checkpointing for Tucker decomposition. + + References + ---------- + .. _[1] : Loeschcke, S., Pitt, D., George, R., Zhao, J., Luo, C., + Tian, Y., Kossaifi, J., Anandkumar, A. (2025). + TensorGRaD: Tensor Gradient Robust Decomposition for Memory-Efficient + Neural Operator Training. arXiv preprint, + https://arxiv.org/abs/2501.02379. + """ + + def __init__( + self, + rank, + update_proj_gap: int = 200, + scale: float = 1.0, + tucker_n_iter_max: int = 10, + warm_restart: bool = False, + activation_checkpoint: bool = False, + ): + self.rank = rank + self.update_proj_gap = update_proj_gap + self.scale = scale + self.warm_restart = warm_restart + self.tucker_n_iter_max = tucker_n_iter_max + self.activation_checkpoint = activation_checkpoint + self.proj_tensor = None + + def project(self, full_rank_grad, iter): + if self.proj_tensor is None or iter % self.update_proj_gap == 0: + self.proj_tensor = self.get_projection_tensor(full_rank_grad, self.rank) + return self.transform(self.proj_tensor, full_rank_grad) + + def project_back(self, low_rank_grad): + full_rank_grad = self.inverse_transform(self.proj_tensor, low_rank_grad) + return full_rank_grad * self.scale + + def get_projection_tensor(self, weights, rank): + if torch.is_complex(weights.data) and weights.data.dtype != torch.cfloat: + matrix = weights.data.cfloat() + else: + matrix = weights.data + + if self.warm_restart and self.proj_tensor is not None: + init_factors = [factor.to(matrix.device) for factor in self.proj_tensor] + init_core = self.transform(init_factors, matrix) + init = (init_core, init_factors) + else: + init = "svd" + if self.activation_checkpoint: + core, factors = checkpoint(tucker, matrix, rank=rank, init=init, n_iter_max=self.tucker_n_iter_max, use_reentrant=False) + else: + core, factors = tucker(matrix, rank=rank, init=init, n_iter_max=self.tucker_n_iter_max) + del core + return factors + + def transform(self, factors, x): + if self.activation_checkpoint: + return checkpoint(tenalg.multi_mode_dot, x, factors, transpose=True, use_reentrant=False) + return tenalg.multi_mode_dot(x, factors, transpose=True) + + def inverse_transform(self, factors, x): + if self.activation_checkpoint: + return checkpoint(tenalg.multi_mode_dot, x, factors) + return tenalg.multi_mode_dot(x, factors) + + +class UnstructuredSparseProjector: + """Project gradients by keeping a sparse set of entries in flattened order. + + Parameters + ---------- + sparse_ratio : float + Fraction of entries to keep in the sparse gradient. + update_proj_gap : int, optional + Number of optimizer steps between sparse mask updates. + sparse_type : {"randk", "randomk", "topk"}, optional + Strategy used to choose sparse entries. ``topk`` keeps entries with the + largest absolute gradient values, while ``randk``/``randomk`` sample + entries uniformly at random. + scale : float, optional + Scalar applied after projecting the sparse update back to full size. + scale_by_mask_ratio : bool, optional + If ``True``, additionally scales by the square root of the inverse + sparse mask ratio after projection back. + """ + + def __init__( + self, + sparse_ratio: float, + update_proj_gap: int = 50, + sparse_type: str = "randk", + scale: float = 1.0, + scale_by_mask_ratio: bool = False, + ): + if not 0 < sparse_ratio <= 1: + raise ValueError(f"Expected sparse_ratio in (0, 1], got {sparse_ratio}.") + if update_proj_gap < 1: + raise ValueError(f"Expected update_proj_gap >= 1, got {update_proj_gap}.") + if sparse_type not in {"randk", "randomk", "topk"}: + raise ValueError(f"Unsupported sparse_type={sparse_type}.") + + self.sparse_ratio = sparse_ratio + self.update_proj_gap = update_proj_gap + self.sparse_type = sparse_type + self.scale = scale + self.scale_by_mask_ratio = scale_by_mask_ratio + self.indices = None + self.orig_shape = None + + def project(self, grad: torch.Tensor, step: int): + if self.orig_shape is None: + self.orig_shape = grad.shape + if self.indices is None or step % self.update_proj_gap == 0: + self.indices = self._build_indices(grad) + return grad.reshape(-1)[self.indices] + + def project_back(self, sparse_grad: torch.Tensor): + out = torch.zeros( + self.orig_shape, + dtype=sparse_grad.dtype, + device=sparse_grad.device, + ) + values = sparse_grad * self.scale + if self.scale_by_mask_ratio: + values = values * math.sqrt(out.numel() / sparse_grad.numel()) + out.reshape(-1).scatter_(0, self.indices, values.to(out.dtype)) + return out + + def _build_indices(self, grad: torch.Tensor): + flat = grad.reshape(-1) + k = max(1, int(self.sparse_ratio * flat.numel())) + if self.sparse_type == "topk": + _, indices = torch.topk(flat.abs(), k) + else: + indices = torch.randperm(flat.numel(), device=grad.device)[:k] + return indices.sort().values + + +class TensorGRaD(Optimizer): + """AdamW with optional low-rank and sparse gradient projection. + + Parameters with a ``tensorgrad`` parameter-group flag are optimized in a + compressed gradient space. Groups with only ``rank`` use a single + TensorGRaD/Tucker low-rank branch. Groups that also set + ``sparse_ratio`` use a TensorGRaD-style residual branch: low-rank project + the gradient, sparse-project the low-rank residual, run Adam on both + compressed states, then project both updates back and combine them. + + Parameters + ---------- + params : iterable + Iterable of parameters or parameter groups. Parameter groups with + ``tensorgrad=True`` use compressed-gradient updates. + lr : float, optional + Learning rate. + betas : tuple[float, float], optional + Adam exponential moving average coefficients. + eps : float, optional + Epsilon added to the denominator for numerical stability. + weight_decay : float, optional + Decoupled weight decay. + correct_bias : bool, optional + Whether to apply Adam bias correction. + + TensorGRaD parameter-group options + ---------------------------------- + rank : float or tuple[int, ...] + Tucker low-rank budget for the low-rank branch. A float gives the + target fraction of low-rank gradient entries. + sparse_ratio : float, optional + If provided, enables the sparse residual branch with this entry budget. + update_proj_gap : int, optional + Number of optimizer steps between low-rank basis and sparse mask + updates. + scale : float, optional + Scalar applied to the projected-back low-rank update. + sparse_scale : float, optional + Scalar applied to the projected-back sparse update. + lambda_sparse : float, optional + Weight used when adding the sparse update to the low-rank update. + """ + + def __init__( + self, + params: Iterable[nn.Parameter], + lr: float = 1e-3, + betas: tuple[float, float] = (0.9, 0.999), + eps: float = 1e-6, + weight_decay: float = 0.0, + correct_bias: bool = True, + ): + if lr < 0: + raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0") + if not 0 <= betas[0] < 1: + raise ValueError( + f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)" + ) + if not 0 <= betas[1] < 1: + raise ValueError( + f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)" + ) + if eps < 0: + raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0") + + defaults = { + "lr": lr, + "betas": betas, + "eps": eps, + "weight_decay": weight_decay, + "correct_bias": correct_bias, + } + super().__init__(params, defaults) + + @torch.no_grad() + def step(self, closure: Optional[Callable] = None): + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + for param in group["params"]: + if param.grad is None: + continue + grad = param.grad + if grad.is_sparse: + raise RuntimeError("TensorGRaD does not support sparse gradients.") + + state = self.state[param] + if "step" not in state: + state["step"] = 0 + + step = state["step"] + if group.get("tensorgrad", False): + update, step_size = self._tensorgrad_update( + param, + grad, + group, + state, + ) + else: + update, step_size = self._adamw_update( + grad, + group, + state, + "exp_avg", + "exp_avg_sq", + step + 1, + ) + + param.add_(update, alpha=-step_size) + if group["weight_decay"] > 0: + param.add_(param, alpha=-group["lr"] * group["weight_decay"]) + state["step"] = step + 1 + + return loss + + def _tensorgrad_update(self, param, grad, group, state): + if "low_rank_projector" not in state: + state["low_rank_projector"] = self._make_low_rank_projector(param, group) + if group.get("sparse_ratio") is not None: + state["sparse_projector"] = self._make_sparse_projector(group) + + low_rank_projector = state["low_rank_projector"] + low_rank_grad = low_rank_projector.project(grad, state["step"]) + + if "sparse_projector" not in state: + update, step_size = self._adamw_update( + low_rank_grad, + group, + state, + "low_rank_exp_avg", + "low_rank_exp_avg_sq", + state["step"] + 1, + ) + return low_rank_projector.project_back(update), step_size + + # Build the sparse branch from the residual left by the unscaled + # low-rank reconstruction. Scaling is applied only to the final update. + low_rank_reconstruction = low_rank_projector.inverse_transform( + low_rank_projector.proj_tensor, + low_rank_grad, + ) + residual = grad - low_rank_reconstruction + sparse_projector = state["sparse_projector"] + sparse_grad = sparse_projector.project(residual, state["step"]) + + low_rank_update, step_size = self._adamw_update( + low_rank_grad, + group, + state, + "low_rank_exp_avg", + "low_rank_exp_avg_sq", + state["step"] + 1, + ) + sparse_update, _ = self._adamw_update( + sparse_grad, + group, + state, + "sparse_exp_avg", + "sparse_exp_avg_sq", + state["step"] + 1, + ) + sparse_weight = group.get("lambda_sparse", 1.0) + full_update = low_rank_projector.project_back(low_rank_update) + full_update.add_( + sparse_projector.project_back(sparse_update), + alpha=sparse_weight, + ) + return full_update, step_size + + def _adamw_update(self, grad, group, state, exp_avg_key, exp_avg_sq_key, step): + if exp_avg_key not in state: + state[exp_avg_key] = torch.zeros_like(grad) + state[exp_avg_sq_key] = torch.zeros_like(grad) + + exp_avg = state[exp_avg_key] + exp_avg_sq = state[exp_avg_sq_key] + beta1, beta2 = group["betas"] + + exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) + if torch.is_complex(grad): + exp_avg_sq.mul_(beta2).addcmul_(grad, grad.conj(), value=1 - beta2) + else: + exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) + + denom = exp_avg_sq.sqrt().add_(group["eps"]) + step_size = group["lr"] + if group["correct_bias"]: + bias_correction1 = 1 - beta1 ** step + bias_correction2 = 1 - beta2 ** step + step_size *= math.sqrt(bias_correction2) / bias_correction1 + return exp_avg / denom, step_size + + @staticmethod + def _make_low_rank_projector(param, group): + rank = validate_tucker_rank(param.shape, group.get("rank", 0.25)) + return TensorGRaDProjector( + rank=rank, + update_proj_gap=group.get("update_proj_gap", 50), + scale=group.get("scale", 1.0), + warm_restart=group.get("warm_restart", True), + tucker_n_iter_max=group.get("tucker_n_iter_max", 10), + activation_checkpoint=group.get("activation_checkpoint", False), + ) + + @staticmethod + def _make_sparse_projector(group): + return UnstructuredSparseProjector( + sparse_ratio=group["sparse_ratio"], + update_proj_gap=group.get("update_proj_gap", 50), + sparse_type=group.get("sparse_type", "randk"), + scale=group.get("sparse_scale", 1.0), + scale_by_mask_ratio=group.get("scale_by_mask_ratio", False), + ) + + +def fno_tensorgrad_param_groups( + model: nn.Module, + rank: float = 0.25, + sparse_ratio: Optional[float] = None, + min_params: int = 1000, + update_proj_gap: int = 50, + scale: float = 1.0, + sparse_scale: float = 1.0, + sparse_type: str = "randk", + lambda_sparse: float = 1.0, + warm_restart: bool = True, +): + """Return AdamW and TensorGRaD parameter groups for FNO spectral weights. + + The returned groups put large parameters from ``model.fno_blocks.convs`` in + a TensorGRaD group and all remaining trainable parameters in a regular + AdamW-style group. + + Parameters + ---------- + model : nn.Module + FNO-like model with ``fno_blocks.convs``. + rank : float, optional + Tucker low-rank budget for selected spectral-convolution parameters. + sparse_ratio : float, optional + Sparse residual budget. If ``None``, only the low-rank branch is used. + min_params : int, optional + Minimum number of entries a spectral-convolution parameter must have to + be optimized with TensorGRaD. + update_proj_gap : int, optional + Number of optimizer steps between projection updates. + scale : float, optional + Scalar applied to projected-back low-rank updates. + sparse_scale : float, optional + Scalar applied to projected-back sparse updates. + sparse_type : {"randk", "randomk", "topk"}, optional + Strategy used by the sparse residual projector. + lambda_sparse : float, optional + Weight used when adding the sparse update to the low-rank update. + warm_restart : bool, optional + Whether Tucker decomposition reuses the previous projection factors + when updating the low-rank basis. + """ + + module = model.module if hasattr(model, "module") else model + if not hasattr(module, "fno_blocks") or not hasattr(module.fno_blocks, "convs"): + raise ValueError("Expected an FNO-like model with fno_blocks.convs.") + + tensorgrad_params = [ + param + for param in module.fno_blocks.convs.parameters() + if param.requires_grad and param.numel() >= min_params + ] + tensorgrad_param_ids = {id(param) for param in tensorgrad_params} + regular_params = [ + param + for param in model.parameters() + if param.requires_grad and id(param) not in tensorgrad_param_ids + ] + if not tensorgrad_params: + raise ValueError( + "No FNO spectral convolution parameters matched TensorGRaD filtering." + ) + + tensorgrad_group = { + "params": tensorgrad_params, + "tensorgrad": True, + "rank": rank, + "update_proj_gap": update_proj_gap, + "scale": scale, + "warm_restart": warm_restart, + } + if sparse_ratio is not None: + tensorgrad_group.update( + { + "sparse_ratio": sparse_ratio, + "sparse_type": sparse_type, + "sparse_scale": sparse_scale, + "lambda_sparse": lambda_sparse, + } + ) + return [{"params": regular_params}, tensorgrad_group] diff --git a/sources/neuraloperator/neuralop/training/tests/__init__.py b/sources/neuraloperator/neuralop/training/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/training/tests/test_optim.py b/sources/neuraloperator/neuralop/training/tests/test_optim.py new file mode 100644 index 0000000000000000000000000000000000000000..4c20e53311ae13e02fc5b1a0b42ba42f01aeab00 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/tests/test_optim.py @@ -0,0 +1,271 @@ +import torch +from torch.nn import Parameter +from torch.testing import assert_close +import pytest +import math +import neuralop.training.tensorgrad as tensorgrad_module + +from ..adamw import AdamW +from ..tensorgrad import ( + TensorGRaD, + TensorGRaDProjector, + UnstructuredSparseProjector, + fno_tensorgrad_param_groups, +) + +from ...models import FNO + +from tensorly.tucker_tensor import validate_tucker_rank + + +@pytest.mark.parametrize("adam_optimizer_cls", [AdamW]) +def test_correct_complex_adam_momentum(adam_optimizer_cls): + # param = x * 2j + x = torch.randn((3, 3), dtype=torch.float64) + param = Parameter(((0.0 + 1.0j) * x).to(torch.cfloat)) + + optimizer = adam_optimizer_cls(params=[param], betas=(0.5, 0.5)) + + loss = torch.view_as_real((param * param.conj())).sum() + # grad x^2 = 2x, grads are all 0 + 2j * x + + loss.backward() + optimizer.step() + + # momentum value should be elemwise (2jx * -2jx * (1 - 0.5)) = 4x**2 * 0.5 = 2x**2 + # exp_avg_sq should be empty, meaning it is just momentum * (1-beta2) + momentum = optimizer.state[param]["exp_avg_sq"] + assert_close(momentum, (2 * x**2).to(torch.cfloat)) + + +@pytest.mark.parametrize("tensorgrad_param_pct", [0.25, 0.5, 1.0]) +@pytest.mark.parametrize("n_dim", [2, 3, 4]) +def test_tensorgrad_low_rank_projection(tensorgrad_param_pct, n_dim): + """TensorGRaD low-rank projection should preserve the requested rank size.""" + + full_rank_tensor = torch.randn([8] * n_dim) + + tensorgrad_rank = validate_tucker_rank( + full_rank_tensor.shape, + tensorgrad_param_pct, + ) + projector = TensorGRaDProjector(rank=tensorgrad_rank, warm_restart=True) + + # test that the projection is the correct size + # test 0th iter for full computation + low_rank_tensor = projector.project(full_rank_tensor, 0) + assert low_rank_tensor.numel() == math.prod(tensorgrad_rank) + + +def test_tensorgrad_low_rank_projection_updates_after_gap(): + """TensorGRaD should refresh the low-rank projection at the configured gap.""" + + full_rank_tensor = torch.randn(4, 4) + projector = TensorGRaDProjector(rank=(2, 2), update_proj_gap=2) + projection_calls = [] + + def get_projection_tensor(weights, rank): + projection_calls.append((weights.shape, rank)) + return [torch.eye(4)[:, :2], torch.eye(4)[:, :2]] + + projector.get_projection_tensor = get_projection_tensor + + projector.project(full_rank_tensor, 0) + projector.project(full_rank_tensor, 1) + projector.project(full_rank_tensor, 2) + + assert projection_calls == [ + (full_rank_tensor.shape, (2, 2)), + (full_rank_tensor.shape, (2, 2)), + ] + + +def test_tensorgrad_low_rank_projection_warm_restart_updates(): + """Warm restart should pass TensorLy a valid Tucker initialization.""" + + full_rank_tensor = torch.randn(4, 4) + projector = TensorGRaDProjector( + rank=(2, 2), + update_proj_gap=1, + warm_restart=True, + ) + + first_projection = projector.project(full_rank_tensor, 0) + second_projection = projector.project(full_rank_tensor, 1) + + assert first_projection.shape == (2, 2) + assert second_projection.shape == (2, 2) + + +def test_tensorgrad_activation_checkpoint_projection(): + """Checkpointed TensorLy calls should preserve projection behavior.""" + + full_rank_tensor = torch.randn(4, 4) + projector = TensorGRaDProjector( + rank=(2, 2), + activation_checkpoint=True, + ) + + low_rank_tensor = projector.project(full_rank_tensor, 0) + + assert low_rank_tensor.shape == (2, 2) + + +@pytest.mark.parametrize("activation_checkpoint", [False, True]) +def test_tensorgrad_projector_passes_tucker_n_iter_max( + monkeypatch, + activation_checkpoint, +): + """The projector should wire tucker_n_iter_max into TensorLy Tucker calls.""" + + n_iter_max_values = [] + + def fake_tucker(tensor, *, rank, init, n_iter_max): + n_iter_max_values.append(n_iter_max) + factors = [ + torch.eye(dim, rank_dim, dtype=tensor.dtype, device=tensor.device) + for dim, rank_dim in zip(tensor.shape, rank) + ] + return tensor, factors + + monkeypatch.setattr(tensorgrad_module, "tucker", fake_tucker) + + projector = TensorGRaDProjector( + rank=(2, 2), + tucker_n_iter_max=3, + activation_checkpoint=activation_checkpoint, + ) + + projector.get_projection_tensor(torch.randn(4, 4), (2, 2)) + + assert n_iter_max_values == [3] + + +@pytest.mark.parametrize("galore_param_pct", [0.25, 0.5, 1.0]) +def test_galore_adamw_rank(galore_param_pct): + """AdamW's legacy low-rank path should store optimizer state in projected size.""" + + x = torch.randn((8, 8, 8, 8), dtype=torch.float64) + param = Parameter(((0.0 + 1.0j) * x).to(torch.cfloat)) + galore_param = Parameter(((1.0 + 0j) * x).to(torch.cfloat)) + + # pick mode-wise rank so that low_rank_grad.numel() / full_rank_grad.numel() == galore_param_pct + galore_rank = validate_tucker_rank(galore_param.shape, galore_param_pct) + + optimizer = AdamW( + params=[param], + galore_params=[galore_param], + galore_rank=galore_rank, + betas=(0.5, 0.5), + ) + + loss = torch.view_as_real((param * galore_param.conj())).sum() + + loss.backward() + optimizer.step() + + momentum = optimizer.state[galore_param]["exp_avg_sq"] + # make sure low-rank params are being stored + assert momentum.numel() == math.prod(galore_rank) + + +def test_unstructured_sparse_projector_topk(): + """Sparse top-k projection should keep only the requested largest entries.""" + + grad = torch.arange(1, 17, dtype=torch.float32).reshape(4, 4) + projector = UnstructuredSparseProjector( + sparse_ratio=0.25, + sparse_type="topk", + update_proj_gap=1, + ) + + sparse_grad = projector.project(grad, step=0) + projected_back = projector.project_back(sparse_grad) + + assert sparse_grad.numel() == 4 + assert torch.count_nonzero(projected_back) == 4 + assert_close(projected_back.max(), grad.max()) + + +def test_tensorgrad_low_rank_stores_compressed_state(): + """Low-rank TensorGRaD should keep Adam moments in compressed coordinates.""" + + param = Parameter(torch.randn(4, 4, 4, dtype=torch.float32)) + optimizer = TensorGRaD( + [ + { + "params": [param], + "tensorgrad": True, + "rank": 0.5, + "update_proj_gap": 1, + } + ], + betas=(0.5, 0.5), + ) + + loss = (param**2).sum() + loss.backward() + optimizer.step() + + state = optimizer.state[param] + assert state["step"] == 1 + assert "low_rank_exp_avg_sq" in state + assert state["low_rank_exp_avg_sq"].numel() < param.numel() + + +def test_tensorgrad_low_rank_sparse_stores_two_compressed_states(): + """Low-rank+sparse TensorGRaD should keep separate compressed moment states.""" + + param = Parameter(torch.randn(4, 4, 4, dtype=torch.float32)) + optimizer = TensorGRaD( + [ + { + "params": [param], + "tensorgrad": True, + "rank": 0.5, + "sparse_ratio": 0.25, + "sparse_type": "topk", + "update_proj_gap": 1, + } + ], + betas=(0.5, 0.5), + ) + + loss = (param**2).sum() + loss.backward() + optimizer.step() + + state = optimizer.state[param] + assert state["step"] == 1 + assert "low_rank_exp_avg_sq" in state + assert "sparse_exp_avg_sq" in state + assert state["sparse_exp_avg_sq"].numel() == int(0.25 * param.numel()) + + +def test_fno_tensorgrad_param_groups_select_spectral_params(): + """FNO helper should split spectral-convolution params from regular params.""" + + model = FNO( + n_modes=(4, 4), + hidden_channels=8, + in_channels=1, + out_channels=1, + projection_channel_ratio=2, + ) + + groups = fno_tensorgrad_param_groups( + model, + rank=0.25, + sparse_ratio=0.05, + min_params=0, + ) + + regular_params = groups[0]["params"] + tensorgrad_params = groups[1]["params"] + regular_ids = {id(param) for param in regular_params} + tensorgrad_ids = {id(param) for param in tensorgrad_params} + + assert groups[1]["tensorgrad"] + assert groups[1]["sparse_ratio"] == 0.05 + assert tensorgrad_params + assert regular_ids.isdisjoint(tensorgrad_ids) diff --git a/sources/neuraloperator/neuralop/training/tests/test_patching.py b/sources/neuraloperator/neuralop/training/tests/test_patching.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8ed4b7d7e97a1cecea477dc3294e91a1625a1d --- /dev/null +++ b/sources/neuraloperator/neuralop/training/tests/test_patching.py @@ -0,0 +1,85 @@ +import torch +import pytest + +from ..patching import MultigridPatching2D, make_patches +from neuralop.tests.test_utils import DummyModel + +# Input shape params +batch_size = 16 +channels = 1 +side_len = 128 + + +@pytest.mark.parametrize("levels", [1, 2, 3]) +@pytest.mark.parametrize("padding_fraction", [0, 0.1, 0.2]) +def test_make_patches(levels, padding_fraction): + x = torch.randn(batch_size, channels, side_len, side_len) + n_patches = 2**levels + + padding = int(round(side_len * padding_fraction)) + patched_x = make_patches(x, n_patches, padding) + + patched_side_len = int((side_len // n_patches) + (2 * padding)) + assert patched_x.shape == ( + (n_patches**2) * batch_size, + channels, + patched_side_len, + patched_side_len, + ) + + +@pytest.mark.parametrize("levels", [1, 2, 3]) +@pytest.mark.parametrize("padding_fraction", [0, 0.1, 0.2]) +@pytest.mark.parametrize("stitching", [True, False]) +@pytest.mark.parametrize("evaluation", [True, False]) +def test_full_mgp2d(levels, padding_fraction, stitching, evaluation): + model = DummyModel(16) + patcher = MultigridPatching2D( + model=model, + levels=levels, + padding_fraction=padding_fraction, + stitching=stitching, # cpu-only, single process + use_distributed=False, + ) + + input_shape = (batch_size, channels, side_len, side_len) + x = torch.randn(*input_shape) + y = torch.randn(*input_shape) + + patched_x, patched_y = patcher.patch(x, y) + n_patches = 2**levels + padding = int(round(side_len * padding_fraction)) + patched_padded_side_len = int((side_len // n_patches) + (2 * padding)) + + assert patched_x.shape == ( + (n_patches**2) * batch_size, + channels + levels, + patched_padded_side_len, + patched_padded_side_len, + ) + + # mimic output after scattering x to model parallel region + patched_out_shape = (patched_x.shape[0], 1, *patched_x.shape[2:]) + patched_out = torch.randn(patched_out_shape) + + # if padding is not applied, return without stitching + # otherwise unpad and stitch + + if stitching or evaluation: + unpatch_shape = input_shape + else: + unpadded_patch_size = int(side_len // n_patches) + unpatch_shape = ( + patched_x.shape[0], + channels, + unpadded_patch_size, + unpadded_patch_size, + ) + + # test stitching here in cases where padding is applied + unpatched_x, unpatched_y = patcher.unpatch( + patched_out, patched_y, evaluation=evaluation + ) + + assert unpatched_x.shape == unpatch_shape + assert unpatched_y.shape == unpatch_shape diff --git a/sources/neuraloperator/neuralop/training/tests/test_trainer.py b/sources/neuraloperator/neuralop/training/tests/test_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c03c8c5efe0160b8283f45a1ff82df5a60f6756b --- /dev/null +++ b/sources/neuraloperator/neuralop/training/tests/test_trainer.py @@ -0,0 +1,238 @@ +import os +import shutil +from pathlib import Path + +import torch +from torch import nn +from torch.utils.data import Dataset, DataLoader +from neuralop.models import FNO +from neuralop.data.datasets import load_darcy_flow_small + +from neuralop import Trainer, LpLoss, H1Loss +from neuralop.tests.test_utils import DummyDataset, DummyModel +from neuralop.training import IncrementalFNOTrainer, AdamW + + +def test_model_checkpoint_saves(): + save_pth = Path("./test_checkpoints") + + model = DummyModel(50) + + train_loader = DataLoader(DummyDataset(100)) + + trainer = Trainer( + model=model, + n_epochs=5, + ) + + optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-4) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + + # Creating the losses + l2loss = LpLoss(d=2, p=2) + + trainer.train( + train_loader=train_loader, + test_loaders={}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=None, + training_loss=l2loss, + eval_losses=None, + save_dir=save_pth, + save_every=1, + ) + + for file_ext in [ + "model_state_dict.pt", + "model_metadata.pkl", + "optimizer.pt", + "scheduler.pt", + ]: + file_pth = save_pth / file_ext + assert file_pth.exists() + + # clean up dummy checkpoint directory after testing + shutil.rmtree("./test_checkpoints") + + +def test_model_checkpoint_and_resume(): + save_pth = Path("./full_states") + model = DummyModel(50) + + train_loader = DataLoader(DummyDataset(100)) + test_loader = DataLoader(DummyDataset(20)) + + trainer = Trainer(model=model, n_epochs=5, verbose=True) + + optimizer = AdamW(model.parameters(), lr=3e-4, weight_decay=1e-4) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + + # Creating the losses + l2loss = LpLoss(d=2, p=2) + h1loss = H1Loss(d=2) + + eval_losses = {"h1": h1loss, "l2": l2loss} + + trainer.train( + train_loader=train_loader, + test_loaders={"test": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=None, + training_loss=l2loss, + eval_losses=eval_losses, + save_best="test_h1", + save_dir=save_pth, + save_every=1, + ) + + for file_ext in [ + "best_model_state_dict.pt", + "best_model_metadata.pkl", + "optimizer.pt", + "scheduler.pt", + ]: + file_pth = save_pth / file_ext + + assert file_pth.exists() + + # Resume from checkpoint + + new_model = DummyModel(50) + new_optimizer = AdamW(new_model.parameters(), lr=3e-4, weight_decay=1e-4) + trainer = Trainer(model=new_model, n_epochs=10, verbose=True) + errors = trainer.train( + train_loader=train_loader, + test_loaders={"": test_loader}, + optimizer=new_optimizer, + scheduler=scheduler, + regularizer=None, + training_loss=l2loss, + eval_losses=eval_losses, + resume_from_dir=save_pth, + ) + + # Ensure model and opt parameter IDs match after reloading - otherwise model will not train + + # Get model and optimizer parameters as a set of IDs + model_param_ids = {id(p) for p in trainer.model.parameters()} + optimizer_param_ids = {id(p) for group in trainer.optimizer.param_groups for p in group["params"]} + + # Check for mismatches, assert there are none + missing_in_optimizer = model_param_ids - optimizer_param_ids + missing_in_model = optimizer_param_ids - model_param_ids + + assert not missing_in_optimizer and not missing_in_model + + # clean up dummy checkpoint directory after testing + shutil.rmtree(save_pth) + + +# ensure that model accuracy after loading from checkpoint +# is comparable to accuracy at time of save +def test_load_from_checkpoint(): + model = DummyModel(50) + + train_loader = DataLoader(DummyDataset(100)) + test_loader = DataLoader(DummyDataset(100)) + + trainer = Trainer(model=model, n_epochs=10) + + optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-4) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + + # Creating the losses + l2loss = LpLoss(d=2, p=2) + h1loss = H1Loss(d=2) + + eval_losses = {"h1": h1loss, "l2": l2loss} + + orig_model_eval_errors = trainer.train( + train_loader=train_loader, + test_loaders={"test": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=None, + training_loss=l2loss, + eval_losses=eval_losses, + save_dir="./full_states", + save_every=1, + ) + + # create a new model from saved checkpoint and evaluate + loaded_model = DummyModel.from_checkpoint(save_folder="./full_states", save_name="model") + trainer = Trainer(model=loaded_model, n_epochs=1) + + loaded_model_eval_errors = trainer.evaluate( + loss_dict=eval_losses, data_loader=test_loader, log_prefix="test" + ) + + # test l2 difference should be small + assert ( + orig_model_eval_errors["test_l2"] - loaded_model_eval_errors["test_l2"] + ) / orig_model_eval_errors["test_l2"] < 0.1 + + # clean up dummy checkpoint directory after testing + shutil.rmtree("./full_states") + + +# enure that the model incrementally increases in frequency modes +def test_incremental(): + # Loading the Darcy flow dataset + train_loader, test_loaders, output_encoder = load_darcy_flow_small( + n_train=10, + batch_size=16, + test_resolutions=[16, 32], + n_tests=[10, 5], + test_batch_sizes=[32, 32], + ) + + initial_n_modes = (2, 2) + initial_max_modes = (16, 16) + + model = FNO( + n_modes=initial_n_modes, + max_n_modes=initial_max_modes, + hidden_channels=32, + in_channels=1, + out_channels=1, + ) + + trainer = IncrementalFNOTrainer( + model=model, + n_epochs=20, + incremental_loss_gap=False, + incremental_grad=True, + incremental_grad_eps=0.9999, + incremental_buffer=5, + incremental_max_iter=1, + incremental_grad_max_iter=2, + ) + + optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-4) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + + # Creating the losses + l2loss = LpLoss(d=2, p=2) + h1loss = H1Loss(d=2) + + eval_losses = {"h1": h1loss, "l2": l2loss} + + trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=None, + training_loss=l2loss, + eval_losses=eval_losses, + ) + + # assert that the model has increased in frequency modes + for i in range(len(initial_n_modes)): + assert model.fno_blocks.convs[0].n_modes[i] > initial_n_modes[i] + + # assert that the model has not changed the max modes + for i in range(len(initial_max_modes)): + assert model.fno_blocks.convs[0].max_n_modes[i] == initial_max_modes[i] diff --git a/sources/neuraloperator/neuralop/training/torch_setup.py b/sources/neuraloperator/neuralop/training/torch_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..188924d0dfad1a09f45c9d8cad9343fa2d8752dc --- /dev/null +++ b/sources/neuraloperator/neuralop/training/torch_setup.py @@ -0,0 +1,93 @@ +import torch +import neuralop.mpu.comm as comm + + +def setup(config): + """A convenience function to intialize the device, setup torch settings and + check multi-grid and other values. It sets up distributed communitation, if used. + + Parameters + ---------- + config : dict + this function checks: + * config.distributed (use_distributed, seed) + * config.data (n_train, batch_size, test_batch_sizes, n_tests, test_resolutions) + + Returns + ------- + device, is_logger + device : torch.device + is_logger : bool + """ + seed = config.distributed.seed + + if config.distributed.use_distributed: + comm.init( + model_parallel_size=config.distributed.model_parallel_size, + verbose=config.verbose, + ) + + # Set process 0 to log screen and wandb + is_logger = comm.get_local_rank() == 0 + + # Set device and random seed + device = torch.device(f"cuda:{comm.get_local_rank()}") + + if seed is not None: + seed = seed + comm.get_data_parallel_rank() + + # Ensure batch can be evenly split among the model-parallel group + if config.patching.levels > 0: + assert(config.data.batch_size*(2**(2*config.patching.levels)) % comm.get_model_parallel_size() == 0), ( + f'With MG patching, total batch-size of {config.data.batch_size*(2**(2*config.patching.levels))}' + f' ({config.data.batch_size} times {(2**(2*config.patching.levels))}).' + f' However, this total batch-size cannot be evenly split among the {comm.get_model_parallel_size()} model-parallel groups.' + ) + for b_size in config.data.test_batch_sizes: + assert (b_size*(2**(2*config.patching.levels)) % comm.get_model_parallel_size() == 0), ( + f'With MG patching, for test resolution of {config.data.test_resolutions[j]}' + f' the total batch-size is {config.data.batch_size*(2**(2*config.patching.levels))}' + f' ({config.data.batch_size} times {(2**(2*config.patching.levels))}).' + f' However, this total batch-size cannot be evenly split among the {comm.get_model_parallel_size()} model-parallel groups.' + ) + + else: + is_logger = True + if torch.cuda.is_available(): + device = torch.device("cuda:0") + else: + device = torch.device("cpu") + + # Set device, random seed and optimization + if torch.cuda.is_available(): + torch.cuda.set_device(device.index) + + if seed is not None: + torch.cuda.manual_seed(seed) + increase_l2_fetch_granularity() + try: + torch.set_float32_matmul_precision("high") + except AttributeError: + pass + + torch.backends.cudnn.benchmark = True + + if seed is not None: + torch.manual_seed(seed) + + return device, is_logger + + +def increase_l2_fetch_granularity(): + try: + import ctypes + + _libcudart = ctypes.CDLL("libcudart.so") + # Set device limit on the current device + # cudaLimitMaxL2FetchGranularity = 0x05 + pValue = ctypes.cast((ctypes.c_int * 1)(), ctypes.POINTER(ctypes.c_int)) + _libcudart.cudaDeviceSetLimit(ctypes.c_int(0x05), ctypes.c_int(128)) + _libcudart.cudaDeviceGetLimit(pValue, ctypes.c_int(0x05)) + assert pValue.contents.value == 128 + except: + return diff --git a/sources/neuraloperator/neuralop/training/trainer.py b/sources/neuraloperator/neuralop/training/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd714a47c6604fa16c984b99e77993e374332e6 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/trainer.py @@ -0,0 +1,822 @@ +from timeit import default_timer +from pathlib import Path +from typing import Union +import sys +import warnings + +import torch +from torch.cuda import amp +from torch import nn +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel as DDP + +# Only import wandb and use if installed +wandb_available = False +try: + import wandb + + wandb_available = True +except ModuleNotFoundError: + wandb_available = False + +import neuralop.mpu.comm as comm +from neuralop.losses import LpLoss +from .training_state import load_training_state, save_training_state + + +class Trainer: + """ + A general Trainer class to train neural-operators on given datasets. + + .. note :: + Our 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. + For specifics and an example, check ``neuralop.data.datasets.DarcyDataset``. + + Parameters + ---------- + model : nn.Module + n_epochs : int + wandb_log : bool, default is False + whether to log results to wandb + device : torch.device, or str 'cpu' or 'cuda' + mixed_precision : bool, default is False + whether to use torch.autocast to compute mixed precision + data_processor : DataProcessor class to transform data, default is None + 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. + eval_interval : int, default is 1 + how frequently to evaluate model and log training stats + log_output : bool, default is False + if True, and if wandb_log is also True, log output images to wandb + use_distributed : bool, default is False + whether to use DDP + verbose : bool, default is False + """ + + def __init__( + self, + *, + model: nn.Module, + n_epochs: int, + wandb_log: bool = False, + device: str = "cpu", + mixed_precision: bool = False, + data_processor: nn.Module = None, + eval_interval: int = 1, + log_output: bool = False, + use_distributed: bool = False, + verbose: bool = False, + ): + """ """ + + self.model = model + self.n_epochs = n_epochs + # only log to wandb if a run is active + self.wandb_log = False + if wandb_available: + self.wandb_log = wandb_log and wandb.run is not None + self.eval_interval = eval_interval + self.log_output = log_output + self.verbose = verbose + self.use_distributed = use_distributed + self.device = device + # handle autocast device + if isinstance(self.device, torch.device): + self.autocast_device_type = self.device.type + else: + if "cuda" in self.device: + self.autocast_device_type = "cuda" + else: + self.autocast_device_type = "cpu" + self.mixed_precision = mixed_precision + self.data_processor = data_processor + + # Track starting epoch for checkpointing/resuming + self.start_epoch = 0 + + def train( + self, + train_loader, + test_loaders, + optimizer, + scheduler, + regularizer=None, + training_loss=None, + eval_losses=None, + eval_modes=None, + save_every: int = None, + save_best: int = None, + save_dir: Union[str, Path] = "./ckpt", + resume_from_dir: Union[str, Path] = None, + max_autoregressive_steps: int = None, + ): + """Trains the given model on the given dataset. + + If a device is provided, the model and data processor are loaded to device here. + + Parameters + ---------- + train_loader: torch.utils.data.DataLoader + training dataloader + test_loaders: dict[torch.utils.data.DataLoader] + testing dataloaders + optimizer: torch.optim.Optimizer + optimizer to use during training + scheduler: torch.optim.lr_scheduler + learning rate scheduler to use during training + training_loss: training.losses function + cost function to minimize + eval_losses: dict[Loss] + dict of losses to use in self.eval() + eval_modes: dict[str], optional + optional mapping from the name of each loader to its evaluation mode. + + * if 'single_step', predicts one input-output pair and evaluates loss. + + * if 'autoregressive', autoregressively predicts output using last step's + output as input for a number of steps defined by the temporal dimension of the batch. + This requires specially batched data with a data processor whose ``.preprocess`` and + ``.postprocess`` both take ``idx`` as an argument. + save_every: int, optional, default is None + if provided, interval at which to save checkpoints + save_best: str, optional, default is None + if provided, key of metric f"{loader_name}_{loss_name}" + to monitor and save model with best eval result + Overrides save_every and saves on eval_interval + save_dir: str | Path, default "./ckpt" + directory at which to save training states if + save_every and/or save_best is provided + resume_from_dir: str | Path, default None + if provided, resumes training state (model, optimizer, regularizer, scheduler) + from state saved in `resume_from_dir` + max_autoregressive_steps : int, default None + if provided, and a dataloader is to be evaluated in autoregressive mode, + limits the number of autoregressive in each rollout to be performed. + + Returns + ------- + all_metrics: dict + dictionary keyed f"{loader_name}_{loss_name}" + of metric results for last validation epoch across + all test_loaders + + """ + self.optimizer = optimizer + self.scheduler = scheduler + if regularizer: + self.regularizer = regularizer + else: + self.regularizer = None + + if training_loss is None: + training_loss = LpLoss(d=2) + + # Warn the user if training loss is reducing across the batch + if hasattr(training_loss, "reduction"): + if training_loss.reduction == "mean": + warnings.warn( + f"{training_loss.reduction=}. This means that the loss is " + "initialized to average across the batch dim. The Trainer " + "expects losses to sum across the batch dim." + ) + + if eval_losses is None: # By default just evaluate on the training loss + eval_losses = dict(l2=training_loss) + + # accumulated wandb metrics + self.wandb_epoch_metrics = None + + # create default eval modes + if eval_modes is None: + eval_modes = {} + + # attributes for checkpointing + self.save_every = save_every + self.save_best = save_best + if resume_from_dir is not None: + self.resume_state_from_dir(resume_from_dir) + + # Load model and data_processor to device + self.model = self.model.to(self.device) + + if self.use_distributed and dist.is_initialized(): + device_id = dist.get_rank() + self.model = DDP(self.model, device_ids=[device_id], output_device=device_id) + + if self.data_processor is not None: + self.data_processor = self.data_processor.to(self.device) + + # ensure save_best is a metric we collect + if self.save_best is not None: + metrics = [] + for name in test_loaders.keys(): + for metric in eval_losses.keys(): + metrics.append(f"{name}_{metric}") + assert ( + self.save_best in metrics + ), f"Error: expected a metric of the form _, got {save_best}" + best_metric_value = float("inf") + # either monitor metric or save on interval, exclusive for simplicity + self.save_every = None + + if self.verbose: + print(f"Training on {len(train_loader.dataset)} samples") + print(f"Testing on {[len(loader.dataset) for loader in test_loaders.values()]} samples" + f" on resolutions {[name for name in test_loaders]}.") + sys.stdout.flush() + + for epoch in range(self.start_epoch, self.n_epochs): + ( + train_err, + avg_loss, + avg_lasso_loss, + epoch_train_time, + ) = self.train_one_epoch(epoch, train_loader, training_loss) + epoch_metrics = dict( + train_err=train_err, + avg_loss=avg_loss, + avg_lasso_loss=avg_lasso_loss, + epoch_train_time=epoch_train_time, + ) + + if epoch % self.eval_interval == 0: + # evaluate and gather metrics across each loader in test_loaders + eval_metrics = self.evaluate_all( + epoch=epoch, + eval_losses=eval_losses, + test_loaders=test_loaders, + eval_modes=eval_modes, + max_autoregressive_steps=max_autoregressive_steps, + ) + epoch_metrics.update(**eval_metrics) + # save checkpoint if conditions are met + if save_best is not None: + if eval_metrics[save_best] < best_metric_value: + best_metric_value = eval_metrics[save_best] + self.checkpoint(save_dir) + + # save checkpoint if save_every and save_best is not set + if self.save_every is not None: + if epoch % self.save_every == 0: + self.checkpoint(save_dir) + + return epoch_metrics + + def train_one_epoch(self, epoch, train_loader, training_loss): + """train_one_epoch trains self.model on train_loader + for one epoch and returns training metrics + + Parameters + ---------- + epoch : int + epoch number + train_loader : torch.utils.data.DataLoader + data loader of train examples + test_loaders : dict + dict of test torch.utils.data.DataLoader objects + + Returns + ------- + all_errors + dict of all eval metrics for the last epoch + """ + self.on_epoch_start(epoch) + avg_loss = 0 + avg_lasso_loss = 0 + self.model.train() + if self.data_processor: + self.data_processor.train() + t1 = default_timer() + train_err = 0.0 + + # track number of training examples in batch + self.n_samples = 0 + + for idx, sample in enumerate(train_loader): + loss = self.train_one_batch(idx, sample, training_loss) + loss.backward() + self.optimizer.step() + + train_err += loss.item() + with torch.no_grad(): + avg_loss += loss.item() + if self.regularizer: + avg_lasso_loss += self.regularizer.loss + + if isinstance(self.scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): + self.scheduler.step(train_err) + else: + self.scheduler.step() + + epoch_train_time = default_timer() - t1 + + train_err /= len(train_loader) + avg_loss /= self.n_samples + if self.regularizer: + avg_lasso_loss /= self.n_samples + else: + avg_lasso_loss = None + + lr = None + for pg in self.optimizer.param_groups: + lr = pg["lr"] + if self.verbose and epoch % self.eval_interval == 0: + self.log_training( + epoch=epoch, + time=epoch_train_time, + avg_loss=avg_loss, + train_err=train_err, + avg_lasso_loss=avg_lasso_loss, + lr=lr, + ) + + return train_err, avg_loss, avg_lasso_loss, epoch_train_time + + def evaluate_all( + self, + epoch, + eval_losses, + test_loaders, + eval_modes, + max_autoregressive_steps=None, + ): + """evaluate_all iterates through the entire dict of test_loaders + to perform evaluation on the whole dataset stored in each one. + + Parameters + ---------- + epoch : int + current training epoch + eval_losses : dict[Loss] + keyed ``loss_name: loss_obj`` for each pair. Full set of + losses to use in evaluation for each test loader. + test_loaders : dict[DataLoader] + keyed ``loader_name: loader`` for each test loader. + eval_modes : dict[str], optional + keyed ``loader_name: eval_mode`` for each test loader. + * If ``eval_modes.get(loader_name)`` does not return a value, + the evaluation is automatically performed in ``single_step`` mode. + max_autoregressive_steps : ``int``, optional + if provided, and one of the test loaders has ``eval_mode == "autoregressive"``, + limits the number of autoregressive steps performed per rollout. + + Returns + ------- + all_metrics: dict + collected eval metrics for each loader. + """ + # evaluate and gather metrics across each loader in test_loaders + all_metrics = {} + for loader_name, loader in test_loaders.items(): + loader_eval_mode = eval_modes.get(loader_name, "single_step") + loader_metrics = self.evaluate( + eval_losses, + loader, + log_prefix=loader_name, + mode=loader_eval_mode, + max_steps=max_autoregressive_steps, + ) + all_metrics.update(**loader_metrics) + if self.verbose: + self.log_eval(epoch=epoch, eval_metrics=all_metrics) + return all_metrics + + def evaluate( + self, + loss_dict, + data_loader, + log_prefix="", + epoch=None, + mode="single_step", + max_steps=None, + ): + """Evaluates the model on a dictionary of losses + + Parameters + ---------- + loss_dict : dict of functions + each function takes as input a tuple (prediction, ground_truth) + and returns the corresponding loss + data_loader : data_loader to evaluate on + log_prefix : str, default is '' + if not '', used as prefix in output dictionary + epoch : int | None + current epoch. Used when logging both train and eval + default None + mode : Literal {'single_step', 'autoregression'} + if 'single_step', performs standard evaluation + if 'autoregression' loops through `max_steps` steps + max_steps : int, optional + max number of steps for autoregressive rollout. + If None, runs the full rollout. + Returns + ------- + errors : dict + dict[f'{log_prefix}_{loss_name}] = loss for loss in loss_dict + """ + # Ensure model and data processor are loaded to the proper device + + self.model = self.model.to(self.device) + if self.data_processor is not None and self.data_processor.device != self.device: + self.data_processor = self.data_processor.to(self.device) + + self.model.eval() + if self.data_processor: + self.data_processor.eval() + + errors = {f"{log_prefix}_{loss_name}": 0 for loss_name in loss_dict.keys()} + + # Warn the user if any of the eval losses is reducing across the batch + for _, eval_loss in loss_dict.items(): + if hasattr(eval_loss, "reduction"): + if eval_loss.reduction == "mean": + warnings.warn( + f"{eval_loss.reduction=}. This means that the loss is " + "initialized to average across the batch dim. The Trainer " + "expects losses to sum across the batch dim." + ) + + self.n_samples = 0 + with torch.no_grad(): + for idx, sample in enumerate(data_loader): + return_output = False + if idx == len(data_loader) - 1: + return_output = True + if mode == "single_step": + eval_step_losses, outs = self.eval_one_batch( + sample, loss_dict, return_output=return_output + ) + elif mode == "autoregression": + eval_step_losses, outs = self.eval_one_batch_autoreg( + sample, + loss_dict, + return_output=return_output, + max_steps=max_steps, + ) + + for loss_name, val_loss in eval_step_losses.items(): + errors[f"{log_prefix}_{loss_name}"] += val_loss + + for key in errors.keys(): + errors[key] /= self.n_samples + + # on last batch, log model outputs + if self.log_output and self.wandb_log: + errors[f"{log_prefix}_outputs"] = wandb.Image(outs) + + return errors + + def on_epoch_start(self, epoch): + """on_epoch_start runs at the beginning + of each training epoch. This method is a stub + that can be overwritten in more complex cases. + + Parameters + ---------- + epoch : int + index of epoch + + Returns + ------- + None + """ + self.epoch = epoch + return None + + def train_one_batch(self, idx, sample, training_loss): + """Run one batch of input through model + and return training loss on outputs + + Parameters + ---------- + idx : int + index of batch within train_loader + sample : dict + data dictionary holding one batch + + Returns + ------- + loss: float | Tensor + float value of training loss + """ + + self.optimizer.zero_grad(set_to_none=True) + if self.regularizer: + self.regularizer.reset() + if self.data_processor is not None: + sample = self.data_processor.preprocess(sample) + else: + # load data to device if no preprocessor exists + sample = {k: v.to(self.device) for k, v in sample.items() if torch.is_tensor(v)} + + if isinstance(sample["y"], torch.Tensor): + self.n_samples += sample["y"].shape[0] + else: + self.n_samples += 1 + + if self.mixed_precision: + with torch.autocast(device_type=self.autocast_device_type): + out = self.model(**sample) + else: + out = self.model(**sample) + + if self.epoch == 0 and idx == 0 and self.verbose and isinstance(out, torch.Tensor): + print(f"Raw outputs of shape {out.shape}") + + if self.data_processor is not None: + out, sample = self.data_processor.postprocess(out, sample) + + loss = 0.0 + + if self.mixed_precision: + with torch.autocast(device_type=self.autocast_device_type): + loss += training_loss(out, **sample) + else: + loss += training_loss(out, **sample) + + if self.regularizer: + loss += self.regularizer.loss + + return loss + + def eval_one_batch( + self, sample: dict, eval_losses: dict, return_output: bool = False + ): + """eval_one_batch runs inference on one batch + and returns eval_losses for that batch. + + Parameters + ---------- + sample : dict + data batch dictionary + eval_losses : dict + dictionary of named eval metrics + return_outputs : bool + whether to return model outputs for plotting + by default False + Returns + ------- + eval_step_losses : dict + keyed "loss_name": step_loss_value for each loss name + outputs: torch.Tensor | None + optionally returns batch outputs + """ + if self.data_processor is not None: + sample = self.data_processor.preprocess(sample) + else: + # load data to device if no preprocessor exists + sample = {k: v.to(self.device) for k, v in sample.items() if torch.is_tensor(v)} + + self.n_samples += sample["y"].size(0) + + out = self.model(**sample) + + if self.data_processor is not None: + out, sample = self.data_processor.postprocess(out, sample) + + eval_step_losses = {} + + for loss_name, loss in eval_losses.items(): + val_loss = loss(out, **sample) + eval_step_losses[loss_name] = val_loss + + if return_output: + return eval_step_losses, out + else: + return eval_step_losses, None + + def eval_one_batch_autoreg( + self, + sample: dict, + eval_losses: dict, + return_output: bool = False, + max_steps: int = None, + ): + """eval_one_batch runs inference on one batch + and returns eval_losses for that batch. + + Parameters + ---------- + sample : dict + data batch dictionary + eval_losses : dict + dictionary of named eval metrics + return_outputs : bool + whether to return model outputs for plotting + by default False + max_steps: int + number of timesteps to roll out + typically the full trajectory length + If max_steps is none, runs until the full length + + .. note:: + If a value for ``max_steps`` is not provided, a data_processor + must be provided to handle rollout logic. + Returns + ------- + eval_step_losses : dict + keyed "loss_name": step_loss_value for each loss name + outputs: torch.Tensor | None + optionally returns batch outputs + + + """ + eval_step_losses = {loss_name: 0.0 for loss_name in eval_losses.keys()} + # eval_rollout_losses = {loss_name: 0. for loss_name in eval_losses.keys()} + + t = 0 + if max_steps is None: + max_steps = float("inf") + + # only increment the sample count once + sample_count_incr = False + + while sample is not None and t < max_steps: + if self.data_processor is not None: + sample = self.data_processor.preprocess(sample, step=t) + else: + # load data to device if no preprocessor exists + sample = { + k: v.to(self.device) + for k, v in sample.items() + if torch.is_tensor(v) + } + + if sample is None: + break + + # only increment the sample count once + if not sample_count_incr: + self.n_samples += sample["y"].shape[0] + sample_count_incr = True + + out = self.model(**sample) + + if self.data_processor is not None: + out, sample = self.data_processor.postprocess(out, sample, step=t) + + for loss_name, loss in eval_losses.items(): + step_loss = loss(out, **sample) + eval_step_losses[loss_name] += step_loss + + t += 1 + # average over all steps of the final rollout + for loss_name in eval_step_losses.keys(): + eval_step_losses[loss_name] /= t + + if return_output: + return eval_step_losses, out + else: + return eval_step_losses, None + + def log_training( + self, + epoch: int, + time: float, + avg_loss: float, + train_err: float, + avg_lasso_loss: float = None, + lr: float = None, + ): + """Basic method to log results + from a single training epoch. + + + Parameters + ---------- + epoch: int + time: float + training time of epoch + avg_loss: float + average train_err per individual sample + train_err: float + train error for entire epoch + avg_lasso_loss: float + average lasso loss from regularizer, optional + lr: float + learning rate at current epoch + """ + # accumulate info to log to wandb + if self.wandb_log: + values_to_log = dict( + train_err=train_err, + time=time, + avg_loss=avg_loss, + avg_lasso_loss=avg_lasso_loss, + lr=lr, + ) + + msg = f"[{epoch}] time={time:.2f}, " + msg += f"avg_loss={avg_loss:.4f}, " + msg += f"train_err={train_err:.4f}" + if avg_lasso_loss is not None: + msg += f", avg_lasso={avg_lasso_loss:.4f}" + + print(msg) + sys.stdout.flush() + + if self.wandb_log: + wandb.log(data=values_to_log, step=epoch + 1, commit=False) + + def log_eval(self, epoch: int, eval_metrics: dict): + """log_eval logs outputs from evaluation + on all test loaders to stdout and wandb + + Parameters + ---------- + epoch : int + current training epoch + eval_metrics : dict + metrics collected during evaluation + keyed f"{test_loader_name}_{metric}" for each test_loader + + """ + values_to_log = {} + msg = "" + for metric, value in eval_metrics.items(): + if isinstance(value, float) or isinstance(value, torch.Tensor): + msg += f"{metric}={value:.4f}, " + if self.wandb_log: + values_to_log[metric] = value + + msg = f"Eval: " + msg[:-2] # cut off last comma+space + print(msg) + sys.stdout.flush() + + if self.wandb_log: + wandb.log(data=values_to_log, step=epoch + 1, commit=True) + + def resume_state_from_dir(self, save_dir): + """ + Resume training from save_dir created by `neuralop.training.save_training_state` + + Parameters + ---------- + save_dir: Union[str, Path] + directory in which training state is saved + (see neuralop.training.training_state) + """ + if isinstance(save_dir, str): + save_dir = Path(save_dir) + + # check for save model exists + if (save_dir / "best_model_state_dict.pt").exists(): + save_name = "best_model" + elif (save_dir / "model_state_dict.pt").exists(): + save_name = "model" + else: + raise FileNotFoundError( + "Error: resume_from_dir expects a model\ + state dict named model.pt or best_model.pt." + ) + # returns model, loads other modules if provided + + ( + self.model, + self.optimizer, + self.scheduler, + self.regularizer, + resume_epoch, + ) = load_training_state( + save_dir=save_dir, + save_name=save_name, + model=self.model, + optimizer=self.optimizer, + regularizer=self.regularizer, + scheduler=self.scheduler, + ) + + if resume_epoch is not None: + if resume_epoch > self.start_epoch: + self.start_epoch = resume_epoch + if self.verbose: + print(f"Trainer resuming from epoch {resume_epoch}") + + def checkpoint(self, save_dir): + """checkpoint saves current training state + to a directory for resuming later. Only saves + training state on the first GPU. + See neuralop.training.training_state + + Parameters + ---------- + save_dir : str | Path + directory in which to save training state + """ + if comm.get_local_rank() == 0: + if self.save_best is not None: + save_name = "best_model" + else: + save_name = "model" + save_training_state( + save_dir=save_dir, + save_name=save_name, + model=self.model, + optimizer=self.optimizer, + scheduler=self.scheduler, + regularizer=self.regularizer, + epoch=self.epoch, + ) + if self.verbose: + print(f"[Rank 0]: saved training state to {save_dir}") diff --git a/sources/neuraloperator/neuralop/training/training_state.py b/sources/neuraloperator/neuralop/training/training_state.py new file mode 100644 index 0000000000000000000000000000000000000000..60055f22768de33b17c5c25f2bffb97ef0451851 --- /dev/null +++ b/sources/neuraloperator/neuralop/training/training_state.py @@ -0,0 +1,158 @@ +""" +Snippet to load all artifacts of training state as Modules +without constraining to use inside a default Trainer +""" +from typing import Union +from pathlib import Path + +import torch +from torch import nn +import torch.distributed as dist +from neuralop.mpu.comm import get_local_rank + + +def load_training_state( + save_dir: Union[str, Path], + save_name: str, + model: nn.Module, + optimizer: nn.Module = None, + scheduler: nn.Module = None, + regularizer: nn.Module = None, + map_location: dict = None, +) -> dict: + """load_training_state returns model and optional other training modules + saved from prior training for downstream use + + Parameters + ---------- + 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 : nn.Module + model to save + optimizer : nn.Module, optional + optimizer object to save, by default None + scheduler : nn.Module, optional + scheduler object to save, by default None + regularizer : nn.Module, optional + regularizer object to save, by default None + map_location : dict, optional + mapping dictionary keyed `{device_from: device_to}`, by default None + dictionary instructs torch to load a model from a checkpoint on rank `device_from` + and send it to `device_to` + + Returns + ------- + tuple of training state + ``model, optimizer, scheduler, regularizer, epoch`` + + """ + if not map_location: + if dist.is_initialized(): + map_location = {"cuda:0": f"cuda:{get_local_rank()}"} + + if isinstance(save_dir, str): + save_dir = Path(save_dir) + + # optionally load epoch + epoch = None + manifest_pth = save_dir / "manifest.pt" + if manifest_pth.exists(): + manifest = torch.load(manifest_pth) + epoch = manifest.get("epoch") + + if dist.is_initialized(): + # To minimize CUDA memory overhead during checkpoint loading, + # load the model to CPU first, then load to GPU instead of mapping from + # CUDA:0 to CUDA:DEVICE_ID + device_id = get_local_rank() + save_pth = save_dir / f"{save_name}_state_dict.pt" + model.load_state_dict( + torch.load(save_pth.absolute().as_posix(), map_location="cpu") + ) + model = model.to(device=f"cuda:{device_id}") + torch.cuda.empty_cache() + else: + save_pth = save_dir / f"{save_name}_state_dict.pt" + model.load_state_dict(torch.load(save_pth.absolute().as_posix())) + + # load optimizer if state exists + if optimizer is not None: + optimizer_pth = save_dir / "optimizer.pt" + if optimizer_pth.exists(): + optimizer.load_state_dict(torch.load(optimizer_pth.absolute().as_posix(), map_location=map_location)) + else: + print(f"Warning: requested to load optimizer state, but no saved optimizer state exists in {save_dir}.") + + if scheduler is not None: + scheduler_pth = save_dir / "scheduler.pt" + if scheduler_pth.exists(): + scheduler.load_state_dict(torch.load(scheduler_pth.absolute().as_posix(), map_location=map_location)) + else: + print(f"Warning: requested to load scheduler state, but no saved scheduler state exists in {save_dir}.") + + if regularizer is not None: + regularizer_pth = save_dir / "regularizer.pt" + if regularizer_pth.exists(): + regularizer.load_state_dict(torch.load(regularizer_pth.absolute().as_posix(), map_location=map_location)) + else: + print(f"Warning: requested to load regularizer state, but no saved regularizer state exists in {save_dir}.") + + return model, optimizer, scheduler, regularizer, epoch + + +def save_training_state( + save_dir: Union[str, Path], + save_name: str, + model: nn.Module, + optimizer: nn.Module = None, + scheduler: nn.Module = None, + regularizer: nn.Module = None, + epoch: int = None, +) -> None: + """save_training_state returns model and optional other training modules + saved from prior training for downstream use + + Parameters + ---------- + 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 + """ + if isinstance(save_dir, str): + save_dir = Path(save_dir) + + manifest = {} + + # Just save the model.module if model is in DDP mode + if isinstance(model, torch.nn.parallel.DistributedDataParallel): + save_dir.mkdir(exist_ok=True, parents=True) + model_pth = save_dir / f"{save_name}_state_dict.pt" + torch.save(model.module.state_dict(), model_pth.as_posix()) + else: + # otherwise save the model checkpoint + model.save_checkpoint(save_dir, save_name) + manifest["model"] = f"{save_name}_state_dict.pt" + + # save optimizer if state exists + if optimizer is not None: + optimizer_pth = save_dir / "optimizer.pt" + torch.save(optimizer.state_dict(), optimizer_pth) + manifest["optimizer"] = "optimizer.pt" + + if scheduler is not None: + scheduler_pth = save_dir / "scheduler.pt" + torch.save(scheduler.state_dict(), scheduler_pth) + manifest["scheduler"] = "scheduler.pt" + + if regularizer is not None: + regularizer_pth = save_dir / "regularizer.pt" + torch.save(regularizer.state_dict(), regularizer_pth) + manifest["regularizer"] = "regularizer.pt" + + if epoch is not None: + manifest["epoch"] = epoch + + torch.save(manifest, save_dir / "manifest.pt") diff --git a/sources/neuraloperator/neuralop/utils.py b/sources/neuraloperator/neuralop/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3544f0e15005c978ec33eb292e25ab17dabf536a --- /dev/null +++ b/sources/neuraloperator/neuralop/utils.py @@ -0,0 +1,226 @@ +from typing import List, Optional, Union +from math import prod +from pathlib import Path +import torch + +# Only import wandb and use if installed +wandb_available = False +try: + import wandb + + wandb_available = True +except ModuleNotFoundError: + wandb_available = False + + +def count_model_params(model): + """Returns the total number of parameters of a PyTorch model + + Notes + ----- + One complex number is counted as two parameters (we count real and imaginary parts)' + """ + return sum( + [p.numel() * 2 if p.is_complex() else p.numel() for p in model.parameters()] + ) + + +def count_tensor_params(tensor, dims=None): + """Returns the number of parameters (elements) in a single tensor, optionally, along certain dimensions only + + Parameters + ---------- + tensor : torch.tensor + dims : int list or None, default is None + if not None, the dimensions to consider when counting the number of parameters (elements) + + Notes + ----- + One complex number is counted as two parameters (we count real and imaginary parts)' + """ + if dims is None: + dims = list(tensor.shape) + else: + dims = [tensor.shape[d] for d in dims] + n_params = prod(dims) + if tensor.is_complex(): + return 2 * n_params + return n_params + + +def wandb_login(api_key_file="../config/wandb_api_key.txt", key=None): + if key is None: + key = get_wandb_api_key(api_key_file) + + wandb.login(key=key) + + +def set_wandb_api_key(api_key_file="../config/wandb_api_key.txt"): + import os + + try: + os.environ["WANDB_API_KEY"] + except KeyError: + with open(api_key_file, "r") as f: + key = f.read() + os.environ["WANDB_API_KEY"] = key.strip() + + +def get_wandb_api_key(api_key_file="../config/wandb_api_key.txt"): + import os + + try: + return os.environ["WANDB_API_KEY"] + except KeyError: + with open(api_key_file, "r") as f: + key = f.read() + return key.strip() + + +# Define the function to compute the spectrum +def spectrum_2d(signal, n_observations, normalize=True): + """This function computes the spectrum of a 2D signal using the Fast Fourier Transform (FFT). + + Parameters + ---------- + 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: an integer + 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)``). + Returns + -------- + 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. + """ + T = signal.shape[0] + signal = signal.view(T, n_observations, n_observations) + + if normalize: + signal = torch.fft.fft2(signal, norm="ortho") + else: + signal = torch.fft.rfft2( + signal, s=(n_observations, n_observations), norm="backward" + ) + + # 2d wavenumbers following PyTorch fft convention + k_max = n_observations // 2 + wavenumers = torch.cat( + ( + torch.arange(start=0, end=k_max, step=1), + torch.arange(start=-k_max, end=0, step=1), + ), + 0, + ).repeat(n_observations, 1) + k_x = wavenumers.transpose(0, 1) + k_y = wavenumers + + # Sum wavenumbers + sum_k = torch.sqrt(k_x**2 + k_y**2) + sum_k = sum_k + + # Remove symmetric components from wavenumbers + index = -1.0 * torch.ones((n_observations, n_observations)) + k_max1 = k_max + 1 + index[0:k_max1, 0:k_max1] = sum_k[0:k_max1, 0:k_max1] + + spectrum = torch.zeros((T, n_observations)) + for j in range(1, n_observations + 1): + ind = torch.where(index == j) + spectrum[:, j - 1] = (signal[:, ind[0], ind[1]].abs() ** 2).sum(dim=1) + + spectrum = spectrum.mean(dim=0) + return spectrum + + +Number = Union[float, int] + + +def validate_scaling_factor( + scaling_factor: Union[None, Number, List[Number], List[List[Number]]], + n_dim: int, + n_layers: Optional[int] = None, +) -> Union[None, List[float], List[List[float]]]: + """ + Parameters + ---------- + scaling_factor : None OR float OR list[float] Or list[list[float]] + n_dim : int + n_layers : int or None; defaults to None + If None, return a single list (rather than a list of lists) + with `factor` repeated `dim` times. + """ + if scaling_factor is None: + return None + if isinstance(scaling_factor, (float, int)): + if n_layers is None: + return [float(scaling_factor)] * n_dim + + return [[float(scaling_factor)] * n_dim] * n_layers + + if ( + isinstance(scaling_factor, list) + and len(scaling_factor) > 0 + and all([isinstance(s, (float, int)) for s in scaling_factor]) + ): + if n_layers is None and len(scaling_factor) == n_dim: + # this is a dim-wise scaling + return [float(s) for s in scaling_factor] + return [[float(s)] * n_dim for s in scaling_factor] + + if ( + isinstance(scaling_factor, list) + and len(scaling_factor) > 0 + and all([isinstance(s, (list)) for s in scaling_factor]) + ): + s_sub_pass = True + for s in scaling_factor: + if all([isinstance(s_sub, (int, float)) for s_sub in s]): + pass + else: + s_sub_pass = False + if s_sub_pass: + return scaling_factor + + return None + + +def compute_rank(tensor): + # Compute the matrix rank of a tensor + rank = torch.matrix_rank(tensor) + return rank + + +def compute_stable_rank(tensor): + # Compute the stable rank of a tensor + tensor = tensor.detach() + fro_norm = torch.linalg.norm(tensor, ord="fro") ** 2 + l2_norm = torch.linalg.norm(tensor, ord=2) ** 2 + rank = fro_norm / l2_norm + rank = rank + return rank + + +def compute_explained_variance(frequency_max, s): + # Compute the explained variance based on frequency_max and singular + # values (s) + s_current = s.clone() + s_current[frequency_max:] = 0 + return 1 - torch.var(s - s_current) / torch.var(s) + + +def get_project_root(): + root = Path(__file__).parent.parent + return root diff --git a/sources/neuraloperator/pyproject.toml b/sources/neuraloperator/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..011c818fd8db7538c59f53398931aa7bae1cbb56 --- /dev/null +++ b/sources/neuraloperator/pyproject.toml @@ -0,0 +1,78 @@ +[project] +name = "neuraloperator" +description = "NeuralOperator: Learning in Infinite Dimensions" +authors = [ + {name = "Jean Kossaifi , David Pitt , Nik Kovachki, Zongyi Li", email="david.h.pitt@gmail.com"}, +] +dependencies = [ + "wandb", + "ruamel-yaml", + "zencfg", + "configmypy", + "tensorly", + "tensorly-torch", + "matplotlib", + "numpy>=1.25", + "opt-einsum", + "h5py", + "zencfg>=0.3.0", +] +requires-python = ">=3.9" +readme = "README.rst" +license = {text = "MIT"} + +# Dynamic versioning +dynamic = ["version"] + +# Required config for build system +[build-system] +requires = ["setuptools>=64"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +include = [ + "neuralop", + "neuralop.*", +] + +# Dynamic versioning from neuralop.__init__ +[tool.setuptools.dynamic] +version = {attr = "neuralop.__version__"} + +[project.optional-dependencies] +dev = [ + "pytest", + "flaky", + "black" + +] +doc = [ + "matplotlib", + "myst-nb", + "numpydoc", + "numpy>=1.25", + "sphinx", + "sphinx-gallery", + "sphinx-design", + "setuptools>=40.0,<80", + "tensorly_sphinx_theme", + "torchtnt", + "torch_harmonics==0.7.4" +] +all = [ + "pytest", + "flaky", + "black", + "matplotlib", + "myst-nb", + "numpydoc", + "sphinx", + "sphinx-gallery", + "sphinx-design", + "setuptools>=40.0,<80", + "tensorly_sphinx_theme", + "torchtnt", + "numpy>=1.25", + "scipy", + "torch_harmonics==0.7.4" +] diff --git a/sources/neuraloperator/requirements.txt b/sources/neuraloperator/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..df1478738bdd6c889c78176206ce623d7da5fcf9 --- /dev/null +++ b/sources/neuraloperator/requirements.txt @@ -0,0 +1,11 @@ +wandb +ruamel.yaml +configmypy +zencfg +tensorly +tensorly-torch +torch-harmonics +matplotlib +opt-einsum +h5py +zarr diff --git a/sources/neuraloperator/requirements_dev.txt b/sources/neuraloperator/requirements_dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c89d8e150973c0cf203918fe4c718bc63571e3e --- /dev/null +++ b/sources/neuraloperator/requirements_dev.txt @@ -0,0 +1,3 @@ +black +flaky +pytest \ No newline at end of file diff --git a/sources/neuraloperator/scripts/login_wandb.py b/sources/neuraloperator/scripts/login_wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe5e80dc19eaeec9bcbb42fc9fa0d17713bf820 --- /dev/null +++ b/sources/neuraloperator/scripts/login_wandb.py @@ -0,0 +1,3 @@ +from neuralop.utils import wandb_login + +wandb_login() diff --git a/sources/neuraloperator/scripts/test_from_config.py b/sources/neuraloperator/scripts/test_from_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7f8661a0ad4a5a012692721bb1cc84ec61f822ac --- /dev/null +++ b/sources/neuraloperator/scripts/test_from_config.py @@ -0,0 +1,49 @@ +import torch +import time +from tensorly import tenalg + +tenalg.set_backend("einsum") + +from neuralop import get_model + + +# Read the configuration +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.test_config import TestConfig + + +config = make_config_from_cli(TestConfig) +print(config) +print(config.to_dict()) +config = config.to_dict() + +batch_size = config.data.batch_size +size = config.data.size + +if torch.has_cuda: + device = "cuda" +else: + device = "cpu" + +model = get_model(config) +model = model.to(device) + +in_data = torch.randn(batch_size, 3, size, size).to(device) +print(model.__class__) +print(model) + +t1 = time.time() +out = model(in_data) +t = time.time() - t1 +print(f"Output of size {out.shape} in {t}.") + +loss = out.sum() +loss.backward() + +# Check for unused params +for name, param in model.named_parameters(): + if param.grad is None: + print(f"Usused parameter {name}!") diff --git a/sources/neuraloperator/scripts/train_burgers.py b/sources/neuraloperator/scripts/train_burgers.py new file mode 100644 index 0000000000000000000000000000000000000000..95a3928b51aaec5773b0c1df5ba7d14b5acae797 --- /dev/null +++ b/sources/neuraloperator/scripts/train_burgers.py @@ -0,0 +1,225 @@ +""" +Training script for Burgers equation using standard neural operator training. + +This script trains a neural operator on the 1D time-dependent Burgers equation +using the standard training approach with weighted loss functions and optional +multi-grid patching for improved performance on high-resolution data. +""" + +import sys +import torch +import wandb +from torch.nn.parallel import DistributedDataParallel as DDP +import torch.nn.functional as F + +from neuralop import H1Loss, LpLoss, BurgersEqnLoss, ICLoss, WeightedSumLoss, Trainer, get_model +from neuralop.data.datasets import load_mini_burgers_1dtime +from neuralop.data.transforms.data_processors import MGPatchingDataProcessor +from neuralop.training import setup, AdamW +from neuralop.utils import get_wandb_api_key, count_model_params, get_project_root + + +# Read the configuration +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.burgers_config import Default + + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# Set up WandB logging +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config_name, + config.model.model_arch, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) +else: + wandb_init_args = None +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose: + print("##### CONFIG ######") + print(config) + sys.stdout.flush() + +# Data loading setup +data_path = get_project_root() / config.data.folder +# Load the Burgers dataset with specified parameters +train_loader, test_loaders, data_processor = load_mini_burgers_1dtime( + data_path=data_path, + n_train=config.data.n_train, + batch_size=config.data.batch_size, + n_test=config.data.n_tests[0], + test_batch_size=config.data.test_batch_sizes[0], + temporal_subsample=config.data.get("temporal_subsample", 1), + spatial_subsample=config.data.get("spatial_subsample", 1), +) + +# Model initialization +model = get_model(config) + +# Distributed data parallel setup +if config.distributed.use_distributed: + model = DDP( + model, device_ids=[device.index], output_device=device.index, static_graph=True + ) + +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + + +# Create the loss functions +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) +ic_loss = ICLoss() +equation_loss = BurgersEqnLoss( + method=config.opt.get("pino_method", "fdm"), visc=0.01, loss=F.mse_loss +) + +training_loss = config.opt.training_loss +if not isinstance(training_loss, (tuple, list)): + training_loss = [training_loss] + +losses = [] +weights = [] +for loss in training_loss: + # Append loss + if loss == "l2": + losses.append(l2loss) + elif loss == "h1": + losses.append(h1loss) + elif loss == "equation": + losses.append(equation_loss) + elif loss == "ic": + losses.append(ic_loss) + else: + raise ValueError(f"Training_loss={loss} is not supported.") + + # Append loss weight + if "loss_weights" in config.opt: + weights.append(config.opt.loss_weights.get(loss, 1.0)) + else: + weights.append(1.0) + +train_loss = WeightedSumLoss(losses=losses, weights=weights) +eval_losses = {"h1": h1loss, "l2": l2loss} + +if config.verbose: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + +# only perform multi-grid patching if config patching levels > 0 +if config.patching.levels > 0: + data_processor = MGPatchingDataProcessor( + model=model, + levels=config.patching.levels, + padding_fraction=config.patching.padding, + stitching=config.patching.stitching, + device=device, + in_normalizer=data_processor.in_normalizer, + out_normalizer=data_processor.out_normalizer, + ) + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + mixed_precision=config.opt.mixed_precision, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose, + wandb_log=config.wandb.log, +) + +# Log model parameter count +if is_logger: + n_params = count_model_params(model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log, commit=False) + wandb.watch(model) + + +# Start training process +trainer.train( + train_loader, + test_loaders, + optimizer, + scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish() diff --git a/sources/neuraloperator/scripts/train_burgers_pino.py b/sources/neuraloperator/scripts/train_burgers_pino.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa6a97d11406f16796014893014e6e9f1af8bd7 --- /dev/null +++ b/sources/neuraloperator/scripts/train_burgers_pino.py @@ -0,0 +1,319 @@ +""" +Training script for Burgers equation using Physics-Informed Neural Operator (PINO). + +This script trains a neural operator on the 1D time-dependent Burgers equation +using physics-informed loss functions and advanced loss aggregation methods. +The script supports both Relobralo and SoftAdapt loss aggregation strategies. +""" + +import sys +import torch +import wandb +import torch.nn.functional as F + +from neuralop import H1Loss, LpLoss, BurgersEqnLoss, ICLoss, get_model +from neuralop.data.datasets import load_mini_burgers_1dtime +from neuralop.training import AdamW +from neuralop.utils import get_wandb_api_key, count_model_params, get_project_root +from neuralop.losses.meta_losses import Relobralo, SoftAdapt + +# Read the configuration +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.burgers_pino_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +# Set up WandB logging +if config.wandb.log: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config_name, + config.model.model_arch, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) +else: + wandb_init_args = None + + +# Print configuration details +if config.verbose: + print("##### CONFIG ######") + print(config) + sys.stdout.flush() + +# Data loading +data_path = get_project_root() / config.data.folder +# Load the Burgers dataset with specified parameters +train_loader, test_loaders, data_processor = load_mini_burgers_1dtime( + data_path=data_path, + n_train=config.data.n_train, + batch_size=config.data.batch_size, + n_test=config.data.n_tests[0], + test_batch_size=config.data.test_batch_sizes[0], + temporal_subsample=config.data.get("temporal_subsample", 1), + spatial_subsample=config.data.get("spatial_subsample", 1), +) + +# Create the model +model = get_model(config) +model = model.to(device) + +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +# Create the scheduler +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + +# Create the loss functions +l2_loss = LpLoss(d=2, p=2) +h1_loss = H1Loss(d=2) +ic_loss = ICLoss() +equation_loss = BurgersEqnLoss( + method=config.opt.get("pino_method", "fdm"), visc=0.01, loss=F.mse_loss +) + +loss_map = {"l2": l2_loss, "h1": h1_loss, "ic": ic_loss, "equation": equation_loss} + +training_losses = [loss_map[name] for name in config.opt.training_loss] + +# Loss aggregation strategy setup +if config.opt.loss_aggregator.lower() == "relobralo": + train_loss = Relobralo( + num_losses=len(training_losses), + params=model.parameters(), + alpha=0.5, + beta=0.9, + tau=1.0, + ) +elif config.opt.loss_aggregator.lower() == "softadapt": + train_loss = SoftAdapt( + num_losses=len(training_losses), + params=model.parameters(), + ) +else: + raise ValueError( + f"Unknown loss_aggregator: {config.opt.loss_aggregator}. Use 'relobralo' or 'softadapt'." + ) + +# Evaluation loss functions +eval_losses = {"h1": h1_loss, "l2": l2_loss} + +if config.verbose: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + +# Log model parameter count +if config.verbose: + n_params = count_model_params(model) + print(f"\nn_params: {n_params}") + sys.stdout.flush() +if config.wandb.log: + wandb.log({"n_params": n_params}, commit=False) + wandb.watch(model) + + +# Main training loop +model.train() +for epoch in range(config.opt.n_epochs): + model.train() + train_losses = [] + loss_values = {name: [] for name in config.opt.training_loss} + + # Process training batches + for batch_idx, sample in enumerate(train_loader): + # Move tensors to device + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + optimizer.zero_grad(set_to_none=True) + + # Preprocess data if processor is available + if data_processor is not None: + sample = data_processor.preprocess(sample) + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + # Forward pass + pred = model(**sample) + + # Postprocess model output + if data_processor is not None: + pred, sample = data_processor.postprocess(pred, sample) + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + # Compute individual loss components + loss_vals = {} + for loss_name in config.opt.training_loss: + if loss_name == "equation": + # Physics-informed loss requires input coordinates + loss_val = loss_map[loss_name](pred, x=sample["x"]) + else: + # Standard data losses + loss_val = loss_map[loss_name](pred, sample["y"]) + + loss_vals[loss_name] = loss_val + loss_values[loss_name].append(loss_val.item()) + + # Aggregate losses using adaptive strategy + total_loss, weights = train_loss(loss_vals, step=epoch) + + # Backward pass and optimization step + total_loss.backward() + optimizer.step() + + # Record losses for monitoring + train_losses.append(total_loss.item()) + + # Calculate average losses for this epoch + avg_train_loss = sum(train_losses) / len(train_losses) + avg_losses = {name: sum(vals) / len(vals) for name, vals in loss_values.items()} + + # Print training progress + if config.verbose: + print(f"\nEpoch {epoch+1}/{config.opt.n_epochs}") + print(f"Average Training Loss: {avg_train_loss:.4f}") + print("Individual Training Losses:") + for name, avg_val in avg_losses.items(): + print(f" {name.upper()} Loss: {avg_val:.4f}") + + # Display adaptive loss weights if available + if hasattr(train_loss, "weights"): + print("Loss Weights:") + for i, name in enumerate(config.opt.training_loss): + print(f" {name.upper()} Weight: {weights[i]:.4f}") + sys.stdout.flush() + + # Periodic evaluation on test set + eval_losses_dict = {} + if epoch % config.opt.eval_interval == 0: + model.eval() + + with torch.no_grad(): + for test_name, test_loader in test_loaders.items(): + test_losses = [] + for sample in test_loader: + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + if data_processor is not None: + sample = data_processor.preprocess(sample) + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + pred = model(**sample) + + if data_processor is not None: + pred, sample = data_processor.postprocess(pred, sample) + sample = { + k: v.to(device).float() if torch.is_tensor(v) else v + for k, v in sample.items() + } + + l2_test_loss = l2_loss(pred.float(), sample["y"].float()) + h1_test_loss = h1_loss(pred.float(), sample["y"].float()) + test_losses.append(l2_test_loss.item()) + + avg_test_loss = sum(test_losses) / len(test_losses) + eval_losses_dict[f"{test_name}_loss"] = avg_test_loss + + if config.verbose: + print(f"\nTest {test_name} loss: {avg_test_loss:.4f}") + + # Update learning rate scheduler + if isinstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): + scheduler.step(eval_losses_dict.get("test_loss", avg_train_loss)) + else: + scheduler.step() + + # Log metrics to WandB + if config.wandb.log: + log_dict = { + "train_loss": avg_train_loss, + "learning_rate": optimizer.param_groups[0]["lr"], + } + + # Log individual losses + for name, avg_val in avg_losses.items(): + log_dict[f"train_{name}_loss"] = avg_val + + if hasattr(train_loss, "weights"): + for i, name in enumerate(config.opt.training_loss): + log_dict[f"weight_{name}"] = weights[i] + + if eval_losses_dict: + log_dict.update(eval_losses_dict) + + wandb.log(log_dict) + + # Periodic GPU memory cleanup + if device.type == "cuda" and epoch % 10 == 0: + torch.cuda.empty_cache() + +# Finalize WandB logging +if config.wandb.log: + wandb.finish() diff --git a/sources/neuraloperator/scripts/train_burgers_rno.py b/sources/neuraloperator/scripts/train_burgers_rno.py new file mode 100644 index 0000000000000000000000000000000000000000..13fe9e604729a055b902494c6eb4a43bf11393df --- /dev/null +++ b/sources/neuraloperator/scripts/train_burgers_rno.py @@ -0,0 +1,250 @@ +""" +Training script for Burgers equation using the Recurrent Neural Operator (RNO). + +This script trains an RNO on the 1D time-dependent Burgers equation +using a small in-repo dataset. +""" + +import sys +from pathlib import Path + +import torch +import wandb +import torch.nn as nn + +from zencfg import make_config_from_cli + +# Add project root to sys.path for imports +SCRIPT_DIR = Path(__file__).resolve().parent +PROJECT_ROOT = SCRIPT_DIR.parent +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from config.burgers_rno_config import Default +from neuralop.utils import get_wandb_api_key, count_model_params +from neuralop.training import AdamW, Trainer +from neuralop.losses import LpLoss +from neuralop.models import get_model +from neuralop.data.datasets import load_mini_burgers_1dtime + + +class RNOTimeAdapter(nn.Module): + """Adapter to reconcile dataset batch format with RNO's expected input format. + + The mini_burgers_1dtime dataset returns batches with shape (B, C, T, X), + where the time dimension is at index 2. However, RNO expects the time + dimension at index 1 with shape (B, T, C, X). This adapter performs the + necessary permutation and extracts the final time step prediction. + + This wrapper is necessary because the Trainer expects a standard forward(x, y) + signature that returns predictions matching the target format, whereas the raw + RNO model returns both predictions and hidden states with a different input format. + + Parameters + ---------- + core : nn.Module + The RNO model to wrap. This is the trained RNO that performs the + actual sequence modeling. + + Input + ----- + x : torch.Tensor + Input with shape (B, C, T, X) from the dataset. + + Returns + ------- + torch.Tensor + Prediction of the last time step with shape (B, C, X). + """ + + def __init__(self, core: nn.Module): + super().__init__() + self.core = core + + def forward(self, x, y=None): + # (B, C, T, X) -> (B, T, C, X) + x_rno = x.permute(0, 2, 1, 3).contiguous() + pred = self.core(x_rno) + return pred + + +class LastFrameDataProcessor(nn.Module): + """Processor that extracts the last time frame from targets for single-step supervision. + + The Burgers dataset provides full temporal sequences as targets with shape + (B, C, T, X), but we train the RNO to predict only the final time step. + This processor wraps an existing data_processor and extracts y[:, :, -1, :] + during preprocessing, converting the target to shape (B, C, X) for L2 loss computation. + + Parameters + ---------- + base : nn.Module or object + The underlying data processor to wrap (e.g., DefaultDataProcessor). + This processor's preprocess/postprocess methods are called before/after + extracting the last frame. + """ + + def __init__(self, base): + super().__init__() + self.base = base + self.device = "cpu" + + def to(self, device): + self.device = device + if hasattr(self.base, "to"): + self.base = self.base.to(device) + return self + + def preprocess(self, data_dict, batched=True): + if hasattr(self.base, "preprocess"): + data_dict = self.base.preprocess(data_dict, batched=batched) + # Supervise on last time step only + if torch.is_tensor(data_dict["y"]): + data_dict["y"] = data_dict["y"][:, :, -1, :] + return data_dict + + def postprocess(self, output, data_dict): + if hasattr(self.base, "postprocess"): + return self.base.postprocess(output, data_dict) + return output, data_dict + + +def main(): + config = make_config_from_cli(Default) + config = config.to_dict() + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + # Set up WandB logging + if config.wandb.log: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" for var in [ + config["arch"], + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) + else: + wandb_init_args = None + + # Print configuration details + if config.verbose: + print("##### CONFIG ######") + print(config) + sys.stdout.flush() + + # Data loading + data_path = PROJECT_ROOT / config.data.folder + train_loader, test_loaders, data_processor = load_mini_burgers_1dtime( + data_path=data_path, + n_train=config.data.n_train, + batch_size=config.data.batch_size, + n_test=config.data.n_tests[0], + test_batch_size=config.data.test_batch_sizes[0], + temporal_subsample=config.data.get("temporal_subsample", 1), + spatial_subsample=config.data.get("spatial_subsample", 1), + ) + + # Model instantiation and wrapping + core_model = get_model(config) + model = RNOTimeAdapter(core_model).to(device) + + # Data processor wrapper: convert target to last time step + if data_processor is not None: + data_processor = LastFrameDataProcessor(data_processor).to(device) + + # Optimizer and scheduler + optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, + ) + if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) + elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) + elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) + else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + + # Losses + l2_loss = LpLoss(d=2, p=2) + eval_losses = {"l2": l2_loss} + train_loss = l2_loss + + if config.verbose: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + + # Trainer + trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + device=device, + data_processor=data_processor, + mixed_precision=config.opt.mixed_precision, + wandb_log=config.wandb.log, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose, + ) + + # Log model parameter count + n_params = count_model_params(model) + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + if config.wandb.log: + wandb.log({"n_params": n_params}, commit=False) + wandb.watch(model) + + # Start training + trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, + ) + + if config.wandb.log: + wandb.finish() + + +if __name__ == "__main__": + main() diff --git a/sources/neuraloperator/scripts/train_darcy.py b/sources/neuraloperator/scripts/train_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..3d1106e6b3f9674ff8bce6af9c581fbc7a71887d --- /dev/null +++ b/sources/neuraloperator/scripts/train_darcy.py @@ -0,0 +1,213 @@ +""" +Training script for Darcy flow equation using neural operators. + +This script trains a neural operator on the 2D Darcy flow equation, +which models fluid flow through porous media. The script supports +distributed training and multi-grid patching for high-resolution data. +""" + +from pathlib import Path +import sys + +import torch + +from torch.utils.data import DataLoader, DistributedSampler +import wandb + +from neuralop import H1Loss, LpLoss, Trainer, get_model +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.data.transforms.data_processors import MGPatchingDataProcessor +from neuralop.training import setup, AdamW +from neuralop.mpu.comm import get_local_rank +from neuralop.utils import get_wandb_api_key, count_model_params + + +# Read the configuration +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.darcy_config import Default + + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# Set up WandB logging +wandb_args = None +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config.model.model_arch, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_args) + +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose and is_logger: + print(f"##### CONFIG #####\n") + print(config) + sys.stdout.flush() + +# Load the Darcy flow dataset +data_root = Path(config.data.folder).expanduser() +train_loader, test_loaders, data_processor = load_darcy_flow_small( + data_root=data_root, + n_train=config.data.n_train, + batch_size=config.data.batch_size, + test_resolutions=config.data.test_resolutions, + n_tests=config.data.n_tests, + test_batch_sizes=config.data.test_batch_sizes, + encode_input=False, + encode_output=False, +) +# Model initialization +model = get_model(config) + +# convert dataprocessor to an MGPatchingDataProcessor if patching levels > 0 +if config.patching.levels > 0: + data_processor = MGPatchingDataProcessor( + model=model, + in_normalizer=data_processor.in_normalizer, + out_normalizer=data_processor.out_normalizer, + padding_fraction=config.patching.padding, + stitching=config.patching.stitching, + levels=config.patching.levels, + use_distributed=config.distributed.use_distributed, + device=device, + ) + +# Distributed data parallel setup +# Reconfigure DataLoaders to use a DistributedSampler if in distributed mode +if config.distributed.use_distributed: + train_db = train_loader.dataset + train_sampler = DistributedSampler(train_db, rank=get_local_rank()) + train_loader = DataLoader( + dataset=train_db, batch_size=config.data.batch_size, sampler=train_sampler + ) + for (res, loader), batch_size in zip( + test_loaders.items(), config.data.test_batch_sizes + ): + test_db = loader.dataset + test_sampler = DistributedSampler(test_db, rank=get_local_rank()) + test_loaders[res] = DataLoader( + dataset=test_db, batch_size=batch_size, shuffle=False, sampler=test_sampler + ) +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + + +# Create the losses functions +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) +if config.opt.training_loss == "l2": + train_loss = l2loss +elif config.opt.training_loss == "h1": + train_loss = h1loss +else: + raise ValueError( + f"Got training_loss={config.opt.training_loss} " + f'but expected one of ["l2", "h1"]' + ) +eval_losses = {"h1": h1loss, "l2": l2loss} + +if config.verbose and is_logger: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + device=device, + data_processor=data_processor, + mixed_precision=config.opt.mixed_precision, + wandb_log=config.wandb.log, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose and is_logger, +) + +# Log model parameter count +if is_logger: + n_params = count_model_params(model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log, commit=False) + wandb.watch(model) + +# Start training process +trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish() diff --git a/sources/neuraloperator/scripts/train_fnogno_carcfd.py b/sources/neuraloperator/scripts/train_fnogno_carcfd.py new file mode 100644 index 0000000000000000000000000000000000000000..95bf607ff187e011306795537a3509dddcf6b97b --- /dev/null +++ b/sources/neuraloperator/scripts/train_fnogno_carcfd.py @@ -0,0 +1,243 @@ +""" +Training script for FNOGNO on Car CFD dataset. + +This script trains a Fourier Neural Operator with Graph Neural Operator (FNOGNO) +on computational fluid dynamics data for car pressure prediction. +The model learns to predict pressure fields from geometric inputs. +""" + +import torch +import wandb +import sys +from neuralop.training import setup, AdamW +from neuralop import get_model +from neuralop.utils import get_wandb_api_key +from neuralop.losses.data_losses import LpLoss +from neuralop.training.trainer import Trainer +from neuralop.data.datasets import CarCFDDataset +from neuralop.data.transforms.data_processors import DataProcessor +from copy import deepcopy + +# query points is [sdf_query_resolution] * 3 (taken from config ahmed) +# Read the configuration +config_name = "cfd" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.fnogno_carcfd_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# Model architecture adjustment for query resolution +# If the model's number of modes is greater than the query resolution, +# shrink the model to avoid an ill-posed FNO +if config.data.sdf_query_resolution < config.model.fno_n_modes[0]: + config.model.fno_n_modes = [config.data.sdf_query_resolution] * 3 + +# Set up WandB logging +wandb_init_args = {} +config_name = "car-pressure" +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" for var in [config_name, config.data.sdf_query_resolution] + ) + + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) + +# Load CFD dataset +data_module = CarCFDDataset( + root_dir=config.data.root, + query_res=[config.data.sdf_query_resolution] * 3, + n_train=config.data.n_train, + n_test=config.data.n_test, + download=True, +) + +# Create data loaders +train_loader = data_module.train_loader(batch_size=1, shuffle=True) +test_loader = data_module.test_loader(batch_size=1, shuffle=False) + +# Model initialization +model = get_model(config) + +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got {config.opt.scheduler=}") + + +l2loss = LpLoss(d=2, p=2) + +if config.opt.training_loss == "l2": + train_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.training_loss=}") + +if config.opt.testing_loss == "l2": + test_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.testing_loss=}") + +# Custom data processor for FNOGNO CFD training + + +class CFDDataProcessor(DataProcessor): + """ + Data processor for FNOGNO training on CFD car-pressure dataset. + + This processor handles the conversion of CFD mesh data into the format + expected by the FNOGNO model, including coordinate transformations + and feature extraction from geometric inputs. + """ + + def __init__(self, normalizer, device="cuda"): + super().__init__() + self.normalizer = normalizer + self.device = device + self.model = None + + def preprocess(self, sample): + """ + Convert CFD mesh data into FNOGNO input format. + + Transforms the data dictionary from MeshDataModule's DictDataset + into the form expected by the FNOGNO model. + """ + + in_p = sample["query_points"].squeeze(0).to(self.device) + out_p = sample["centroids"].squeeze(0).to(self.device) + + f = sample["distance"].squeeze(0).to(self.device) + + weights = sample["triangle_areas"].squeeze(0).to(self.device) + + # Output pressure data + truth = sample["press"].squeeze(0).unsqueeze(-1) + + # Take the first 3682 vertices of the output mesh to correspond to pressure + output_vertices = truth.shape[1] + if out_p.shape[0] > output_vertices: + out_p = out_p[:output_vertices, :] + + truth = truth.to(device) + + inward_normals = -sample["triangle_normals"].squeeze(0).to(self.device) + flow_normals = torch.zeros((sample["triangle_areas"].shape[1], 3)).to( + self.device + ) + flow_normals[:, 0] = -1.0 + batch_dict = dict( + in_p=in_p, + out_p=out_p, + f=f, + y=truth, + inward_normals=inward_normals, + flow_normals=flow_normals, + flow_speed=None, + vol_elm=weights, + reference_area=None, + ) + + sample.update(batch_dict) + return sample + + def postprocess(self, out, sample): + """ + Postprocess model output and ground truth data. + + Applies inverse normalization to both predictions and ground truth + when not in training mode. + """ + if not self.training: + out = self.normalizer.inverse_transform(out) + y = self.normalizer.inverse_transform(sample["y"].squeeze(0)) + sample["y"] = y + + return out, sample + + def to(self, device): + self.device = device + self.normalizer = self.normalizer.to(device) + return self + + def wrap(self, model): + self.model = model + + def forward(self, sample): + """ + Complete forward pass through the data processor and model. + """ + sample = self.preprocess(sample) + out = self.model(sample) + out, sample = self.postprocess(out, sample) + return out, sample + + +# Initialize data processor +output_encoder = deepcopy(data_module.normalizers["press"]).to(device) +data_processor = CFDDataProcessor(normalizer=output_encoder, device=device) + +# Trainer setup +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + wandb_log=config.wandb.log, + verbose=is_logger, +) + +# Log additional dataset information +if config.wandb.log: + wandb.log({"time_to_distance": data_module.time_to_distance}, commit=False) + +# Start training process +trainer.train( + train_loader=train_loader, + test_loaders={"": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + training_loss=train_loss_fn, + eval_losses={config.opt.testing_loss: test_loss_fn}, # can add 'drag' : DragLoss + regularizer=None, +) diff --git a/sources/neuraloperator/scripts/train_gino_carcfd.py b/sources/neuraloperator/scripts/train_gino_carcfd.py new file mode 100644 index 0000000000000000000000000000000000000000..b1deb60ea1581ada8a84b5a4bc65272a7d6480c5 --- /dev/null +++ b/sources/neuraloperator/scripts/train_gino_carcfd.py @@ -0,0 +1,234 @@ +""" +Training script for GINO on Car CFD dataset. + +This script trains a Graph Neural Operator (GINO) on computational fluid +dynamics data for car pressure prediction. The model learns to predict +pressure fields from geometric inputs using graph-based representations. +""" + +import torch +import wandb +import sys +from neuralop.training import setup, AdamW +from neuralop import get_model +from neuralop.utils import get_wandb_api_key +from neuralop.losses.data_losses import LpLoss +from neuralop.training.trainer import Trainer +from neuralop.data.datasets import CarCFDDataset +from neuralop.data.transforms.data_processors import DataProcessor +from copy import deepcopy + +# query points is [sdf_query_resolution] * 3 (taken from config ahmed) +# Read the configuration +config_name = "cfd" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.gino_carcfd_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# Model architecture adjustment for query resolution +if config.data.sdf_query_resolution < config.model.fno_n_modes[0]: + config.model.fno_n_modes = [config.data.sdf_query_resolution] * 3 + +# WandB logging configuration +wandb_init_args = {} +config_name = "car-pressure" +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" for var in [config_name, config.data.sdf_query_resolution] + ) + + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) + +# Load CFD dataset +data_module = CarCFDDataset( + root_dir=config.data.root, + query_res=[config.data.sdf_query_resolution] * 3, + n_train=config.data.n_train, + n_test=config.data.n_test, + download=config.data.download, +) + +# Create data loaders +train_loader = data_module.train_loader(batch_size=1, shuffle=True) +test_loader = data_module.test_loader(batch_size=1, shuffle=False) + +# Model initialization +model = get_model(config) + +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got {config.opt.scheduler=}") + + +l2loss = LpLoss(d=2, p=2) + +if config.opt.training_loss == "l2": + train_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.training_loss=}") + +if config.opt.testing_loss == "l2": + test_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.testing_loss=}") + +# Custom data processor for GINO CFD training + + +class GINOCFDDataProcessor(DataProcessor): + """ + Data processor for GINO training on CFD car-pressure dataset. + + This processor handles the conversion of CFD mesh data into the format + expected by the GINO model, including graph construction and + feature extraction from geometric inputs. + """ + + def __init__(self, normalizer, device="cuda"): + super().__init__() + self.normalizer = normalizer + self.device = device + self.model = None + + def preprocess(self, sample): + """ + Convert CFD mesh data into GINO input format. + + Transforms the data dictionary from MeshDataModule's DictDataset + into the form expected by the GINO model. + """ + + # input geometry: just vertices + in_p = sample["vertices"].squeeze(0).to(self.device) + latent_queries = sample["query_points"].squeeze(0).to(self.device) + out_p = sample["vertices"].squeeze(0).to(self.device) + f = sample["distance"].to(self.device) + + # Output pressure data + truth = sample["press"].squeeze(0).unsqueeze(-1) + + # Take the first 3586 vertices of the output mesh to correspond to pressure + # if there are less than 3586 vertices, take the maximum number of truth points + output_vertices = truth.shape[1] + if out_p.shape[0] > output_vertices: + out_p = out_p[:output_vertices, :] + + truth = truth.to(device) + + batch_dict = dict( + input_geom=in_p, + latent_queries=latent_queries, + output_queries=out_p, + latent_features=f, + y=truth, + x=None, + ) + + sample.update(batch_dict) + + return sample + + def postprocess(self, out, sample): + """ + Postprocess model output and ground truth data. + + Applies inverse normalization to both predictions and ground truth + when not in training mode. + """ + if not self.training: + out = self.normalizer.inverse_transform(out) + y = self.normalizer.inverse_transform(sample["y"].squeeze(0)) + sample["y"] = y + + return out, sample + + def to(self, device): + self.device = device + self.normalizer = self.normalizer.to(device) + return self + + def wrap(self, model): + self.model = model + + def forward(self, sample): + """ + Complete forward pass through the data processor and model. + """ + sample = self.preprocess(sample) + out = self.model(sample) + out, sample = self.postprocess(out, sample) + return out, sample + + +# Initialize data processor +output_encoder = deepcopy(data_module.normalizers["press"]).to(device) +data_processor = GINOCFDDataProcessor(normalizer=output_encoder, device=device) + +# Trainer setup +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + wandb_log=config.wandb.log, + verbose=is_logger, +) + +# Log additional dataset information +if config.wandb.log: + wandb.log({"time_to_distance": data_module.time_to_distance}, commit=False) + +# Start training process +trainer.train( + train_loader=train_loader, + test_loaders={"test": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + training_loss=train_loss_fn, + eval_losses={config.opt.testing_loss: test_loss_fn}, + regularizer=None, +) diff --git a/sources/neuraloperator/scripts/train_mhd64.py b/sources/neuraloperator/scripts/train_mhd64.py new file mode 100644 index 0000000000000000000000000000000000000000..672137099999c9a464ec96eafadaaf1d8057b5af --- /dev/null +++ b/sources/neuraloperator/scripts/train_mhd64.py @@ -0,0 +1,223 @@ +""" +Training script for MHD64 dataset using neural operators. + +This script trains a neural operator on the 3D magnetohydrodynamics (MHD) +dataset with 64x64x64 resolution. The model learns to predict the next time step +in the MHD simulation, supporting both next-step prediction and autoregressive +evaluation modes. +""" + +import sys + +from configmypy import ConfigPipeline, YamlConfig, ArgparseConfig +from pathlib import Path +import torch + +from torch.utils.data import DataLoader, DistributedSampler +import wandb + +from neuralop import H1Loss, LpLoss, Trainer, get_model +from neuralop.data.datasets.the_well_dataset import MHD64Dataset +from neuralop.data.transforms.data_processors import MGPatchingDataProcessor +from neuralop.training import setup, AdamW +from neuralop.mpu.comm import get_local_rank +from neuralop.utils import get_wandb_api_key, count_model_params + +# Configuration setup +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.the_well.mhd_64_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# Set up WandB logging +wandb_args = None +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config.model.model_arch, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_args) + +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose and is_logger: + print(f"##### CONFIG #####\n\n{config}\n") + sys.stdout.flush() + +# Load the MHD64 dataset +dataset = MHD64Dataset( + root_dir=Path(config.data.root).expanduser(), + train_task="next_step", + eval_tasks=["next_step", "autoregression"], + first_only=True, +) + +# Print dataset metadata +print(dataset.train_db.metadata.n_steps_per_trajectory) + +# Create data loaders +train_loader = DataLoader(dataset.train_db, batch_size=config.data.batch_size) + +test_loaders = {} +for mode, db in dataset.test_dbs.items(): + test_loaders[mode] = DataLoader(db, batch_size=config.data.test_batch_size) + +# Get data processor from dataset +data_processor = dataset.data_processor +print(data_processor) + +# Model initialization +model = get_model(config) + +# convert dataprocessor to an MGPatchingDataprocessor if patching levels > 0 +if config.patching.levels > 0: + data_processor = MGPatchingDataProcessor( + model=model, + in_normalizer=data_processor.normalizer, + out_normalizer=data_processor.normalizer, + padding_fraction=config.patching.padding, + stitching=config.patching.stitching, + levels=config.patching.levels, + use_distributed=config.distributed.use_distributed, + device=device, + ) + +# Reconfigure DataLoaders to use a DistributedSampler +# if in distributed data parallel mode +"""if config.distributed.use_distributed: + train_sampler = DistributedSampler(dataset.train_db, rank=get_local_rank()) + train_loader = DataLoader(dataset=dataset.train_db, + batch_size=config.data.batch_size, + sampler=train_sampler) + for (res, loader), batch_size in zip(test_loaders.items(), config.data.test_batch_sizes): + + test_db = loader.dataset + test_sampler = DistributedSampler(test_db, rank=get_local_rank()) + test_loaders[res] = DataLoader(dataset=test_db, + batch_size=batch_size, + shuffle=False, + sampler=test_sampler)""" +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + + +# Loss function configuration +l2loss = LpLoss(d=3, p=2) +h1loss = H1Loss(d=3) +if config.opt.training_loss == "l2": + train_loss = l2loss +elif config.opt.training_loss == "h1": + train_loss = h1loss +else: + raise ValueError( + f"Got training_loss={config.opt.training_loss}" + f'but expected one of ["l2", "h1"]' + ) +eval_losses = {"h1": h1loss, "l2": l2loss} + +if config.verbose and is_logger: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + device=device, + data_processor=data_processor, + mixed_precision=config.opt.mixed_precision, + wandb_log=config.wandb.log, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose and is_logger, +) + +# Log model parameter count +if is_logger: + n_params = count_model_params(model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log, commit=False) + wandb.watch(model) + +# Start training process with autoregressive evaluation +trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + eval_modes={"autoregression": "autoregression"}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish() diff --git a/sources/neuraloperator/scripts/train_navier_stokes.py b/sources/neuraloperator/scripts/train_navier_stokes.py new file mode 100644 index 0000000000000000000000000000000000000000..941a056be8be32c4615efca9e232b555d09769ad --- /dev/null +++ b/sources/neuraloperator/scripts/train_navier_stokes.py @@ -0,0 +1,228 @@ +""" +Training script for Navier-Stokes equation using neural operators. + +This script trains a neural operator on the 2D Navier-Stokes equations +for fluid dynamics simulation. The model learns to predict velocity fields +from initial conditions, supporting multiple resolutions and distributed training. +""" + +import sys + +from pathlib import Path +import torch +from torch.utils.data import DataLoader, DistributedSampler +import torch.distributed as dist +import wandb + +from neuralop import H1Loss, LpLoss, Trainer, get_model +from neuralop.data.datasets.navier_stokes import load_navier_stokes_pt +from neuralop.data.transforms.data_processors import MGPatchingDataProcessor +from neuralop.utils import get_wandb_api_key, count_model_params +from neuralop.mpu.comm import get_local_rank +from neuralop.training import setup, AdamW + +# Configuration setup +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.navier_stokes_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# WandB logging configuration +wandb_init_args = None +if config.wandb.log and is_logger: + print(config.wandb.log) + print(config) + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config_name, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + config.model.factorization, + config.model.rank, + config.patching.levels, + config.patching.padding, + ] + ) + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) + +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose: + print(f"##### CONFIG #####\n") + print(config) + +# Data directory setup +data_dir = Path(config.data.folder).expanduser() + +# Load the Navier-Stokes dataset +train_loader, test_loaders, data_processor = load_navier_stokes_pt( + data_root=data_dir, + train_resolution=config.data.train_resolution, + n_train=config.data.n_train, + batch_size=config.data.batch_size, + test_resolutions=config.data.test_resolutions, + n_tests=config.data.n_tests, + test_batch_sizes=config.data.test_batch_sizes, + encode_input=config.data.encode_input, + encode_output=config.data.encode_output, +) + +# Model initialization +model = get_model(config) +model = model.to(device) +# convert dataprocessor to an MGPatchingDataprocessor if patching levels > 0 +if config.patching.levels > 0: + data_processor = MGPatchingDataProcessor( + model=model, + in_normalizer=data_processor.in_normalizer, + out_normalizer=data_processor.out_normalizer, + padding_fraction=config.patching.padding, + stitching=config.patching.stitching, + levels=config.patching.levels, + use_distributed=config.distributed.use_distributed, + ) +data_processor = data_processor.to(device) + +# Distributed data parallel setup +# Reconfigure DataLoaders to use a DistributedSampler if in distributed mode +if config.distributed.use_distributed: + train_db = train_loader.dataset + train_sampler = DistributedSampler(train_db, rank=get_local_rank()) + train_loader = DataLoader( + dataset=train_db, batch_size=config.data.batch_size, sampler=train_sampler + ) + for (res, loader), batch_size in zip( + test_loaders.items(), config.data.test_batch_sizes + ): + test_db = loader.dataset + test_sampler = DistributedSampler(test_db, rank=get_local_rank()) + test_loaders[res] = DataLoader( + dataset=test_db, batch_size=batch_size, shuffle=False, sampler=test_sampler + ) + +# Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + + +# Loss function configuration +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) +if config.opt.training_loss == "l2": + train_loss = l2loss +elif config.opt.training_loss == "h1": + train_loss = h1loss +else: + raise ValueError( + f"Got training_loss={config.opt.training_loss} " + f'but expected one of ["l2", "h1"]' + ) +eval_losses = {"h1": h1loss, "l2": l2loss} + +if config.verbose: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + mixed_precision=config.opt.mixed_precision, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose, + wandb_log=config.wandb.log, +) + +# Log model parameter count +if is_logger: + n_params = count_model_params(model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log, commit=False) + wandb.watch(model) + + +# Start training process +trainer.train( + train_loader, + test_loaders, + optimizer, + scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish() + +# Clean up distributed training +if dist.is_initialized(): + dist.destroy_process_group() diff --git a/sources/neuraloperator/scripts/train_otno_carcfd.py b/sources/neuraloperator/scripts/train_otno_carcfd.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c8d4668a965344a3e433f6b4b7f2af7cc8a2d9 --- /dev/null +++ b/sources/neuraloperator/scripts/train_otno_carcfd.py @@ -0,0 +1,128 @@ +import torch +import wandb +import sys +from neuralop.training import setup, AdamW +from neuralop import get_model +from neuralop.utils import get_wandb_api_key +from neuralop.losses.data_losses import LpLoss +from neuralop.training.trainer import Trainer +from neuralop.data.datasets import CarOTDataset, load_saved_ot, CFDDataProcessor +from copy import deepcopy + +# query points is [sdf_query_resolution] * 3 (taken from config ahmed) +# Read the configuration +from zencfg import make_config_from_cli +import os + +project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, project_root) +from config.otno_carcfd_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +#Set-up distributed communication, if using +device, is_logger = setup(config) + +#Set up WandB logging +wandb_init_args = {} +config_name = "car-pressure-otno" +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" for var in [config_name, config.data.expand_factor] + ) + + wandb_init_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_init_args) + +#Load CFD body data (once the OT dataset is generated, we can use "load_saved_ot", avoiding recomputation) +data_module = CarOTDataset( + root_dir=config.data.root, + n_train=config.data.n_train, + n_test=config.data.n_test, + expand_factor=config.data.expand_factor, + reg=config.data.reg, + device=device, +) + +train_loader = data_module.train_loader(batch_size=1, shuffle=True) +test_loader = data_module.test_loader(batch_size=1, shuffle=False) + +model = get_model(config) + +#Create the optimizer +optimizer = AdamW( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got {config.opt.scheduler=}") + + +l2loss = LpLoss(d=2, p=2) + +if config.opt.training_loss == "l2": + train_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.training_loss=}") + +if config.opt.testing_loss == "l2": + test_loss_fn = l2loss +else: + raise ValueError(f"Got {config.opt.testing_loss=}") + +output_encoder = deepcopy(data_module.normalizers["press"]).to(device) +data_processor = CFDDataProcessor(normalizer=output_encoder, device=device) + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + wandb_log=config.wandb.log, + verbose=is_logger, +) + +if config.wandb.log: + wandb.log({"time_to_distance": data_module.time_to_distance}, commit=False) + +trainer.train( + train_loader=train_loader, + test_loaders={"": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + training_loss=train_loss_fn, + eval_losses={config.opt.testing_loss: test_loss_fn}, + regularizer=None, +) diff --git a/sources/neuraloperator/scripts/train_poisson.py b/sources/neuraloperator/scripts/train_poisson.py new file mode 100644 index 0000000000000000000000000000000000000000..2217f224ded1583a0dd2ada818a72142424833d7 --- /dev/null +++ b/sources/neuraloperator/scripts/train_poisson.py @@ -0,0 +1,273 @@ +""" +Training script for nonlinear Poisson equation using GINO. + +This script trains a Graph Neural Operator (GINO) on the nonlinear Poisson +equation with boundary conditions. The model learns to solve elliptic PDEs +with complex geometries and boundary conditions using graph-based representations. +""" + +import sys + +import torch +import wandb +from torch.nn.parallel import DistributedDataParallel as DDP +import torch.nn.functional as F + +# Set warning filter to show each warning only once +import warnings +warnings.filterwarnings("once", category=UserWarning) + +from neuralop.losses.data_losses import LpLoss, MSELoss +from neuralop.training import Trainer, setup +from neuralop.data.datasets.nonlinear_poisson import load_nonlinear_poisson_pt +from neuralop.losses.equation_losses import PoissonBoundaryLoss, PoissonEqnLoss +from neuralop.losses.meta_losses import WeightedSumLoss +from neuralop.models import get_model +from neuralop.utils import get_wandb_api_key, count_model_params + +# Configuration setup +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.poisson_gino_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# WandB logging configuration +wandb_args = None +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config_name, + config.model.in_gno_radius, + config.model.out_gno_radius, + config.model.gno_weighting_function, + config.model.gno_weight_function_scale, + config.model.fno_n_modes, + config.model.fno_n_layers, + config.data.n_train, + config.data.n_test, + ] + ) + wandb_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_args) + +else: + wandb_init_args = None +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose: + print(f"##### CONFIG #####\n") + print(config) + sys.stdout.flush() + +# Load the nonlinear Poisson dataset +train_loader, test_loader, data_processor = load_nonlinear_poisson_pt( + data_path=config.data.file, + query_res=config.data.query_resolution, + n_train=config.data.n_train, + n_test=config.data.n_test, + n_in=config.data.n_in, + n_out=config.data.n_out, + n_eval=config.data.n_eval, + n_bound=config.data.n_bound, + val_on_same_instance=config.data.single_instance, + train_out_res=config.data.train_out_res, + input_min_sample_points=config.data.input_min, + input_max_sample_points=config.data.input_max, + input_subsample_level=config.data.sample_random_in, + output_subsample_level=config.data.sample_random_out, + return_dict=config.data.return_queries_dict, +) + +# Create test loaders dictionary +test_loaders = {"test": test_loader} + +# Model initialization +model = get_model(config) +model = model.to(device) + +# Distributed data parallel setup +if config.distributed.use_distributed: + model = DDP( + model, device_ids=[device.index], output_device=device.index, static_graph=True + ) + +# Create the optimizer +optimizer = torch.optim.Adam( + model.parameters(), + lr=config.opt.learning_rate, + weight_decay=config.opt.weight_decay, +) + +if config.opt.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.gamma, + patience=config.opt.scheduler_patience, + mode="min", + ) +elif config.opt.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.scheduler_T_max + ) +elif config.opt.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma + ) +else: + raise ValueError(f"Got scheduler={config.opt.scheduler}") + +# Create the losses: MSE and relative L2 +mse_loss = MSELoss() +l2_loss = LpLoss(d=2, p=2) + + +class GINOLoss(object): + """ + Custom loss wrapper for GINO models that handle dictionary outputs. + + This loss function concatenates dictionary outputs from GINO models + before applying the base loss function. + """ + + def __init__(self, base_loss): + super().__init__() + self.base_loss = base_loss + + def __call__(self, out, y, **kwargs): + """ + Apply loss to GINO model outputs. + + Parameters + ---------- + out : dict or torch.Tensor + Model output, either dictionary of field outputs or tensor + y : dict or torch.Tensor + Ground truth, either dictionary of field targets or tensor + **kwargs + Additional arguments passed to base loss + + Returns + ------- + torch.Tensor + Computed loss value + """ + if kwargs: + warnings.warn( + f"GINOLoss.__call__() received unexpected keyword arguments: {list(kwargs.keys())}. " + "These arguments will be ignored.", + UserWarning, + stacklevel=2 + ) + if isinstance(out, dict) and isinstance(y, dict): + y = torch.cat([y[field] for field in out.keys()], dim=1) + out = torch.cat([out[field] for field in out.keys()], dim=1) + + return self.base_loss(out, y, **kwargs) + + +gino_mseloss = GINOLoss(mse_loss) + +training_loss = config.opt.training_loss +if not isinstance(training_loss, (tuple, list)): + training_loss = [training_loss] + +losses = [] +weights = [] + +if "mse" in training_loss: + losses.append(gino_mseloss) + weights.append(config.opt.loss_weights.get("mse", 1.0)) +if "equation" in training_loss: + equation_loss = PoissonEqnLoss( + interior_weight=config.opt.loss_weights.get("interior", 1.0), + boundary_weight=config.opt.loss_weights.get("boundary", 1.0), + diff_method=config.opt.get("pino_method", "autograd"), + ) + losses.append(equation_loss) + weights.append(1) + +if len(losses) == 1: + train_loss = losses[0] +else: + train_loss = WeightedSumLoss(losses=losses, weights=weights) + +eval_losses = {"mse": mse_loss, "relative_l2": l2_loss} + +if config.verbose: + print("\n### MODEL ###\n", model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + +trainer = Trainer( + model=model, + n_epochs=config.opt.n_epochs, + data_processor=data_processor, + device=device, + mixed_precision=config.opt.mixed_precision, + eval_interval=config.opt.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose, + wandb_log=config.wandb.log, +) + +# Log model parameter count +if is_logger: + n_params = count_model_params(model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log) + wandb.watch(model) + +# Start training process +trainer.train( + train_loader, + test_loaders, + optimizer, + scheduler, + regularizer=None, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish() diff --git a/sources/neuraloperator/scripts/train_uqno_darcy.py b/sources/neuraloperator/scripts/train_uqno_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..873c8d0d2ff41aa108c7798cc29dd6fc0f6467f5 --- /dev/null +++ b/sources/neuraloperator/scripts/train_uqno_darcy.py @@ -0,0 +1,773 @@ +""" +Training script for UQNO (Uncertainty Quantification Neural Operator) on Darcy flow. + +This script implements a two-stage training process: +1. Train a base solution model on Darcy flow data +2. Train a residual model to predict uncertainty bounds +3. Calibrate the uncertainty predictions for reliable coverage + +The UQNO approach provides both point predictions and uncertainty estimates +for neural operator predictions on PDEs. +""" + +import sys +import copy +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader +import wandb + +from neuralop import H1Loss, LpLoss, Trainer, get_model +from neuralop.data.datasets.darcy import DarcyDataset +from neuralop.data.datasets.tensor_dataset import TensorDataset +from neuralop.data.transforms.data_processors import DataProcessor, DefaultDataProcessor +from neuralop.data.transforms.normalizers import UnitGaussianNormalizer +from neuralop.losses.data_losses import PointwiseQuantileLoss +from neuralop.models import UQNO +from neuralop.training import setup +from neuralop.utils import get_wandb_api_key, count_model_params + +# Configuration setup +config_name = "default" +from zencfg import make_config_from_cli +import sys + +sys.path.insert(0, "../") +from config.uqno_config import Default + +config = make_config_from_cli(Default) +config = config.to_dict() + +# Distributed training setup, if enabled +device, is_logger = setup(config) + +# WandB logging configuration +wandb_args = None +if config.wandb.log and is_logger: + wandb.login(key=get_wandb_api_key()) + if config.wandb.name: + wandb_name = config.wandb.name + else: + wandb_name = "_".join( + f"{var}" + for var in [ + config.model.model_arch, + config.model.n_layers, + config.model.n_modes, + config.model.hidden_channels, + ] + ) + wandb_args = dict( + config=config, + name=wandb_name, + group=config.wandb.group, + project=config.wandb.project, + entity=config.wandb.entity, + ) + if config.wandb.sweep: + for key in wandb.config.keys(): + config.params[key] = wandb.config[key] + wandb.init(**wandb_args) + +# Make sure we only print information when needed +config.verbose = config.verbose and is_logger + +# Print configuration details +if config.verbose and is_logger and config.opt.solution.n_epochs > 0: + print(f"##### CONFIG #####\n{config}") + sys.stdout.flush() + +# Loading the Darcy flow dataset for training the base model +root_dir = Path(config.data.root).expanduser() +solution_dataset = DarcyDataset( + root_dir=root_dir, + n_train=config.data.n_train_total, + n_tests=[config.data.n_test], + batch_size=config.data.batch_size, + test_batch_sizes=[config.data.test_batch_size], + train_resolution=421, + test_resolutions=[421], + encode_input=config.data.encode_input, + encode_output=config.data.encode_output, +) + +train_db = solution_dataset.train_db + +test_db = solution_dataset.test_dbs[421] +test_loaders = { + 421: DataLoader( + test_db, + shuffle=False, + batch_size=config.data.test_batch_size, + ) +} +data_processor = solution_dataset.data_processor + +# split the training set up into train, residual_train, residual_calibration + +solution_train_db = TensorDataset(**train_db[: config.data.n_train_solution]) +residual_train_db = TensorDataset( + **train_db[ + config.data.n_train_solution : config.data.n_train_solution + + config.data.n_train_residual + ] +) +residual_calib_db = TensorDataset( + **train_db[ + config.data.n_train_solution + + config.data.n_train_residual : config.data.n_train_solution + + config.data.n_train_residual + + config.data.n_calib_residual + ] +) + +data_processor = data_processor.to(device) + +# Base solution model initialization +solution_model = get_model(config) +solution_model = solution_model.to(device) + +# Create the optimizer +optimizer = torch.optim.Adam( + solution_model.parameters(), + lr=config.opt.solution.learning_rate, + weight_decay=config.opt.solution.weight_decay, +) + +if config.opt.solution.scheduler == "ReduceLROnPlateau": + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, + factor=config.opt.solution.gamma, + patience=config.opt.solution.scheduler_patience, + mode="min", + ) +elif config.opt.solution.scheduler == "CosineAnnealingLR": + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=config.opt.solution.scheduler_T_max + ) +elif config.opt.solution.scheduler == "StepLR": + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, + step_size=config.opt.solution.step_size, + gamma=config.opt.solution.gamma, + ) +else: + raise ValueError(f"Got scheduler={config.opt.solution.scheduler}") + + +# Loss function configuration for base model +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) +if config.opt.solution.training_loss == "l2": + train_loss = l2loss +elif config.opt.solution.training_loss == "h1": + train_loss = h1loss +else: + raise ValueError( + f"Got training_loss={config.opt.solution.training_loss}" + f'but expected one of ["l2", "h1"]' + ) +eval_losses = {"h1": h1loss, "l2": l2loss} + +# if not config.load_soln_model: +if config.verbose and is_logger and config.opt.solution.n_epochs > 0: + print("\n### MODEL ###\n", solution_model) + print("\n### OPTIMIZER ###\n", optimizer) + print("\n### SCHEDULER ###\n", scheduler) + print("\n### LOSSES ###") + print(f"\n * Train: {train_loss}") + print(f"\n * Test: {eval_losses}") + print(f"\n### Beginning Training...\n") + sys.stdout.flush() + + +# Log model parameter count +if is_logger: + n_params = count_model_params(solution_model) + + if config.verbose: + print(f"\nn_params: {n_params}") + sys.stdout.flush() + + if config.wandb.log: + to_log = {"n_params": n_params} + if config.n_params_baseline is not None: + to_log["n_params_baseline"] = (config.n_params_baseline,) + to_log["compression_ratio"] = (config.n_params_baseline / n_params,) + to_log["space_savings"] = 1 - (n_params / config.n_params_baseline) + wandb.log(to_log) + + +solution_train_loader = DataLoader( + solution_train_db, + batch_size=config.data.batch_size, + shuffle=True, + num_workers=4, + pin_memory=True, + persistent_workers=False, +) + +trainer = Trainer( + model=solution_model, + n_epochs=config.opt.solution.n_epochs, + device=device, + data_processor=data_processor, + mixed_precision=config.opt.solution.mixed_precision, + wandb_log=config.wandb.log, + eval_interval=config.opt.solution.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose and is_logger, +) +if config.opt.solution.n_epochs > 0: + if config.opt.solution.resume == True: + resume_dir = "./solution_ckpts" + else: + resume_dir = None + + # save the best solution model + + trainer.train( + train_loader=solution_train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, + save_best="421_l2", + save_dir="./solution_ckpts", + resume_from_dir=resume_dir, + ) + +############################# +# UQ Training and Utilities # +############################# + + +def loader_to_residual_db(model, data_processor, loader, device, train_val_split=True): + """ + Convert a dataset of solution data to residual data for uncertainty training. + + This function takes a dataset of input-output pairs (x: a(x), y: u(x)) and + converts it to residual data (x: a(x), y: G(a,x) - u(x)) where G is the + trained solution model. This residual data is used to train the uncertainty + quantification model. + + Parameters + ---------- + model : nn.Module + Trained solution model (frozen) that predicts G(a,x) + data_processor : DataProcessor + Data processor used to train the solution model + loader : DataLoader + Data loader containing solution data to convert to residuals. + Must be drawn from the same distribution as the solution model's + training distribution + device : str or torch.device + Device to run computations on + train_val_split : bool, optional + Whether to split the residual data into training and validation sets, + by default True + + Returns + ------- + tuple + (residual_train_db, residual_val_db, residual_data_processor) + - residual_train_db: Training dataset of residuals + - residual_val_db: Validation dataset of residuals (or None if train_val_split=False) + - residual_data_processor: Data processor for residual data + """ + error_list = [] + x_list = [] + model = model.to(device) + model.eval() + data_processor.eval() # unnormalized y + data_processor = data_processor.to(device) + for idx, sample in enumerate(loader): + sample = data_processor.preprocess(sample) + out = model(**sample) + out, sample = data_processor.postprocess(out, sample) # unnormalize output + + x_list.append(sample["x"].to("cpu")) + error = ( + (out - sample["y"]).detach().to("cpu") + ) # detach, otherwise residual carries gradient of model weight + # error is unnormalized here + error_list.append(error) + + del sample, out + errors = torch.cat(error_list, axis=0) + xs = torch.cat(x_list, axis=0) # check this + + residual_encoder = UnitGaussianNormalizer() + residual_encoder.fit(errors) + + # positional encoding and normalization already applied to X values + residual_data_processor = DefaultDataProcessor( + in_normalizer=None, out_normalizer=residual_encoder + ) + residual_data_processor.train() + + if train_val_split: + val_start = int(0.8 * xs.shape[0]) + + residual_train_db = TensorDataset(x=xs[:val_start], y=errors[:val_start]) + residual_val_db = TensorDataset(x=xs[val_start:], y=errors[val_start:]) + else: + residual_val_db = None + return residual_train_db, residual_val_db, residual_data_processor + + +class UQNODataProcessor(DataProcessor): + """ + Data processor for UQNO (Uncertainty Quantification Neural Operator) training. + + This processor handles the conversion of UQNO model outputs and ground truth + into the format expected by PointwiseQuantileLoss for uncertainty training. + It converts the tuple (G_hat(a,x), E(a,x)) and ground truth G_true(a,x) into: + - y_pred = E(a,x) (uncertainty predictions) + - y_true = abs(G_hat(a,x) - G_true(a,x)) (absolute prediction errors) + + The processor also preserves all necessary transformations for both the + base solution model and residual model inputs/outputs. + """ + + def __init__( + self, + base_data_processor: DataProcessor, + resid_data_processor: DataProcessor, + device: str = "cpu", + ): + """ + Initialize the UQNO data processor. + + Parameters + ---------- + base_data_processor : DataProcessor + Data processor for base solution model input/output transformations + resid_data_processor : DataProcessor + Data processor for residual model input/output transformations + device : str, optional + Device to run computations on ("cpu" or "cuda"), by default "cpu" + """ + super().__init__() + self.base_data_processor = base_data_processor + self.residual_normalizer = resid_data_processor.out_normalizer + + self.device = device + self.scale_factor = None + + def set_scale_factor(self, factor): + """ + Set the uncertainty scaling factor for calibration. + + Parameters + ---------- + factor : torch.Tensor + Scaling factor to apply to uncertainty predictions + """ + self.scale_factor = factor.to(device) + + def wrap(self, model): + """ + Wrap the model with this data processor. + + Parameters + ---------- + model : nn.Module + Model to wrap with this data processor + + Returns + ------- + self + Returns self for method chaining + """ + self.model = model + return self + + def to(self, device): + """ + Move the data processor to the specified device. + + Parameters + ---------- + device : str or torch.device + Device to move the processor to + + Returns + ------- + self + Returns self for method chaining + """ + self.device = device + self.base_data_processor = self.base_data_processor.to(device) + self.residual_normalizer = self.residual_normalizer.to(device) + return self + + def train(self): + """Set the data processor to training mode.""" + self.base_data_processor.train() + + def eval(self): + """Set the data processor to evaluation mode.""" + self.base_data_processor.eval() + + def preprocess(self, *args, **kwargs): + """ + Preprocess input data using the base data processor. + + No additional preprocessing is required - this method simply + wraps the base data processor's preprocessing functionality. + """ + return self.base_data_processor.preprocess(*args, **kwargs) + + def postprocess(self, out, sample): + """ + Postprocess UQNO model outputs and ground truth data. + + This method handles the conversion of UQNO outputs (G_hat, E) and + ground truth into the format expected by PointwiseQuantileLoss. + It also applies inverse normalization to both predictions and ground truth. + """ + self.base_data_processor.eval() + g_hat, pred_uncertainty = out # UQNO returns a tuple + + pred_uncertainty = self.residual_normalizer.inverse_transform(pred_uncertainty) + # this is normalized + + g_hat, sample = self.base_data_processor.postprocess( + g_hat, sample + ) # unnormalize g_hat + + g_true = sample["y"] # this is unnormalized in eval mode + sample["y"] = g_true - g_hat # both unnormalized + + sample.pop("x") # remove x arg to avoid overloading loss args + + if self.scale_factor is not None: + pred_uncertainty = pred_uncertainty * self.scale_factor + return pred_uncertainty, sample + + def forward(self, **sample): + """ + Complete forward pass through the UQNO data processor and model. + + This method combines preprocessing, model forward pass, and postprocessing + for the UQNO training pipeline. + """ + sample = self.preprocess(sample) + out = self.model(**sample) + out, sample = self.postprocess(out, sample) + return out, sample + + +# Load the best-performing solution model from checkpoint +solution_model = solution_model.from_checkpoint( + save_folder="./solution_ckpts", save_name="best_model_815" +) +solution_model = solution_model.to(device) + +# Evaluate the solution model performance +eval_metrics = trainer.evaluate(eval_losses, data_loader=test_loaders[421], epoch=1) +print(f"Eval metrics = {eval_metrics}") + +# Create residual model as a copy of the solution model +residual_model = copy.deepcopy(solution_model) +residual_model = residual_model.to(device) + +# Set up quantile loss for uncertainty training +quantile_loss = PointwiseQuantileLoss(alpha= 1 - config.opt.alpha) + +# Create the quantile model's optimizer +residual_optimizer = torch.optim.Adam( + residual_model.parameters(), + lr=config.opt.residual.learning_rate, + weight_decay=config.opt.residual.weight_decay, +) + + +# Update WandB run name for uncertainty quantification phase +if wandb_args is not None: + uq_wandb_name = "uq_" + wandb_args["name"] + wandb_args["name"] = uq_wandb_name + +# Residual model training phase +# Create data loader for residual training +residual_train_loader_unprocessed = DataLoader( + residual_train_db, + batch_size=1, + shuffle=True, + num_workers=4, + pin_memory=True, + persistent_workers=False, +) + +# Convert solution data to residual data for uncertainty training +# This creates dataset of x: a(x), y: G_hat(a,x) - u(x) +( + processed_residual_train_db, + processed_residual_val_db, + residual_data_processor, +) = loader_to_residual_db( + solution_model, data_processor, residual_train_loader_unprocessed, device +) + +residual_data_processor = residual_data_processor.to(device) + +# Create data loaders for residual model training +residual_train_loader = DataLoader( + processed_residual_train_db, + batch_size=config.data.batch_size, + shuffle=True, + num_workers=4, + pin_memory=True, + persistent_workers=False, +) +residual_val_loader = DataLoader( + processed_residual_val_db, + batch_size=config.data.batch_size, + shuffle=True, + num_workers=4, + pin_memory=True, + persistent_workers=False, +) + +# Configure learning rate scheduler for residual model +if config.opt.residual.scheduler == "ReduceLROnPlateau": + resid_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + residual_optimizer, + factor=config.opt.residual.gamma, + patience=config.opt.residual.scheduler_patience, + mode="min", + ) +elif config.opt.residual.scheduler == "CosineAnnealingLR": + resid_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + residual_optimizer, T_max=config.opt.residual.scheduler_T_max + ) +elif config.opt.residual.scheduler == "StepLR": + resid_scheduler = torch.optim.lr_scheduler.StepLR( + residual_optimizer, + step_size=config.opt.solution.step_size, + gamma=config.opt.solution.gamma, + ) +else: + raise ValueError(f"Got residual scheduler={config.opt.residual.scheduler}") + +# Train the residual model if specified +if config.opt.residual.n_epochs > 0: + # Create trainer for residual model + residual_trainer = Trainer( + model=residual_model, + n_epochs=config.opt.residual.n_epochs, + data_processor=residual_data_processor, + wandb_log=config.wandb.log, + device=device, + mixed_precision=config.opt.residual.mixed_precision, + eval_interval=config.opt.residual.eval_interval, + log_output=config.wandb.log_output, + use_distributed=config.distributed.use_distributed, + verbose=config.verbose and is_logger, + ) + + # Train the residual model for uncertainty quantification + residual_trainer.train( + train_loader=residual_train_loader, + test_loaders={"test": residual_val_loader}, + optimizer=residual_optimizer, + scheduler=resid_scheduler, + regularizer=False, + training_loss=quantile_loss, + eval_losses={"quantile": quantile_loss, "l2": l2loss}, + save_best="test_quantile", + save_dir="./residual_ckpts", + ) + +# Load the best residual model from checkpoint +residual_model = residual_model.from_checkpoint( + save_name="best_model", save_folder="./residual_ckpts" +) +residual_model = residual_model.to(device) + + +# Uncertainty calibration phase +def get_coeff_quantile_idx(alpha, delta, n_samples, n_gridpts): + """ + Compute quantile indices for uncertainty calibration. + + This function calculates the indices needed for uncertainty calibration + based on the desired coverage parameters. It determines both domain-level + and function-level quantile indices for reliable uncertainty estimation. + + Parameters + ---------- + alpha : float + Desired pointwise coverage level (percentage of points in domain) + delta : float + Desired function-level coverage (percentage of functions that satisfy alpha threshold) + n_samples : int + Number of function samples available for calibration + n_gridpts : int + Number of grid points per function (domain discretization) + + Returns + ------- + tuple + (domain_idx, function_idx) + - domain_idx: Index for domain-level quantile selection + - function_idx: Index for function-level quantile selection + + Notes + ----- + The function computes quantile indices based on concentration inequalities. + There is a minimum alpha that can be achieved based on the number of + grid points, samples, and delta. The parameter t is chosen to balance + domain-level and function-level coverage requirements. + """ + lb = np.sqrt(-np.log(delta) / 2 / n_gridpts) + t = (alpha - lb) / 3 + lb # if t too small, will make the in-domain estimate conservative + # too large will make the across-function estimate conservative. so we find a moderate t value + print(f"we set alpha (on domain): {alpha}, t={t}") + percentile = alpha - t + domain_idx = int(np.ceil(percentile * n_gridpts)) + print(f"domain index: {domain_idx}'th largest of {n_gridpts}") + + # get function idx + function_percentile = ( + np.ceil((n_samples + 1) * (delta - np.exp(-2 * n_gridpts * t * t))) / n_samples + ) + function_idx = int(np.ceil(function_percentile * n_samples)) + print(f"function index: {function_idx}'th largest of {n_samples}") + return domain_idx, function_idx + + +# Create the full UQNO model and data processor +uqno = UQNO(base_model=solution_model, residual_model=residual_model) +uqno_data_proc = UQNODataProcessor( + base_data_processor=data_processor, + resid_data_processor=residual_data_processor, + device=device, +) + +# Set to evaluation mode for calibration +uqno_data_proc.eval() + +# Compute calibration ratios for uncertainty scaling +# This creates a list of (true error / uncertainty band) ratios +val_ratio_list = [] +calib_loader = DataLoader(residual_calib_db, shuffle=True, batch_size=1) +with torch.no_grad(): + for idx, sample in enumerate(calib_loader): + sample = uqno_data_proc.preprocess(sample) + out = uqno(sample["x"]) + out, sample = uqno_data_proc.postprocess(out, sample) + ratio = torch.abs(sample["y"]) / out + val_ratio_list.append(ratio.squeeze().to("cpu")) + del sample, out + +# Stack all calibration ratios +val_ratios = torch.stack(val_ratio_list) + +# Reshape for quantile computation +vr_view = val_ratios.view(val_ratios.shape[0], -1) + + +def eval_coverage_bandwidth(test_loader, alpha, device="cuda"): + """ + Evaluate coverage and bandwidth of uncertainty predictions. + + This function computes the percentage of instances that achieve the target + pointwise coverage level and calculates the average uncertainty bandwidth. + It provides metrics for assessing the quality of uncertainty quantification. + + Parameters + ---------- + test_loader : DataLoader + Test data loader for evaluation + alpha : float + Target pointwise coverage level (e.g., 0.05 for 95% coverage) + device : str, optional + Device to run computations on, by default "cuda" + + Returns + ------- + tuple + (mean_interval, in_pred_percentage) + - mean_interval: Average uncertainty bandwidth across test instances + - in_pred_percentage: Percentage of instances achieving target coverage + """ + in_pred_list = [] + avg_interval_list = [] + + with torch.no_grad(): + for _, sample in enumerate(test_loader): + sample = {k: v.to(device) for k, v in sample.items() if torch.is_tensor(v)} + sample = uqno_data_proc.preprocess(sample) + out = uqno(**sample) + uncertainty_pred, sample = uqno_data_proc.postprocess(out, sample) + pointwise_true_err = sample["y"] + + in_pred = ( + (torch.abs(pointwise_true_err) < torch.abs(uncertainty_pred)) + .float() + .squeeze() + ) + avg_interval = ( + torch.abs(uncertainty_pred.squeeze()) + .view(uncertainty_pred.shape[0], -1) + .mean(dim=1) + ) + avg_interval_list.append(avg_interval.to("cpu")) + + in_pred_flattened = in_pred.view(in_pred.shape[0], -1) + in_pred_instancewise = ( + torch.mean(in_pred_flattened, dim=1) >= 1 - alpha + ) # expected shape (batchsize, 1) + in_pred_list.append(in_pred_instancewise.float().to("cpu")) + + in_pred = torch.cat(in_pred_list, axis=0) + intervals = torch.cat(avg_interval_list, axis=0) + mean_interval = torch.mean(intervals, dim=0) + in_pred_percentage = torch.mean(in_pred, dim=0) + print( + f"{in_pred_percentage} of instances satisfy that >= {1-alpha} pts drawn are inside the predicted quantile" + ) + print(f"Mean interval width is {mean_interval}") + return mean_interval, in_pred_percentage + + +# Calibrate uncertainty predictions for different coverage levels +for alpha in [0.02, 0.05, 0.1]: + for delta in [0.02, 0.05, 0.1]: + # get quantile of domain gridpoints and quantile of function samples + darcy_discretization = train_db[0]["x"].shape[-1] ** 2 + domain_idx, function_idx = get_coeff_quantile_idx( + alpha, delta, n_samples=len(calib_loader), n_gridpts=darcy_discretization + ) + + # Compute uncertainty scaling factor based on calibration ratios + val_ratios_pointwise_quantile = torch.topk(val_ratios.view(val_ratios.shape[0], -1),domain_idx+1, dim=1).values[:,-1] + uncertainty_scaling_factor = torch.abs(torch.topk(val_ratios_pointwise_quantile, function_idx+1, dim=0).values[-1]) + print(f"scale factor: {uncertainty_scaling_factor}") + + # Apply scaling factor to uncertainty predictions + uqno_data_proc.set_scale_factor(uncertainty_scaling_factor) + + # Evaluate coverage and bandwidth for this configuration + uqno_data_proc.eval() + print(f"------- for values {alpha=} {delta=} ----------") + interval, percentage = eval_coverage_bandwidth( + test_loader=test_loaders[train_db[0]["x"].shape[-1]], + alpha=alpha, + device=device, + ) + + # Log results to WandB + if config.wandb.log and is_logger: + wandb.log(interval, percentage) + +# Finalize WandB logging +if config.wandb.log and is_logger: + wandb.finish()