nops 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nops/__init__.py ADDED
File without changes
File without changes
File without changes
@@ -0,0 +1,57 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class MLP(nn.Module):
6
+ def __init__(
7
+ self,
8
+ in_features: int,
9
+ out_features: int,
10
+ hidden_features: int,
11
+ num_layers: int = 2,
12
+ activation: nn.Module = nn.GELU(),
13
+ ):
14
+ """
15
+ Multi-Layer Perceptron (MLP) module for DeepONet.
16
+
17
+ Args:
18
+ in_features (int): Number of input features.
19
+ out_features (int): Number of output features.
20
+ hidden_features (int): Number of features in hidden layers.
21
+ num_layers (int): Number of hidden layers. Default: 2.
22
+ activation (nn.Module): Activation function. Default: GELU.
23
+ """
24
+ super().__init__()
25
+ self.in_features = in_features
26
+ self.out_features = out_features
27
+ self.hidden_features = hidden_features
28
+ self.num_layers = num_layers
29
+ self.activation = activation
30
+
31
+ # Build layers
32
+ layers = []
33
+ # Input layer
34
+ layers.append(nn.Linear(in_features, hidden_features))
35
+ layers.append(activation)
36
+
37
+ # Hidden layers
38
+ for _ in range(num_layers - 1):
39
+ layers.append(nn.Linear(hidden_features, hidden_features))
40
+ layers.append(activation)
41
+
42
+ # Output layer
43
+ layers.append(nn.Linear(hidden_features, out_features))
44
+
45
+ self.mlp = nn.Sequential(*layers)
46
+
47
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
48
+ """
49
+ Forward pass of the MLP.
50
+
51
+ Args:
52
+ x (torch.Tensor): Input tensor of shape (*, in_features).
53
+
54
+ Returns:
55
+ torch.Tensor: Output tensor of shape (*, out_features).
56
+ """
57
+ return self.mlp(x)
@@ -0,0 +1,3 @@
1
+ from .deeponet import DeepONet, DeepONetCartesianProd
2
+
3
+ __all__ = ["DeepONet", "DeepONetCartesianProd"]
@@ -0,0 +1,287 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import List, Optional, Union
4
+ from nops.deeponet.layers.mlp import MLP
5
+
6
+
7
+ class DeepONet(nn.Module):
8
+ """
9
+ Deep Operator Network (DeepONet) for learning operators between function spaces.
10
+
11
+ The DeepONet consists of two sub-networks:
12
+ 1. Branch network: Encodes the input function (discretized at sensor locations)
13
+ 2. Trunk network: Encodes the query locations where to evaluate the operator
14
+
15
+ The output is computed as the dot product of the branch and trunk outputs,
16
+ optionally followed by a transformation layer.
17
+
18
+ Args:
19
+ branch_layers (List[int]): Layer sizes for the branch network.
20
+ Format: [input_size, hidden_size, ..., hidden_size, output_size]
21
+ trunk_layers (List[int]): Layer sizes for the trunk network.
22
+ Format: [input_size, hidden_size, ..., hidden_size, output_size]
23
+ activation (nn.Module): Activation function to use. Default: GELU.
24
+ num_outputs (int): Number of output functions. Default: 1.
25
+ use_bias (bool): Whether to use bias in the final transformation. Default: True.
26
+ dropout_rate (float): Dropout rate for regularization. Default: 0.0.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ branch_layers: List[int],
32
+ trunk_layers: List[int],
33
+ activation: nn.Module = nn.GELU(),
34
+ num_outputs: int = 1,
35
+ use_bias: bool = True,
36
+ dropout_rate: float = 0.0,
37
+ ):
38
+ super().__init__()
39
+
40
+ self.branch_layers = branch_layers
41
+ self.trunk_layers = trunk_layers
42
+ self.num_outputs = num_outputs
43
+ self.use_bias = use_bias
44
+
45
+ # Ensure the output dimensions of branch and trunk match
46
+ self.branch_output_size = branch_layers[-1]
47
+ self.trunk_output_size = trunk_layers[-1]
48
+
49
+ if self.branch_output_size != self.trunk_output_size:
50
+ raise ValueError(
51
+ f"Branch output size ({self.branch_output_size}) must match "
52
+ f"trunk output size ({self.trunk_output_size}). "
53
+ f"Consider using projection layers or matching the final layer sizes."
54
+ )
55
+
56
+ self.latent_size = self.branch_output_size
57
+
58
+ # Build branch network
59
+ self.branch_net = self._build_network(branch_layers, activation, dropout_rate)
60
+
61
+ # Build trunk network
62
+ self.trunk_net = self._build_network(trunk_layers, activation, dropout_rate)
63
+
64
+ # Final transformation layer (optional) - only for multiple outputs
65
+ if num_outputs > 1:
66
+ self.output_transform = nn.Linear(
67
+ self.latent_size, num_outputs, bias=use_bias
68
+ )
69
+ else:
70
+ self.output_transform = None
71
+
72
+ # Dropout layer
73
+ self.dropout = nn.Dropout(dropout_rate) if dropout_rate > 0.0 else None
74
+
75
+ def _build_network(
76
+ self, layers: List[int], activation: nn.Module, dropout_rate: float
77
+ ) -> nn.Sequential:
78
+ """Build a neural network with given layer sizes."""
79
+ network_layers = []
80
+
81
+ for i in range(len(layers) - 1):
82
+ network_layers.append(nn.Linear(layers[i], layers[i + 1]))
83
+ if i < len(layers) - 2: # No activation after last layer
84
+ network_layers.append(activation)
85
+ if dropout_rate > 0.0:
86
+ network_layers.append(nn.Dropout(dropout_rate))
87
+
88
+ return nn.Sequential(*network_layers)
89
+
90
+ def forward(
91
+ self, branch_input: torch.Tensor, trunk_input: torch.Tensor
92
+ ) -> torch.Tensor:
93
+ """
94
+ Forward pass of the DeepONet.
95
+
96
+ Args:
97
+ branch_input (torch.Tensor): Input function values at sensor locations.
98
+ Shape: [batch_size, num_sensors, branch_input_dim]
99
+ or [batch_size, branch_input_dim] for single sensor
100
+ trunk_input (torch.Tensor): Query locations where to evaluate the operator.
101
+ Shape: [batch_size, num_query_points, trunk_input_dim]
102
+ or [batch_size, trunk_input_dim] for single query point
103
+
104
+ Returns:
105
+ torch.Tensor: Output values G(u)(y) for each query point.
106
+ Shape: [batch_size, num_query_points, num_outputs]
107
+ """
108
+ # Handle branch input
109
+ if branch_input.dim() == 2:
110
+ # [batch_size, branch_input_dim] -> [batch_size, 1, branch_input_dim]
111
+ branch_input = branch_input.unsqueeze(1)
112
+
113
+ batch_size_branch, num_sensors, branch_input_dim = branch_input.shape
114
+
115
+ # Process branch input through branch network
116
+ # The branch network processes the entire function (all sensor values concatenated)
117
+ branch_flat = branch_input.view(
118
+ batch_size_branch, -1
119
+ ) # [batch_size, num_sensors * branch_input_dim]
120
+ branch_output = self.branch_net(branch_flat) # [batch_size, latent_size]
121
+
122
+ # Handle trunk input
123
+ if trunk_input.dim() == 2:
124
+ # [batch_size, num_query_points] -> [batch_size, num_query_points, 1]
125
+ # Assume trunk_input_dim = 1 for coordinate inputs
126
+ trunk_input = trunk_input.unsqueeze(-1)
127
+
128
+ batch_size_trunk, num_query_points, trunk_input_dim = trunk_input.shape
129
+
130
+ # Ensure batch sizes match
131
+ if batch_size_branch != batch_size_trunk:
132
+ raise ValueError(
133
+ f"Batch size mismatch: branch ({batch_size_branch}) != trunk ({batch_size_trunk})"
134
+ )
135
+
136
+ # Process trunk input through trunk network
137
+ trunk_flat = trunk_input.view(
138
+ -1, trunk_input_dim
139
+ ) # [batch_size * num_query_points, trunk_input_dim]
140
+ trunk_output = self.trunk_net(
141
+ trunk_flat
142
+ ) # [batch_size * num_query_points, latent_size]
143
+ trunk_output = trunk_output.view(
144
+ batch_size_trunk, num_query_points, self.latent_size
145
+ ) # [batch_size, num_query_points, latent_size]
146
+
147
+ # Compute element-wise product and sum (dot product in latent space)
148
+ # branch_output: [batch_size, latent_size]
149
+ # trunk_output: [batch_size, num_query_points, latent_size]
150
+
151
+ # Expand branch_output to match trunk_output dimensions for broadcasting
152
+ branch_expanded = branch_output.unsqueeze(1) # [batch_size, 1, latent_size]
153
+
154
+ # Element-wise multiplication
155
+ product = (
156
+ branch_expanded * trunk_output
157
+ ) # [batch_size, num_query_points, latent_size]
158
+
159
+ # Sum over latent dimension to get dot product
160
+ dot_product = torch.sum(product, dim=-1) # [batch_size, num_query_points]
161
+
162
+ # Apply output transformation if needed
163
+ if self.num_outputs > 1 and self.output_transform is not None:
164
+ # Apply transformation for each query point
165
+ # product: [batch_size, num_query_points, latent_size]
166
+ batch_size, num_query_points, latent_size = product.shape
167
+ product_flat = product.view(
168
+ -1, latent_size
169
+ ) # [batch_size * num_query_points, latent_size]
170
+ output_flat = self.output_transform(
171
+ product_flat
172
+ ) # [batch_size * num_query_points, num_outputs]
173
+ output = output_flat.view(batch_size, num_query_points, self.num_outputs)
174
+ else:
175
+ # For single output without transformation, keep as is
176
+ output = dot_product.unsqueeze(-1) # [batch_size, num_query_points, 1]
177
+
178
+ # Apply dropout if specified
179
+ if self.dropout is not None:
180
+ output = self.dropout(output)
181
+
182
+ return output
183
+
184
+ def encode_branch(self, x: torch.Tensor) -> torch.Tensor:
185
+ """
186
+ Encode input function using the branch network.
187
+
188
+ Args:
189
+ x (torch.Tensor): Input function values at sensor locations.
190
+ Shape: [batch_size, num_sensors, branch_input_dim]
191
+ or [batch_size, branch_input_dim]
192
+
193
+ Returns:
194
+ torch.Tensor: Encoded branch representation.
195
+ Shape: [batch_size, latent_size]
196
+ """
197
+ if x.dim() == 2:
198
+ x = x.unsqueeze(1)
199
+
200
+ batch_size, num_sensors, input_dim = x.shape
201
+ x_flat = x.view(batch_size, -1) # [batch_size, num_sensors * input_dim]
202
+ return self.branch_net(x_flat)
203
+
204
+ def encode_trunk(self, x: torch.Tensor) -> torch.Tensor:
205
+ """
206
+ Encode query locations using the trunk network.
207
+
208
+ Args:
209
+ x (torch.Tensor): Query locations.
210
+ Shape: [batch_size, num_points, trunk_input_dim]
211
+ or [batch_size, trunk_input_dim]
212
+
213
+ Returns:
214
+ torch.Tensor: Encoded trunk representation.
215
+ Shape: [batch_size, num_points, latent_size]
216
+ """
217
+ if x.dim() == 2:
218
+ x = x.unsqueeze(-1)
219
+
220
+ batch_size, num_points, input_dim = x.shape
221
+ x_flat = x.view(-1, input_dim)
222
+ trunk_output = self.trunk_net(x_flat)
223
+ return trunk_output.view(batch_size, num_points, self.latent_size)
224
+
225
+
226
+ class DeepONetCartesianProd(DeepONet):
227
+ """
228
+ DeepONet for Cartesian product formatted data.
229
+
230
+ This variant expects inputs where:
231
+ - branch_input: [batch_size, branch_input_dim] (same for all trunk points)
232
+ - trunk_input: [batch_size * num_trunk_points, trunk_input_dim]
233
+
234
+ and produces output of shape [batch_size, num_trunk_points, num_outputs].
235
+ """
236
+
237
+ def forward(
238
+ self, branch_input: torch.Tensor, trunk_input: torch.Tensor
239
+ ) -> torch.Tensor:
240
+ """
241
+ Forward pass for Cartesian product formatted data.
242
+
243
+ Args:
244
+ branch_input (torch.Tensor): Input function values.
245
+ Shape: [batch_size, branch_input_dim]
246
+ trunk_input (torch.Tensor): Query locations.
247
+ Shape: [batch_size * num_trunk_points, trunk_input_dim]
248
+
249
+ Returns:
250
+ torch.Tensor: Output values.
251
+ Shape: [batch_size, num_trunk_points, num_outputs]
252
+ """
253
+ batch_size = branch_input.shape[0]
254
+
255
+ # Process branch input (same for all trunk points)
256
+ branch_output = self.branch_net(branch_input) # [batch_size, latent_size]
257
+
258
+ # Process trunk input
259
+ trunk_output = self.trunk_net(
260
+ trunk_input
261
+ ) # [batch_size * num_trunk_points, latent_size]
262
+ trunk_output = trunk_output.view(
263
+ batch_size, -1, self.latent_size
264
+ ) # [batch_size, num_trunk_points, latent_size]
265
+
266
+ # Compute dot product for each trunk point
267
+ # branch_output: [batch_size, latent_size] -> [batch_size, 1, latent_size]
268
+ # trunk_output: [batch_size, num_trunk_points, latent_size]
269
+ branch_expanded = branch_output.unsqueeze(1)
270
+ product = (
271
+ branch_expanded * trunk_output
272
+ ) # [batch_size, num_trunk_points, latent_size]
273
+ dot_product = torch.sum(product, dim=-1) # [batch_size, num_trunk_points]
274
+
275
+ # Apply output transformation
276
+ if self.num_outputs > 1 or self.output_transform is not None:
277
+ output = self.output_transform(
278
+ dot_product.unsqueeze(-1)
279
+ ) # [batch_size, num_trunk_points, num_outputs]
280
+ else:
281
+ output = dot_product.unsqueeze(-1) # [batch_size, num_trunk_points, 1]
282
+
283
+ # Apply dropout if specified
284
+ if self.dropout is not None:
285
+ output = self.dropout(output)
286
+
287
+ return output
@@ -0,0 +1,11 @@
1
+ from .mlp import MLP
2
+ from .ffn import FeedForwardNet
3
+ from .fno_block import FourierBlock
4
+ from .spectral_convolution import SpectralConvolution
5
+
6
+ __all__ = [
7
+ "MLP",
8
+ "FeedForwardNet",
9
+ "FourierBlock",
10
+ "SpectralConvolution"
11
+ ]
nops/fno/layers/ffn.py ADDED
@@ -0,0 +1,41 @@
1
+ from typing import Literal
2
+
3
+ from torch import nn
4
+
5
+ class FeedForwardNet(nn.Module):
6
+ """
7
+
8
+ FeedForwardNet is a simple feed-forward neural network with two hidden layers.
9
+ It supports configurable hidden layer sizes, dropout, and choice of non-linearity.
10
+
11
+ Args:
12
+ input_dim (int): Dimension of the input features.
13
+ hidden1 (int): Number of units in the first hidden layer. Default is 128.
14
+ hidden2 (int): Number of units in the second hidden layer. Default is 64.
15
+ output_dim (int): Dimension of the output features. Default is 1.
16
+ dropout (float): Dropout rate applied after each hidden layer. Default is 0.1.
17
+ non_linearity (str): Type of non-linearity to use ('relu' or 'gelu'). Default is 'relu'.
18
+ """
19
+ def __init__(
20
+ self,
21
+ input_dim: int,
22
+ hidden1: int = 128,
23
+ hidden2: int = 64,
24
+ output_dim: int = 1,
25
+ dropout: float = 0.1,
26
+ non_linearity: Literal['relu', 'gelu'] = 'relu'
27
+ ):
28
+ super().__init__()
29
+
30
+ self.model = nn.Sequential(
31
+ nn.Linear(input_dim, hidden1),
32
+ nn.ReLU() if non_linearity == 'relu' else nn.GELU(),
33
+ nn.Dropout(dropout),
34
+ nn.Linear(hidden1, hidden2),
35
+ nn.ReLU() if non_linearity == 'relu' else nn.GELU(),
36
+ nn.Dropout(dropout),
37
+ nn.Linear(hidden2, output_dim)
38
+ )
39
+
40
+ def forward(self, x):
41
+ return self.model(x)
@@ -0,0 +1,121 @@
1
+ from typing import Literal, List
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from .mlp import MLP
7
+ from .ffn import FeedForwardNet
8
+ from .spectral_convolution import SpectralConvolution
9
+
10
+ class FourierBlock(nn.Module):
11
+ """
12
+ # Fourier block.
13
+
14
+ This block consists of three layers:
15
+ 1. Fourier layer: SpectralConvolution
16
+ 2. MLP layer: MLP
17
+ 3. Convolution layer: Convolution
18
+
19
+ """
20
+ def __init__(
21
+ self,
22
+ modes: List[int],
23
+ in_channels: int,
24
+ out_channels: int,
25
+ hidden_size: int | None = None,
26
+ activation: nn.Module = nn.GELU(),
27
+ mid_net_type: Literal['mlp', 'ffn'] = 'mlp',
28
+ bias: bool = False
29
+ ) -> None:
30
+ """
31
+ Parameters:
32
+ -----------
33
+ modes: List[int] or int (Required)
34
+ Number of Fourier modes to use in the Fourier layer (SpectralConvolution). Example: [1, 2, 3] or 4
35
+ in_channels: int (Required)
36
+ Number of input channels
37
+ out_channels: int (Required)
38
+ Number of output channels
39
+ hidden_size: int (Optional)
40
+ Number of hidden units in the MLP layer
41
+ activation: nn.Module (Optional)
42
+ Activation function to use in the MLP layer. Default: nn.GELU()
43
+ bias: bool (Optional)
44
+ Whether to add bias to the output. Default: False
45
+ """
46
+ super().__init__()
47
+ self.in_channels = in_channels
48
+ self.out_channels = out_channels
49
+ self.hidden_size = hidden_size
50
+ self.activation = activation
51
+ self.modes = modes
52
+ self.dim = len(self.modes)
53
+ self.bias = bias
54
+
55
+ # Fourier layer (SpectralConvolution)
56
+ self.fourier = SpectralConvolution(in_channels, out_channels, modes, factorization='dense')
57
+
58
+ # MLP layer
59
+ if self.hidden_size is not None:
60
+ if mid_net_type == 'mlp':
61
+ self.mlp = MLP(len(self.modes), in_channels, out_channels, self.hidden_size, activation)
62
+ elif mid_net_type == 'ffn':
63
+ self.mlp = FeedForwardNet(
64
+ input_dim=in_channels,
65
+ hidden1=self.hidden_size,
66
+ hidden2=self.hidden_size,
67
+ output_dim=out_channels,
68
+ dropout=0.0,
69
+ non_linearity='gelu'
70
+ )
71
+ else:
72
+ raise NotImplementedError(f"Mid network type '{mid_net_type}' is not implemented. Choose either 'mlp' or 'ffn'.")
73
+
74
+ # Convolution layer
75
+ if self.dim == 2:
76
+ self.conv = nn.Conv2d(in_channels, out_channels, 3, padding=1)
77
+ elif self.dim == 3:
78
+ self.conv = nn.Conv3d(in_channels, out_channels, 3, padding=1)
79
+ else:
80
+ self.conv = nn.Conv1d(in_channels, out_channels, 3, padding=1)
81
+
82
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
83
+ """
84
+ Parameters:
85
+ ----------
86
+ x: torch.Tensor
87
+ Input tensor of shape [batch, channels, *sizes]
88
+
89
+ Returns:
90
+ -------
91
+ x: torch.Tensor
92
+ Output tensor of shape [batch, channels, *sizes]
93
+ """
94
+ assert x.size(1) == self.in_channels, f"Input channels must be {self.in_channels} but got {x.size(1)} channels instead."
95
+ sizes = x.size()
96
+
97
+ if self.bias:
98
+ bias = x
99
+
100
+ # Fourier layer
101
+ x_ft = self.fourier(x)
102
+
103
+ # MLP layer
104
+ if self.hidden_size is not None:
105
+ x_mlp = self.mlp(x)
106
+
107
+ # Convolution layer
108
+ if self.dim == 2 or self.dim == 3:
109
+ x_conv = self.conv(x)
110
+ else:
111
+ x_conv = self.conv(x.reshape(sizes[0], self.in_channels, -1)).reshape(*sizes)
112
+
113
+ # Add
114
+ x = x_ft + x_conv
115
+ if self.hidden_size is not None:
116
+ x = x + x_mlp
117
+ if self.bias:
118
+ x = x + bias
119
+ # Activation
120
+ x = self.activation(x)
121
+ return x
nops/fno/layers/mlp.py ADDED
@@ -0,0 +1,56 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class MLP(nn.Module):
6
+ def __init__(
7
+ self,
8
+ dim: int,
9
+ in_channels: int,
10
+ out_channels: int,
11
+ mid_channels: int,
12
+ activation: nn.Module = nn.GELU(),
13
+ ):
14
+ """
15
+ Multi-Layer Perceptron (MLP) module.
16
+
17
+ Args:
18
+ dim (int): The dimensionality of the input data. Can be 1, 2, or 3.
19
+ in_channels (int): Number of input channels.
20
+ out_channels (int): Number of output channels.
21
+ mid_channels (int): Number of channels in the intermediate layer.
22
+ activation (torch.nn.Module, optional): Activation function to be applied after the first convolutional layer.
23
+ Defaults to `torch.nn.GELU()`.
24
+
25
+ """
26
+ super().__init__()
27
+ self.dim = dim
28
+ self.in_channels = in_channels
29
+ self.out_channels = out_channels
30
+ self.mid_channels = mid_channels
31
+ self.activation = activation
32
+ if self.dim == 2:
33
+ self.mlp1 = nn.Conv2d(self.in_channels, self.mid_channels, 1)
34
+ self.mlp2 = nn.Conv2d(self.mid_channels, self.out_channels, 1)
35
+ elif self.dim == 3:
36
+ self.mlp1 = nn.Conv3d(self.in_channels, self.mid_channels, 1)
37
+ self.mlp2 = nn.Conv3d(self.mid_channels, self.out_channels, 1)
38
+ else:
39
+ self.mlp1 = nn.Conv1d(self.in_channels, self.mid_channels, 1)
40
+ self.mlp2 = nn.Conv1d(self.mid_channels, self.out_channels, 1)
41
+
42
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
43
+ """
44
+ Forward pass of the MLP module.
45
+
46
+ Args:
47
+ x (torch.Tensor): Input tensor of shape (batch_size, channels, *spatial_dims).
48
+
49
+ Returns:
50
+ torch.Tensor: Output tensor of shape (batch_size, out_channels, *spatial_dims).
51
+
52
+ """
53
+ x = self.mlp1(x)
54
+ x = self.activation(x)
55
+ x = self.mlp2(x)
56
+ return x