wuff-mann commited on
Commit
7cbb55b
·
verified ·
1 Parent(s): a1a1fbf

Upload CIDM Foundation A1-R1-R2 FIX1 experimental results and data (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d2_c25.npz +3 -0
  2. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d3_c25.npz +3 -0
  3. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d4_c25.npz +3 -0
  4. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d5_c25.npz +3 -0
  5. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d6_c25.npz +3 -0
  6. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d7_c25.npz +3 -0
  7. sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d8_c25.npz +3 -0
  8. sources/neuraloperator/neuralop/layers/fno_block.py +498 -0
  9. sources/neuraloperator/neuralop/layers/fourier_continuation.py +453 -0
  10. sources/neuraloperator/neuralop/layers/gno_block.py +250 -0
  11. sources/neuraloperator/neuralop/layers/gno_weighting_functions.py +93 -0
  12. sources/neuraloperator/neuralop/layers/integral_transform.py +227 -0
  13. sources/neuraloperator/neuralop/layers/legacy_spectral_convolution.py +742 -0
  14. sources/neuraloperator/neuralop/layers/local_no_block.py +587 -0
  15. sources/neuraloperator/neuralop/layers/neighbor_search.py +119 -0
  16. sources/neuraloperator/neuralop/layers/normalization_layers.py +165 -0
  17. sources/neuraloperator/neuralop/layers/padding.py +133 -0
  18. sources/neuraloperator/neuralop/layers/resample.py +102 -0
  19. sources/neuraloperator/neuralop/layers/rno_block.py +432 -0
  20. sources/neuraloperator/neuralop/layers/segment_csr.py +98 -0
  21. sources/neuraloperator/neuralop/layers/skip_connections.py +130 -0
  22. sources/neuraloperator/neuralop/layers/spectral_convolution.py +570 -0
  23. sources/neuraloperator/neuralop/layers/spectral_projection.py +102 -0
  24. sources/neuraloperator/neuralop/layers/spherical_convolution.py +484 -0
  25. sources/neuraloperator/neuralop/layers/tests/__init__.py +0 -0
  26. sources/neuraloperator/neuralop/layers/tests/test_attention_layer.py +32 -0
  27. sources/neuraloperator/neuralop/layers/tests/test_coda_layer.py +57 -0
  28. sources/neuraloperator/neuralop/layers/tests/test_disco_conv.py +98 -0
  29. sources/neuraloperator/neuralop/layers/tests/test_finite_difference_conv.py +67 -0
  30. sources/neuraloperator/neuralop/layers/tests/test_fno_block.py +250 -0
  31. sources/neuraloperator/neuralop/layers/tests/test_fourier_continuation.py +135 -0
  32. sources/neuraloperator/neuralop/layers/tests/test_gno_block.py +110 -0
  33. sources/neuraloperator/neuralop/layers/tests/test_grid_embeddings.py +42 -0
  34. sources/neuraloperator/neuralop/layers/tests/test_legacy_spectral_convolution.py +228 -0
  35. sources/neuraloperator/neuralop/layers/tests/test_local_no_block.py +194 -0
  36. sources/neuraloperator/neuralop/layers/tests/test_neighbor_search.py +55 -0
  37. sources/neuraloperator/neuralop/layers/tests/test_padding.py +17 -0
  38. sources/neuraloperator/neuralop/layers/tests/test_resample.py +24 -0
  39. sources/neuraloperator/neuralop/layers/tests/test_rno_block.py +252 -0
  40. sources/neuraloperator/neuralop/layers/tests/test_segment_csr.py +46 -0
  41. sources/neuraloperator/neuralop/layers/tests/test_sin_embeddings.py +110 -0
  42. sources/neuraloperator/neuralop/layers/tests/test_spectral_convolution.py +115 -0
  43. sources/neuraloperator/neuralop/layers/tests/test_spectral_projection.py +36 -0
  44. sources/neuraloperator/neuralop/layers/tests/test_spherical_convolution.py +108 -0
  45. sources/neuraloperator/neuralop/losses/__init__.py +10 -0
  46. sources/neuraloperator/neuralop/losses/__pycache__/__init__.cpython-313.pyc +0 -0
  47. sources/neuraloperator/neuralop/losses/__pycache__/data_losses.cpython-313.pyc +0 -0
  48. sources/neuraloperator/neuralop/losses/__pycache__/differentiation.cpython-313.pyc +0 -0
  49. sources/neuraloperator/neuralop/losses/__pycache__/equation_losses.cpython-313.pyc +0 -0
  50. sources/neuraloperator/neuralop/losses/__pycache__/meta_losses.cpython-313.pyc +0 -0
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d2_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33a0ee1bb8a6a6b2229cca47d78d6dcafb189fec2c56fce1f9f5d768c52229b8
3
+ size 1302
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d3_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acb6b88051508ff82584b4d33726084120b44f0f705be6ef883120a3795e5ecb
3
+ size 1702
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d4_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04da0d0714d27808b9cdefcada5290238b72a8e98c9f69442f7004ebe26a4c1f
3
+ size 2102
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d5_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a60ec4ef444634164b236f68c0ddf57c566a362c774d4989a9f137241cb44786
3
+ size 2502
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d6_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a98f20321763ffd92d5d1a6e28b9db12bf6a804848448727763f93c3cf39b306
3
+ size 2902
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d7_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c73487f13a2935f8d2749a9edaf9bc99a081510fc1b5aa93c3bb5b92234a694e
3
+ size 3302
sources/neuraloperator/neuralop/layers/fcgram_matrices/FCGram_data_d8_c25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7911eae1f4def9aea17937a0925749ef2743c75b9eff81e7f01fc0fac6586db3
3
+ size 3702
sources/neuraloperator/neuralop/layers/fno_block.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ import torch.nn.functional as F
6
+
7
+ from .channel_mlp import ChannelMLP
8
+ from .complex import CGELU, ctanh, ComplexValued
9
+ from .normalization_layers import AdaIN, InstanceNorm, BatchNorm
10
+ from .skip_connections import skip_connection
11
+ from .spectral_convolution import SpectralConv
12
+ from ..utils import validate_scaling_factor
13
+
14
+
15
+ Number = Union[int, float]
16
+
17
+
18
+ def _make_conv_bias(in_channels, out_channels, n_dim, kernel_size):
19
+ """Create the local convolutional bias term used alongside SpectralConv."""
20
+ if kernel_size < 1:
21
+ raise ValueError(f"conv_bias_kernel must be >= 1, got {kernel_size}")
22
+
23
+ if kernel_size == 1:
24
+ return skip_connection(
25
+ in_channels,
26
+ out_channels,
27
+ skip_type="linear",
28
+ n_dim=n_dim,
29
+ )
30
+
31
+ if n_dim > 3:
32
+ raise NotImplementedError(
33
+ "conv_bias_kernel > 1 is only implemented for 1D, 2D, and 3D FNO blocks."
34
+ )
35
+
36
+ conv_module = getattr(nn, f"Conv{n_dim}d")
37
+ return conv_module(
38
+ in_channels,
39
+ out_channels,
40
+ kernel_size=kernel_size,
41
+ padding="same",
42
+ bias=False,
43
+ )
44
+
45
+
46
+ class FNOBlocks(nn.Module):
47
+ """FNOBlocks implements a sequence of Fourier layers.
48
+
49
+ The Fourier layers are first described in [1]_, and the exact implementation details
50
+ of the Fourier layer architecture are discussed in [2]_.
51
+
52
+ Parameters
53
+ ----------
54
+ in_channels : int
55
+ Number of input channels to Fourier layers
56
+ out_channels : int
57
+ Number of output channels after Fourier layers
58
+ n_modes : int or List[int]
59
+ Number of modes to keep along each dimension in frequency space.
60
+ Can either be specified as an int (for all dimensions) or an iterable
61
+ with one number per dimension
62
+ resolution_scaling_factor : Optional[Union[Number, List[Number]]], optional
63
+ Factor by which to scale outputs for super-resolution, by default None
64
+ n_layers : int, optional
65
+ Number of Fourier layers to apply in sequence, by default 1
66
+ max_n_modes : int or List[int], optional
67
+ Maximum number of modes to keep along each dimension, by default None
68
+ fno_block_precision : str, optional
69
+ Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full"
70
+ use_channel_mlp : bool, optional
71
+ Whether to use an MLP layer after each FNO block, by default True
72
+ channel_mlp_dropout : float, optional
73
+ Dropout parameter for self.channel_mlp, by default 0
74
+ channel_mlp_expansion : float, optional
75
+ Expansion parameter for self.channel_mlp, by default 0.5
76
+ non_linearity : torch.nn.F module, optional
77
+ Nonlinear activation function to use between layers, by default F.gelu
78
+ stabilizer : Literal["tanh"], optional
79
+ Stabilizing module to use between certain layers. Options: "tanh", None, by default None
80
+ norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional
81
+ Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None
82
+ norm_groups : int, optional
83
+ Number of groups for GroupNorm, by default 1
84
+ ada_in_features : int, optional
85
+ Number of features for adaptive instance norm above, by default None
86
+ preactivation : bool, optional
87
+ Whether to call forward pass with pre-activation, by default False
88
+ If True, call nonlinear activation and norm before Fourier convolution
89
+ If False, call activation and norms after Fourier convolutions
90
+ fno_skip : str, optional
91
+ Module to use for FNO skip connections. Options: "linear", "soft-gating", "identity", None, by default "linear"
92
+ If None, no skip connection is added. See layers.skip_connections for more details
93
+ conv_bias_kernel : int, optional
94
+ Kernel size for the local convolutional bias term used when ``fno_skip="linear"``.
95
+ ``1`` preserves the default pointwise bias term, while larger kernels add a
96
+ local convolution alongside the global spectral convolution. Default: 1
97
+ channel_mlp_skip : str, optional
98
+ Module to use for ChannelMLP skip connections. Options: "linear", "soft-gating", "identity", None, by default "soft-gating"
99
+ If None, no skip connection is added. See layers.skip_connections for more details
100
+
101
+ Other Parameters
102
+ ----------------
103
+ complex_data : bool, optional
104
+ Whether the FNO's data takes on complex values in space, by default False
105
+ separable : bool, optional
106
+ Separable parameter for SpectralConv, by default False
107
+ factorization : str, optional
108
+ Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None
109
+ rank : float, optional
110
+ Rank parameter for SpectralConv, by default 1.0
111
+ conv_module : BaseConv, optional
112
+ Module to use for convolutions in FNO block, by default SpectralConv
113
+ joint_factorization : bool, optional
114
+ Whether to factorize all spectralConv weights as one tensor, by default False
115
+ fixed_rank_modes : bool, optional
116
+ Fixed_rank_modes parameter for SpectralConv, by default False
117
+ implementation : str, optional
118
+ Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized"
119
+ decomposition_kwargs : dict, optional
120
+ Kwargs for tensor decomposition in SpectralConv, by default dict()
121
+ enforce_hermitian_symmetry : bool, optional
122
+ Whether to enforce Hermitian symmetry conditions when performing inverse FFT
123
+ for real-valued data. Only used when ``conv_module`` is :class:`SpectralConv`
124
+ or a subclass; ignored otherwise. When True, explicitly enforces that the 0th
125
+ frequency and Nyquist frequency are real-valued before calling irfft. When False,
126
+ relies on cuFFT's irfftn to handle symmetry automatically, which may fail on
127
+ certain GPUs or input sizes, causing line artifacts. By default True.
128
+
129
+ References
130
+ ----------
131
+ .. [1] Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential
132
+ Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895.
133
+ .. [2] Kossaifi, J., Kovachki, N., Azizzadenesheli, K., Anandkumar, A. "Multi-Grid
134
+ Tensorized Fourier Neural Operator for High-Resolution PDEs" (2024).
135
+ TMLR 2024, https://openreview.net/pdf?id=AWiDlO63bH.
136
+ """
137
+
138
+ def __init__(
139
+ self,
140
+ in_channels,
141
+ out_channels,
142
+ n_modes,
143
+ resolution_scaling_factor=None,
144
+ n_layers=1,
145
+ max_n_modes=None,
146
+ fno_block_precision="full",
147
+ use_channel_mlp=True,
148
+ channel_mlp_dropout=0,
149
+ channel_mlp_expansion=0.5,
150
+ non_linearity=F.gelu,
151
+ stabilizer=None,
152
+ norm=None,
153
+ norm_groups=1,
154
+ ada_in_features=None,
155
+ preactivation=False,
156
+ fno_skip="linear",
157
+ conv_bias_kernel=1,
158
+ channel_mlp_skip="soft-gating",
159
+ complex_data=False,
160
+ separable=False,
161
+ factorization=None,
162
+ rank=1.0,
163
+ conv_module=SpectralConv,
164
+ fixed_rank_modes=False,
165
+ implementation="factorized",
166
+ decomposition_kwargs=dict(),
167
+ enforce_hermitian_symmetry=True,
168
+ ):
169
+ super().__init__()
170
+ if isinstance(n_modes, int):
171
+ n_modes = [n_modes]
172
+ self._n_modes = n_modes
173
+ self.n_dim = len(n_modes)
174
+
175
+ self.resolution_scaling_factor: Union[
176
+ None, List[List[float]]
177
+ ] = validate_scaling_factor(resolution_scaling_factor, self.n_dim, n_layers)
178
+
179
+ self.max_n_modes = max_n_modes
180
+ self.fno_block_precision = fno_block_precision
181
+ self.in_channels = in_channels
182
+ self.out_channels = out_channels
183
+ self.n_layers = n_layers
184
+ self.stabilizer = stabilizer
185
+ self.rank = rank
186
+ self.factorization = factorization
187
+ self.fixed_rank_modes = fixed_rank_modes
188
+ self.decomposition_kwargs = decomposition_kwargs
189
+ self.fno_skip = fno_skip
190
+ self.conv_bias_kernel = conv_bias_kernel
191
+ self.channel_mlp_skip = channel_mlp_skip
192
+ self.complex_data = complex_data
193
+
194
+ self.use_channel_mlp = use_channel_mlp
195
+ self.channel_mlp_expansion = channel_mlp_expansion
196
+ self.channel_mlp_dropout = channel_mlp_dropout
197
+ self.implementation = implementation
198
+ self.separable = separable
199
+ self.preactivation = preactivation
200
+ self.ada_in_features = ada_in_features
201
+ self.enforce_hermitian_symmetry = enforce_hermitian_symmetry
202
+
203
+ # apply real nonlin if data is real, otherwise CGELU
204
+ if self.complex_data:
205
+ self.non_linearity = CGELU
206
+ else:
207
+ self.non_linearity = non_linearity
208
+
209
+ # One conv per layer. Only resolution_scaling_factor varies by layer index
210
+ self.convs = nn.ModuleList(
211
+ [
212
+ conv_module(
213
+ self.in_channels,
214
+ self.out_channels,
215
+ self.n_modes,
216
+ # Per-layer scaling for super-resolution, or None if disabled
217
+ resolution_scaling_factor=(
218
+ self.resolution_scaling_factor[i]
219
+ if resolution_scaling_factor is not None
220
+ else None
221
+ ),
222
+ max_n_modes=max_n_modes,
223
+ rank=rank,
224
+ fixed_rank_modes=fixed_rank_modes,
225
+ implementation=implementation,
226
+ separable=separable,
227
+ factorization=factorization,
228
+ fno_block_precision=fno_block_precision,
229
+ decomposition_kwargs=decomposition_kwargs,
230
+ complex_data=complex_data,
231
+ # Only SpectralConv (and subclasses) accept enforce_hermitian_symmetry. Others ignore it
232
+ **(
233
+ {"enforce_hermitian_symmetry": enforce_hermitian_symmetry}
234
+ if issubclass(conv_module, SpectralConv)
235
+ else {}
236
+ ),
237
+ )
238
+ for i in range(n_layers)
239
+ ]
240
+ )
241
+
242
+ if fno_skip is not None:
243
+ if fno_skip.lower() == "linear":
244
+ # FourCastNet v3-like local + global convolutions: the spectral
245
+ # path is global, while larger kernels give this bias term locality.
246
+ fno_skip_modules = [
247
+ _make_conv_bias(
248
+ self.in_channels,
249
+ self.out_channels,
250
+ self.n_dim,
251
+ conv_bias_kernel,
252
+ )
253
+ for _ in range(n_layers)
254
+ ]
255
+ else:
256
+ if conv_bias_kernel != 1:
257
+ raise ValueError(
258
+ "conv_bias_kernel can only differ from 1 when fno_skip='linear'."
259
+ )
260
+ fno_skip_modules = [
261
+ skip_connection(
262
+ self.in_channels,
263
+ self.out_channels,
264
+ skip_type=fno_skip,
265
+ n_dim=self.n_dim,
266
+ )
267
+ for _ in range(n_layers)
268
+ ]
269
+ self.fno_skips = nn.ModuleList(fno_skip_modules)
270
+ else:
271
+ if conv_bias_kernel != 1:
272
+ raise ValueError(
273
+ "conv_bias_kernel can only differ from 1 when fno_skip='linear'."
274
+ )
275
+ self.fno_skips = None
276
+ if self.complex_data and self.fno_skips is not None:
277
+ self.fno_skips = nn.ModuleList([ComplexValued(x) for x in self.fno_skips])
278
+
279
+ if self.use_channel_mlp:
280
+ self.channel_mlp = nn.ModuleList(
281
+ [
282
+ ChannelMLP(
283
+ in_channels=self.out_channels,
284
+ hidden_channels=round(self.out_channels * channel_mlp_expansion),
285
+ dropout=channel_mlp_dropout,
286
+ n_dim=self.n_dim,
287
+ )
288
+ for _ in range(n_layers)
289
+ ]
290
+ )
291
+ if self.complex_data:
292
+ self.channel_mlp = nn.ModuleList(
293
+ [ComplexValued(x) for x in self.channel_mlp]
294
+ )
295
+ if channel_mlp_skip is not None:
296
+ self.channel_mlp_skips = nn.ModuleList(
297
+ [
298
+ skip_connection(
299
+ self.in_channels,
300
+ self.out_channels,
301
+ skip_type=channel_mlp_skip,
302
+ n_dim=self.n_dim,
303
+ )
304
+ for _ in range(n_layers)
305
+ ]
306
+ )
307
+ else:
308
+ self.channel_mlp_skips = None
309
+ if self.complex_data and self.channel_mlp_skips is not None:
310
+ self.channel_mlp_skips = nn.ModuleList(
311
+ [ComplexValued(x) for x in self.channel_mlp_skips]
312
+ )
313
+
314
+ # Each block will have 2 norms if we also use a ChannelMLP
315
+ self.n_norms = 2
316
+ if norm is None:
317
+ self.norm = None
318
+ elif norm == "instance_norm":
319
+ self.norm = nn.ModuleList(
320
+ [InstanceNorm() for _ in range(n_layers * self.n_norms)]
321
+ )
322
+ elif norm == "group_norm":
323
+ self.norm = nn.ModuleList(
324
+ [
325
+ nn.GroupNorm(num_groups=norm_groups, num_channels=self.out_channels)
326
+ for _ in range(n_layers * self.n_norms)
327
+ ]
328
+ )
329
+
330
+ elif norm == "batch_norm":
331
+ self.norm = nn.ModuleList(
332
+ [
333
+ BatchNorm(n_dim=self.n_dim, num_features=self.out_channels)
334
+ for _ in range(n_layers * self.n_norms)
335
+ ]
336
+ )
337
+
338
+ elif norm == "ada_in":
339
+ self.norm = nn.ModuleList(
340
+ [
341
+ AdaIN(ada_in_features, out_channels)
342
+ for _ in range(n_layers * self.n_norms)
343
+ ]
344
+ )
345
+ else:
346
+ raise ValueError(
347
+ f"Got norm={norm} but expected None or one of "
348
+ "[instance_norm, group_norm, batch_norm, ada_in]"
349
+ )
350
+
351
+ if self.complex_data and self.norm is not None:
352
+ self.norm = nn.ModuleList([ComplexValued(x) for x in self.norm])
353
+
354
+ def set_ada_in_embeddings(self, *embeddings):
355
+ """Sets the embeddings of each Ada-IN norm layers
356
+
357
+ Parameters
358
+ ----------
359
+ embeddings : tensor or list of tensor
360
+ if a single embedding is given, it will be used for each norm layer
361
+ otherwise, each embedding will be used for the corresponding norm layer
362
+ """
363
+ if self.norm is not None:
364
+ if len(embeddings) == 1:
365
+ for norm in self.norm:
366
+ norm.set_embedding(embeddings[0])
367
+ else:
368
+ for norm, embedding in zip(self.norm, embeddings):
369
+ norm.set_embedding(embedding)
370
+
371
+ def forward(self, x, index=0, output_shape=None):
372
+ if self.preactivation:
373
+ return self.forward_with_preactivation(x, index, output_shape)
374
+ else:
375
+ return self.forward_with_postactivation(x, index, output_shape)
376
+
377
+ def forward_with_postactivation(self, x, index=0, output_shape=None):
378
+ if self.fno_skips is not None:
379
+ x_skip_fno = self.fno_skips[index](x)
380
+ x_skip_fno = self.convs[index].transform(x_skip_fno, output_shape=output_shape)
381
+
382
+ if self.use_channel_mlp and self.channel_mlp_skips is not None:
383
+ x_skip_channel_mlp = self.channel_mlp_skips[index](x)
384
+ x_skip_channel_mlp = self.convs[index].transform(x_skip_channel_mlp, output_shape=output_shape)
385
+
386
+ if self.stabilizer == "tanh":
387
+ if self.complex_data:
388
+ x = ctanh(x)
389
+ else:
390
+ x = torch.tanh(x)
391
+
392
+ x_fno = self.convs[index](x, output_shape=output_shape)
393
+
394
+ if self.norm is not None:
395
+ x_fno = self.norm[self.n_norms * index](x_fno)
396
+
397
+ x = x_fno + x_skip_fno if self.fno_skips is not None else x_fno
398
+
399
+ if index < (self.n_layers - 1):
400
+ x = self.non_linearity(x)
401
+
402
+ if self.use_channel_mlp:
403
+ if self.channel_mlp_skips is not None:
404
+ x = self.channel_mlp[index](x) + x_skip_channel_mlp
405
+ else:
406
+ x = self.channel_mlp[index](x)
407
+
408
+ if self.norm is not None:
409
+ x = self.norm[self.n_norms * index + 1](x)
410
+
411
+ if index < (self.n_layers - 1):
412
+ x = self.non_linearity(x)
413
+
414
+ return x
415
+
416
+ def forward_with_preactivation(self, x, index=0, output_shape=None):
417
+ # Apply non-linear activation (and norm)
418
+ # before this block's convolution/forward pass:
419
+ x = self.non_linearity(x)
420
+
421
+ if self.norm is not None:
422
+ x = self.norm[self.n_norms * index](x)
423
+
424
+ if self.fno_skips is not None:
425
+ x_skip_fno = self.fno_skips[index](x)
426
+ x_skip_fno = self.convs[index].transform(x_skip_fno, output_shape=output_shape)
427
+
428
+ if self.use_channel_mlp and self.channel_mlp_skips is not None:
429
+ x_skip_channel_mlp = self.channel_mlp_skips[index](x)
430
+ x_skip_channel_mlp = self.convs[index].transform(x_skip_channel_mlp, output_shape=output_shape)
431
+
432
+ if self.stabilizer == "tanh":
433
+ if self.complex_data:
434
+ x = ctanh(x)
435
+ else:
436
+ x = torch.tanh(x)
437
+
438
+ x_fno = self.convs[index](x, output_shape=output_shape)
439
+
440
+ x = x_fno + x_skip_fno if self.fno_skips is not None else x_fno
441
+
442
+ if index < (self.n_layers - 1):
443
+ x = self.non_linearity(x)
444
+
445
+ if self.norm is not None:
446
+ x = self.norm[self.n_norms * index + 1](x)
447
+
448
+ if self.use_channel_mlp:
449
+ if self.channel_mlp_skips is not None:
450
+ x = self.channel_mlp[index](x) + x_skip_channel_mlp
451
+ else:
452
+ x = self.channel_mlp[index](x)
453
+
454
+ return x
455
+
456
+ @property
457
+ def n_modes(self):
458
+ return self._n_modes
459
+
460
+ @n_modes.setter
461
+ def n_modes(self, n_modes):
462
+ for i in range(self.n_layers):
463
+ self.convs[i].n_modes = n_modes
464
+ self._n_modes = n_modes
465
+
466
+ def get_block(self, indices):
467
+ """Returns a sub-FNO Block layer from the jointly parametrized main block
468
+
469
+ The parametrization of an FNOBlock layer is shared with the main one.
470
+ """
471
+ if self.n_layers == 1:
472
+ raise ValueError(
473
+ "A single layer is parametrized, directly use the main class."
474
+ )
475
+
476
+ return SubModule(self, indices)
477
+
478
+ def __getitem__(self, indices):
479
+ return self.get_block(indices)
480
+
481
+
482
+ class SubModule(nn.Module):
483
+ """Class representing one of the sub_module from the mother joint module
484
+
485
+ Notes
486
+ -----
487
+ This relies on the fact that nn.Parameters are not duplicated:
488
+ if the same nn.Parameter is assigned to multiple modules,
489
+ they all point to the same data, which is shared.
490
+ """
491
+
492
+ def __init__(self, main_module, indices):
493
+ super().__init__()
494
+ self.main_module = main_module
495
+ self.indices = indices
496
+
497
+ def forward(self, x):
498
+ return self.main_module.forward(x, self.indices)
sources/neuraloperator/neuralop/layers/fourier_continuation.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from numpy.polynomial.legendre import Legendre
5
+ import warnings
6
+ from pathlib import Path
7
+ import tensorly as tl
8
+
9
+
10
+ class FourierContinuation(nn.Module):
11
+ """Base class for Fourier Continuation implementations.
12
+
13
+ Fourier Continuation is a technique for extending non-periodic functions to periodic
14
+ ones on larger domains, enabling the use of spectral methods for differentiation
15
+ and solving PDEs. This base class provides the common interface and methods for
16
+ different Fourier Continuation approaches (Legendre polynomials, Gram matrices, etc.).
17
+
18
+ This allows spectral methods such as spectral differentiation to be applied to
19
+ non-periodic functions by working on the extended periodic domain.
20
+ """
21
+
22
+ def __init__(self, d=5, n_additional_pts=50):
23
+ """
24
+ Initialize FourierContinuation with specified parameters.
25
+
26
+ Parameters
27
+ ----------
28
+ d : int, optional
29
+ Number of matching points on the left and right boundaries, by default 5
30
+ n_additional_pts : int, optional
31
+ Number of additional points to add for continuation, by default 50
32
+ """
33
+ super().__init__()
34
+
35
+ self.d = d
36
+ self.n_additional_pts = n_additional_pts
37
+
38
+ def extend(self, x, dim):
39
+ """
40
+ Extend tensor along specified dimensions using Fourier Continuation.
41
+
42
+ This method extends non-periodic functions to periodic ones by adding
43
+ continuation points on both sides of the specified dimensions using
44
+ TensorLy's multi_mode_dot for efficient multi-dimensional extension.
45
+
46
+ Parameters
47
+ ----------
48
+ x : torch.Tensor
49
+ Input tensor to extend. Must have at least 2*d points along each
50
+ dimension to be extended (for boundary value extraction).
51
+ dim : int or tuple of ints,
52
+ Dimensions along which to extend:
53
+ - If int: extend along the last dim axes (e.g. dim=2 extends along the last 2 axes)
54
+ - If tuple: extend along the specified axes (supports negative indexing)
55
+
56
+ Returns
57
+ -------
58
+ torch.Tensor
59
+ Extended tensor with additional points added along specified dimensions.
60
+ Each extended dimension will have n_additional_pts more points than the input.
61
+ """
62
+
63
+ # Convert input dimension(s) to list of axes to extend along:
64
+ if isinstance(dim, int):
65
+ # If dim is an integer n, extend along the last n dimensions
66
+ axes = list(range(-dim, 0))
67
+ else:
68
+ # If dim is a tuple, extend along those specific dimensions
69
+ axes = list(dim)
70
+
71
+ # Convert negative axes to positive indices
72
+ axes = [a if a >= 0 else x.ndim + a for a in axes]
73
+
74
+ # Create extension matrices for each axis
75
+ # Each matrix maps input tensor along one axis to extended tensor
76
+ extension_matrices = [] # List of torch tensors, each shape: (extended_size, original_size)
77
+ modes = [] # List of axis indices to extend along
78
+
79
+ for axis in axes:
80
+ # Get the extension matrix for this axis
81
+ ext_mat = self._get_extension_matrix_for_axis(x, axis)
82
+ extension_matrices.append(ext_mat)
83
+ modes.append(axis)
84
+
85
+ # Use TensorLy's multi_mode_dot to apply all extensions simultaneously
86
+ # Input: x (original shape), matrices (list of extension matrices), modes (axis indices)
87
+ # Output: extended tensor with shape modified along specified axes
88
+ return tl.tenalg.multi_mode_dot(x, extension_matrices, modes=modes)
89
+
90
+ def _get_extension_matrix_for_axis(self, x, axis):
91
+ """
92
+ Get the extension matrix for a specific axis using Fourier continuation.
93
+
94
+ This method creates a matrix that maps the input tensor along one axis
95
+ to the extended tensor using the Fourier continuation approach.
96
+
97
+ Parameters
98
+ ----------
99
+ x : torch.Tensor
100
+ Input tensor
101
+ axis : int
102
+ Axis for which to get the extension matrix
103
+
104
+ Returns
105
+ -------
106
+ torch.Tensor
107
+ Extension matrix for the specified axis
108
+ """
109
+
110
+ axis_size = x.shape[axis] # Original size along the axis to extend
111
+ extended_size = axis_size + self.n_additional_pts # Final size after extension
112
+ c = self.n_additional_pts // 2 # Number of continuation points on each side
113
+
114
+ # Create the extension matrix, which maps the input to the extended output
115
+ # Shape: (extended_size, axis_size) where extended_size = axis_size + n_additional_pts
116
+ ext_mat = torch.zeros((extended_size, axis_size), dtype=x.dtype, device=x.device)
117
+
118
+ # Place identity matrix in the middle (original values)
119
+ ext_mat[c:c+axis_size, :] = torch.eye(axis_size, dtype=x.dtype, device=x.device)
120
+
121
+ # Get the extension matrix for boundary points
122
+ ext_mat_boundary = self.ext_mat.to(dtype=x.dtype, device=x.device)
123
+
124
+ # Fill in the continuation regions
125
+ if c > 0:
126
+ # The extension matrix maps [right_bnd, left_bnd] to continuation values
127
+ # where ext_mat_boundary has shape (n_additional_pts, 2*d)
128
+ # and maps [right_bnd, left_bnd] to [left_cont, right_cont]
129
+
130
+ # Left continuation: use the last c rows of the extension matrix
131
+ # These map [right_bnd, left_bnd] to left continuation values
132
+ ext_mat[:c, :self.d] = ext_mat_boundary[-c:, self.d:] # right_bnd -> left_cont
133
+ ext_mat[:c, axis_size-self.d:] = ext_mat_boundary[-c:, :self.d] # left_bnd -> left_cont
134
+
135
+ # Right continuation: use the first c rows of the extension matrix
136
+ # These map [right_bnd, left_bnd] to right continuation values
137
+ ext_mat[-c:, :self.d] = ext_mat_boundary[:c, self.d:] # right_bnd -> right_cont
138
+ ext_mat[-c:, axis_size-self.d:] = ext_mat_boundary[:c, :self.d] # left_bnd -> right_cont
139
+
140
+ return ext_mat
141
+
142
+ def forward(self, x, dim):
143
+ """
144
+ Forward pass that calls the extend method.
145
+
146
+ This method extends non-periodic functions to periodic ones by adding
147
+ continuation points on both sides of the specified dimensions.
148
+
149
+ Parameters
150
+ ----------
151
+ x : torch.Tensor
152
+ Input tensor to extend. Must have at least 2*d points along each
153
+ dimension to be extended (for boundary value extraction).
154
+ dim : int or tuple of ints,
155
+ Dimensions along which to extend:
156
+ - If int: extend along the last dim axes (e.g. dim=2 extends along the last 2 axes)
157
+ - If tuple: extend along the specified axes (supports negative indexing)
158
+
159
+ Returns
160
+ -------
161
+ torch.Tensor
162
+ Extended tensor with additional points added along specified dimensions.
163
+ Each extended dimension will have n_additional_pts more points than the input.
164
+ """
165
+ return self.extend(x, dim)
166
+
167
+ def restrict(self, x, dim):
168
+ """
169
+ Remove Fourier continuation extension points to restore original domain size.
170
+
171
+ This method reverses the extension process by removing the continuation points
172
+ that were added during Fourier continuation.
173
+
174
+ It removes n_additional_pts//2 points from each side of the specified dimensions.
175
+
176
+ Parameters
177
+ ----------
178
+ x : torch.Tensor
179
+ Extended tensor from Fourier continuation. Must have been extended using
180
+ the same n_additional_pts parameter as this instance.
181
+ dim : int or tuple of ints
182
+ Dimensions along which to restrict:
183
+ - If int: restrict along the last dim axes (e.g. dim=2 restricts along the last 2 axes)
184
+ - If tuple: restrict along the specified axes (supports negative indexing)
185
+
186
+ Returns
187
+ -------
188
+ torch.Tensor
189
+ Tensor with original domain size. Each restricted dimension will have
190
+ n_additional_pts fewer points than the input (n_additional_pts//2 removed
191
+ from each side).
192
+ """
193
+
194
+ # Convert input dimension(s) to list of axes to restrict along:
195
+ if isinstance(dim, int):
196
+ # If dim is an integer n, restrict along the last n dimensions
197
+ axes = list(range(-dim, 0))
198
+ else:
199
+ # If dim is a tuple, restrict along those specific dimensions
200
+ axes = list(dim)
201
+
202
+ # Convert negative axes to positive for easier handling
203
+ axes = [a if a >= 0 else x.ndim + a for a in axes]
204
+
205
+ # Create slices to restrict along each axis
206
+ c = self.n_additional_pts // 2 # Number of points to remove from each side
207
+ slices = [slice(None)] * x.ndim
208
+
209
+ for axis in axes:
210
+ # For each axis to restrict, remove c points from each side
211
+ slices[axis] = slice(c, -c)
212
+
213
+ # Return restricted tensor with reduced size along specified axes
214
+ return x[tuple(slices)]
215
+
216
+
217
+ class FCLegendre(FourierContinuation):
218
+ """Fourier Continuation using Legendre polynomials.
219
+
220
+ This class implements Fourier Continuation using Legendre polynomial basis functions
221
+ to extend non-periodic functions to periodic ones on larger domains. The method works
222
+ by fitting Legendre polynomials to boundary values and using them to compute
223
+ continuation values that make the extended function periodic.
224
+
225
+ Legendre polynomials P_n(x) are orthogonal polynomials with weight w=1 on [-1, 1]:
226
+ ∫_{-1}^{1} P_j(x) P_k(x) dx = 2/(2j+1) δ_{jk}
227
+
228
+ The extension process:
229
+ 1. Extract d boundary points from each end of the input signal
230
+ 2. Fit a linear combination of Legendre polynomials to these boundary values
231
+ 3. Use the fitted polynomials to compute continuation values
232
+ 4. Concatenate the continuation with the original signal
233
+
234
+ """
235
+
236
+ def __init__(self, d=5, n_additional_pts=50, rcond=1e-15):
237
+ """
238
+ Initialize FCLegendre with specified parameters.
239
+
240
+ Parameters
241
+ ----------
242
+ d : int
243
+ Number of matching points on the left and right boundaries
244
+ Related to the degree of the Legendre polynomial basis used for extension (degree 2d-1).
245
+ By default 6
246
+ n_additional_pts : int
247
+ Number of additional points to add for continuation, by default 50
248
+ Lower values of d typically require more n_additional_pts points
249
+ rcond : float, optional
250
+ Cutoff for small singular values for the pseudoinverse of the extension matrix
251
+ Singular values less than or equal to rcond * largest_singular_value are set to zero
252
+ This can be adjusted for numerical stability, especially for larger values of d.
253
+ A smaller value can lead to more stable results, but may also introduce numerical errors.
254
+ By default 1e-15 (same as numpy default for np.linalg.pinv)
255
+ """
256
+ super().__init__(d, n_additional_pts)
257
+
258
+ self.rcond = rcond
259
+ self.compute_extension_matrix()
260
+
261
+ def compute_extension_matrix(self):
262
+ """
263
+ Compute the extension matrix using Legendre polynomials.
264
+
265
+ This method constructs the matrix that maps boundary values to continuation
266
+ values using Legendre polynomial basis functions.
267
+ """
268
+
269
+ total_points = 2 * self.d + self.n_additional_pts
270
+
271
+ # Use [-1,1] interval where Legendre polynomials are orthogonal
272
+ a, b = -1.0, 1.0
273
+
274
+ # Generate uniform grid on [-1,1] with total_points points
275
+ h = (b - a) / (total_points - 1)
276
+ full_grid = a + h * np.arange(total_points, dtype=np.float64)
277
+
278
+ # Extract points for fitting (d points from each end)
279
+ fit_grid = np.concatenate((full_grid[0 : self.d], full_grid[-self.d :]), 0)
280
+
281
+ # Extract points for extension (middle points)
282
+ extension_grid = full_grid[self.d : -self.d]
283
+
284
+ # Construct normalized Legendre polynomials
285
+ # numpy.polynomial.legendre.Legendre are orthogonal but not normalized on [-1,1]:
286
+ # ∫_{-1}^{1} P_j(x) P_k(x) dx = 2/(2j+1) δ_{jk}
287
+ # Normalization can improve numerical stability for larger values of d
288
+ I = np.eye(2 * self.d, dtype=np.float64)
289
+ polynomials = [
290
+ np.sqrt((2 * j + 1) / 2) * Legendre(I[j, :]) for j in range(2 * self.d)
291
+ ]
292
+
293
+ # Evaluate normalized polynomials on the fit and extension grids
294
+ X = np.stack([P(fit_grid) for P in polynomials], axis=1) # Fit grid evaluations
295
+ Q = np.stack([P(extension_grid) for P in polynomials], axis=1) # Extension grid evaluations
296
+
297
+ # Compute extension matrix using pseudoinverse
298
+ ext_mat = Q @ np.linalg.pinv(X, rcond=self.rcond)
299
+
300
+ # Register matrices as persistent buffers for the module
301
+ self.register_buffer("ext_mat", torch.from_numpy(ext_mat))
302
+ self.register_buffer("ext_mat_T", self.ext_mat.T.clone())
303
+
304
+ return self.ext_mat
305
+
306
+
307
+ class FCGram(FourierContinuation):
308
+ """Fourier Continuation using Gram matrices.
309
+
310
+ This class implements the FC-Gram algorithm described in Section 3.1 of:
311
+ Amlani, F., & Bruno, O. P. (2016). An FC-based spectral solver for
312
+ elastodynamic problems in general three-dimensional domains.
313
+ Journal of Computational Physics, 307, 333-354.
314
+
315
+ The algorithm uses pre-computed Gram matrices (ArQr, AlQl) to perform
316
+ Fourier Continuation of discretized functions.
317
+
318
+ If the required pre-computed FCGram matrices are not available, they
319
+ can be computed using the MATLAB code from the FCGram repository
320
+ https://github.com/neuraloperator/FCGram/
321
+ and then saved to the appropriate matrices_path directory in .npz format.
322
+
323
+ The matrices are:
324
+ - ArQr: Right boundary continuation matrix
325
+ - AlQl: Left boundary continuation matrix
326
+
327
+ The matrices are saved in the .npz format.
328
+
329
+ """
330
+
331
+ def __init__(self, d=5, n_additional_pts=50, matrices_path=None):
332
+ """
333
+ Initialize FCGram with specified parameters.
334
+
335
+ Parameters
336
+ ----------
337
+ d : int
338
+ Number of matching points on the left and right boundaries
339
+ Degree of the Gram polynomial d
340
+ Typically between 3 and 8 (precomputed matrices available for d in {2,3,4,5,6,7,8}).
341
+ d=3,4,5,6 are typically good choices, by default 6.
342
+ n_additional_pts : int
343
+ Number of continuation points. By default 50.
344
+ Adds n_additional_pts//2 points on each side of the input signal.
345
+ Precomputed matrices available only for n_additional_pts = 50.
346
+ Unlike for FCLegendre, it is usually not necessary to change this parameter.
347
+ matrices_path : str or Path, optional
348
+ Path to directory containing FCGram matrices.
349
+ If None, uses the directory containing this file, by default None
350
+ """
351
+ super().__init__(d, n_additional_pts)
352
+
353
+ if self.n_additional_pts % 2 == 1:
354
+ warnings.warn("n_additional_pts must be even, rounding down.", UserWarning)
355
+ self.n_additional_pts -= 1
356
+
357
+ self.c = int(self.n_additional_pts // 2)
358
+
359
+ if matrices_path is None:
360
+ self.matrices_path = Path(__file__).parent / "fcgram_matrices"
361
+ else:
362
+ self.matrices_path = Path(matrices_path)
363
+
364
+ # Load pre-computed FCGram matrices
365
+ self.load_matrices()
366
+
367
+ def _get_extension_matrix_for_axis(self, x, axis):
368
+ """
369
+ Get the extension matrix for a specific axis using FC-Gram algorithm.
370
+
371
+ This method creates a matrix that maps the input tensor along one axis
372
+ to the extended tensor using pre-computed Gram matrices.
373
+
374
+ Parameters
375
+ ----------
376
+ x : torch.Tensor
377
+ Input tensor
378
+ axis : int
379
+ Axis for which to get the extension matrix
380
+
381
+ Returns
382
+ -------
383
+ torch.Tensor
384
+ Extension matrix for the specified axis
385
+ """
386
+ axis_size = x.shape[axis]
387
+ extended_size = axis_size + self.n_additional_pts
388
+ c = self.n_additional_pts // 2
389
+
390
+ # Create the extension matrix
391
+ ext_mat = torch.zeros((extended_size, axis_size), dtype=x.dtype, device=x.device)
392
+
393
+ # Place identity matrix in the middle (original values)
394
+ ext_mat[c:c+axis_size, :] = torch.eye(axis_size, dtype=x.dtype, device=x.device)
395
+
396
+ # Get pre-computed Gram matrices
397
+ AlQl = self.AlQl.to(dtype=x.dtype, device=x.device)
398
+ ArQr = self.ArQr.to(dtype=x.dtype, device=x.device)
399
+
400
+ # Fill in the continuation regions
401
+ if c > 0:
402
+ # Left continuation: map left boundary to left continuation
403
+ ext_mat[:c, : self.d] = AlQl[:c, :]
404
+
405
+ # Right continuation: map right boundary to right continuation
406
+ ext_mat[-c:, axis_size - self.d :] = ArQr[:c, :]
407
+
408
+ return ext_mat
409
+
410
+ def load_matrices(self):
411
+ """
412
+ Load the pre-computed FCGram matrices from .npz files.
413
+
414
+ This method loads the pre-computed Gram matrices required for the FC-Gram
415
+ algorithm. The matrices are stored in .npz format and contain the optimized
416
+ continuation matrices for the specified (d, c) parameter combination.
417
+
418
+ The loaded matrices are:
419
+ - ArQr: Right boundary continuation matrix
420
+ - AlQl: Left boundary continuation matrix
421
+
422
+ These matrices are registered as PyTorch buffers so they are automatically
423
+ moved to the correct device (CPU/GPU) when the module is moved.
424
+
425
+ Raises
426
+ ------
427
+ FileNotFoundError
428
+ If the required .npz file is not found in the matrices_path directory.
429
+ The file should be named 'FCGram_data_d{d}_c{c}.npz' where c = n_additional_pts // 2.
430
+
431
+ Note
432
+ ----
433
+ If the required matrices are not available, they can be computed using the
434
+ MATLAB code from the FCGram repository:
435
+ https://github.com/neuraloperator/FCGram/
436
+
437
+ The computed matrices should be saved in .npz format in the matrices_path
438
+ directory with the correct naming convention.
439
+ """
440
+ filepath = self.matrices_path / f"FCGram_data_d{self.d}_c{self.c}.npz"
441
+
442
+ if not filepath.exists():
443
+ raise FileNotFoundError(
444
+ f"FCGram matrices not found at {filepath}. \n"
445
+ f"Please ensure the .npz file exists with d={self.d}, c={self.c}."
446
+ )
447
+
448
+ # Load matrices from .npz file
449
+ npz_data = np.load(str(filepath))
450
+
451
+ # Extract matrices, convert to torch tensors, and register as buffers so they are moved to GPU
452
+ self.register_buffer("ArQr", torch.from_numpy(npz_data["ArQr"]))
453
+ self.register_buffer("AlQl", torch.from_numpy(npz_data["AlQl"]))
sources/neuraloperator/neuralop/layers/gno_block.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Literal, Optional, Callable
2
+
3
+ import torch
4
+ from torch import nn
5
+ import torch.nn.functional as F
6
+
7
+ from .channel_mlp import LinearChannelMLP
8
+ from .integral_transform import IntegralTransform
9
+ from .neighbor_search import NeighborSearch
10
+ from .embeddings import SinusoidalEmbedding
11
+
12
+
13
+ class GNOBlock(nn.Module):
14
+ """Graph Neural Operator layer
15
+
16
+ It is a resolution-invariant operator that maps a function defined
17
+ over one coordinate mesh to another defined over another coordinate mesh using
18
+ a pointwise kernel integral that takes contributions from neighbors of distance 1
19
+ within a graph constructed via neighbor search with a specified radius.
20
+ The exact implementation details of the GNO layer architecture are discussed in [1]_.
21
+
22
+ Optionally, if provided, the input and output queries can have a positional embedding
23
+ applied using the argument pos_embedding.
24
+
25
+ The kernel integral computed in IntegralTransform computes one of:
26
+ (a) \\int_{A(x)} k(x, y) dy
27
+ (b) \\int_{A(x)} k(x, y) * f(y) dy
28
+ (c) \\int_{A(x)} k(x, y, f(y)) dy
29
+ (d) \\int_{A(x)} k(x, y, f(y)) * f(y) dy
30
+
31
+ Parameters
32
+ ----------
33
+ in_channels : int
34
+ Number of channels in input function. Only used if transform_type
35
+ is (c) "nonlinear" or (d) "nonlinear_kernelonly"
36
+ out_channels : int
37
+ Number of channels in output function
38
+ coord_dim : int
39
+ Dimension of domain on which x and y are defined
40
+ radius : float
41
+ Radius in which to search for neighbors
42
+ weighting_fn : Callable, optional
43
+ Optional squared-norm weighting function to use for Mollified GNO layer
44
+ by default None. See neuralop.layers.gno_weighting_functions for more details.
45
+ reduction : Literal['sum', 'mean']
46
+ Whether to aggregate information from each neighborhood in the
47
+ integral transform by summing ('sum') or averaging ('mean'), by default 'sum'
48
+
49
+ Other Parameters
50
+ ----------------
51
+ transform_type : str, optional
52
+ Which integral transform to compute. Options: 'linear_kernelonly', 'linear', 'nonlinear_kernelonly', 'nonlinear'.
53
+ The mapping is:
54
+ 'linear_kernelonly' -> (a)
55
+ 'linear' -> (b) [DEFAULT]
56
+ 'nonlinear_kernelonly' -> (c)
57
+ 'nonlinear' -> (d)
58
+ If the input f is not given then (a) is computed
59
+ by default independently of this parameter, by default 'linear'
60
+ pos_embedding_type: literal {'transformer', 'nerf'} | None, optional
61
+ Type of positional embedding to use during the kernel integral transform.
62
+ Options: 'transformer', 'nerf', None. See `neuralop.layers.embeddings.SinusoidalEmbedding` for more details, by default 'transformer'
63
+ pos_embedding_channels : int, optional
64
+ Per-channel dimension of optional positional embedding to use, by default 32
65
+ pos_embedding_max_positions: int, optional
66
+ `max_positions` parameter for SinusoidalEmbedding of type `'transformer'`. If
67
+ `pos_embedding_type != 'transformer'`, this value is not used, by default 10000
68
+ channel_mlp_layers : List[int], optional
69
+ List of layer widths to dynamically construct
70
+ LinearChannelMLP network to parameterize kernel k, by default None
71
+ channel_mlp_non_linearity : torch.nn function, optional
72
+ Activation function for ChannelMLPLinear above, by default F.gelu
73
+ channel_mlp : nn.Module, optional
74
+ ChannelMLP parametrizing the kernel k. Input dimension
75
+ should be dim x + dim y or dim x + dim y + dim f.
76
+ ChannelMLP should not be pointwise and should only operate across
77
+ channels to preserve the discretization-invariance of the
78
+ kernel integral. If you have more specific needs than the LinearChannelMLP,
79
+ this argument allows you to pass your own Module to parameterize the kernel k.
80
+ Default None, by default None
81
+ use_torch_scatter_reduce : bool, optional
82
+ Whether to use torch-scatter to perform grouped reductions in the IntegralTransform.
83
+ If False, uses native Python reduction in neuralop.layers.segment_csr, by default True
84
+
85
+ .. warning::
86
+
87
+ torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch,
88
+ so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency`
89
+ for more information.
90
+ use_open3d_neighbor_search : bool, optional
91
+ Whether to use open3d for fast 3d neighbor search, by default True.
92
+
93
+ .. note ::
94
+ If the coordinates provided are not 3D, the GNOBlock automatically
95
+ uses PyTorch native fallback neighbor search.
96
+
97
+ Examples
98
+ --------
99
+ ```
100
+ >>> gno = GNOBlock(in_channels=2, out_channels=12, coord_dim=3, radius=0.035)
101
+
102
+ >>> gno
103
+ GNOBlock(
104
+ (pos_embedding): SinusoidalEmbedding()
105
+ (neighbor_search): NeighborSearch()
106
+ (integral_transform): IntegralTransform(
107
+ (channel_mlp): LinearChannelMLP(
108
+ (fcs): ModuleList(
109
+ (0): Linear(in_features=384, out_features=128, bias=True)
110
+ (1): Linear(in_features=128, out_features=256, bias=True)
111
+ (2): Linear(in_features=256, out_features=128, bias=True)
112
+ (3): Linear(in_features=128, out_features=12, bias=True)
113
+ )
114
+ )
115
+ )
116
+ )
117
+ ```
118
+
119
+ References
120
+ ----------
121
+ .. [1] Zongyi Li, Kamyar Azizzadenesheli, Burigede Liu, Kaushik Bhattacharya,
122
+ Anima Anandkumar (2020). "Neural Operator: Graph Kernel Network for
123
+ Partial Differential Equations." ArXiV, https://arxiv.org/pdf/2003.03485.
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ in_channels: int,
129
+ out_channels: int,
130
+ coord_dim: int,
131
+ radius: float,
132
+ transform_type="linear",
133
+ weighting_fn: Optional[Callable] = None,
134
+ reduction: Literal["sum", "mean"] = "sum",
135
+ pos_embedding_type: str = "transformer",
136
+ pos_embedding_channels: int = 32,
137
+ pos_embedding_max_positions: int = 10000,
138
+ channel_mlp_layers: List[int] = [128, 256, 128],
139
+ channel_mlp_non_linearity=F.gelu,
140
+ channel_mlp: nn.Module = None,
141
+ use_torch_scatter_reduce: bool = True,
142
+ use_open3d_neighbor_search: bool = True,
143
+ ):
144
+ super().__init__()
145
+
146
+ self.in_channels = in_channels
147
+ self.out_channels = out_channels
148
+ self.coord_dim = coord_dim
149
+
150
+ self.radius = radius
151
+
152
+ # Apply sinusoidal positional embedding
153
+ self.pos_embedding_type = pos_embedding_type
154
+ if self.pos_embedding_type in ["nerf", "transformer"]:
155
+ self.pos_embedding = SinusoidalEmbedding(
156
+ in_channels=coord_dim,
157
+ num_frequencies=pos_embedding_channels,
158
+ embedding_type=pos_embedding_type,
159
+ max_positions=pos_embedding_max_positions,
160
+ )
161
+ else:
162
+ self.pos_embedding = None
163
+
164
+ # Create in-to-out nb search module
165
+ if use_open3d_neighbor_search:
166
+ assert self.coord_dim == 3, f"Error: open3d is only designed for 3d data, \
167
+ GNO instantiated for dim={coord_dim}"
168
+ self.neighbor_search = NeighborSearch(
169
+ use_open3d=use_open3d_neighbor_search, return_norm=weighting_fn is not None
170
+ )
171
+
172
+ # create proper kernel input channel dim
173
+ if self.pos_embedding is None:
174
+ # x and y dim will be coordinate dim if no pos embedding is applied
175
+ kernel_in_dim = self.coord_dim * 2
176
+ kernel_in_dim_str = "dim(y) + dim(x)"
177
+ else:
178
+ # x and y dim will be embedding dim if pos embedding is applied
179
+ kernel_in_dim = self.pos_embedding.out_channels * 2
180
+ kernel_in_dim_str = "dim(y_embed) + dim(x_embed)"
181
+
182
+ if transform_type == "nonlinear" or transform_type == "nonlinear_kernelonly":
183
+ kernel_in_dim += self.in_channels
184
+ kernel_in_dim_str += " + dim(f_y)"
185
+
186
+ if channel_mlp is not None:
187
+ assert channel_mlp.in_channels == kernel_in_dim, f"Error: expected ChannelMLP to take\
188
+ input with {kernel_in_dim} channels (feature channels={kernel_in_dim_str}),\
189
+ got {channel_mlp.in_channels}."
190
+ assert channel_mlp.out_channels == out_channels, f"Error: expected ChannelMLP to have\
191
+ {out_channels=} but got {channel_mlp.in_channels=}."
192
+ channel_mlp = channel_mlp
193
+
194
+ elif channel_mlp_layers is not None:
195
+ if channel_mlp_layers[0] != kernel_in_dim:
196
+ channel_mlp_layers = [kernel_in_dim] + channel_mlp_layers
197
+ if channel_mlp_layers[-1] != self.out_channels:
198
+ channel_mlp_layers.append(self.out_channels)
199
+ channel_mlp = LinearChannelMLP(layers=channel_mlp_layers, non_linearity=channel_mlp_non_linearity)
200
+
201
+ # Create integral transform module
202
+ self.integral_transform = IntegralTransform(
203
+ channel_mlp=channel_mlp,
204
+ transform_type=transform_type,
205
+ use_torch_scatter=use_torch_scatter_reduce,
206
+ weighting_fn=weighting_fn,
207
+ reduction=reduction,
208
+ )
209
+
210
+ def forward(self, y, x, f_y=None):
211
+ """Compute a GNO neighbor search and kernel integral transform.
212
+
213
+ Parameters
214
+ ----------
215
+ y : torch.Tensor of shape [n, d1]
216
+ n points of dimension d1 specifying
217
+ the space to integrate over.
218
+ If batched, these must remain constant
219
+ over the whole batch so no batch dim is needed.
220
+ x : torch.Tensor of shape [m, d1], default None
221
+ m points of dimension d1 over which the
222
+ output function is defined. Must share domain
223
+ with y
224
+ f_y : torch.Tensor of shape [batch, n, d2] or [n, d2], default None
225
+ Function to integrate the kernel against defined
226
+ on the points y. The kernel is assumed diagonal
227
+ hence its output shape must be d3 for the transforms
228
+ (b) or (d). If None, (a) is computed.
229
+
230
+ Returns
231
+ -------
232
+ out_features : torch.Tensor of shape [batch, m, d3] or [m, d3]
233
+ Output function given on the points x.
234
+ d4 is the output size of the kernel k.
235
+ """
236
+
237
+ neighbors_dict = self.neighbor_search(data=y, queries=x, radius=self.radius)
238
+
239
+ if self.pos_embedding is not None:
240
+ y_embed = self.pos_embedding(y)
241
+ x_embed = self.pos_embedding(x)
242
+ else:
243
+ y_embed = y
244
+ x_embed = x
245
+
246
+ out_features = self.integral_transform(
247
+ y=y_embed, x=x_embed, neighbors=neighbors_dict, f_y=f_y
248
+ )
249
+
250
+ return out_features
sources/neuraloperator/neuralop/layers/gno_weighting_functions.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ import torch
3
+
4
+
5
+ def bump_cutoff(x, radius=1.0, scale=1.0, eps=1e-7):
6
+ """
7
+ Bump cutoff function with exponential decay.
8
+
9
+ Formula: w(x) = scale * e * exp(-1/(1-d² + ε))
10
+ where d = x/radius, x ∈ [0, radius], and ε is a small constant for numerical stability.
11
+ """
12
+ out = x.clip(0.0, radius) / radius
13
+ out = -1 / ((1 - out**2) + eps)
14
+ return out.exp() * torch.e * scale
15
+
16
+
17
+ def half_cos_cutoff(x, radius=1.0, scale=1.0):
18
+ """
19
+ Half-cosine cutoff function with smooth decay.
20
+
21
+ Formula: w(x) = scale * (0.5 * cos(π * d) + 0.5)
22
+ where d = x/radius, x ∈ [0, radius].
23
+ """
24
+ x = x / radius
25
+ return scale * (0.5 * torch.cos(torch.pi * x) + 0.5)
26
+
27
+
28
+ def quadr_cutoff(x, radius=1.0, scale=1.0):
29
+ """
30
+ Quadratic cutoff function with piecewise definition.
31
+
32
+ Formula: w(x) = scale * {1 - 2d², if d < 0.5
33
+ {2(1 - d)², if d ≥ 0.5
34
+ where d = x/radius, x ∈ [0, radius].
35
+ """
36
+ x = x / radius
37
+ left = 1 - 2 * x**2
38
+ right = 2 * (1 - x) ** 2
39
+ return scale * torch.where(x < 0.5, left, right)
40
+
41
+
42
+ def quartic_cutoff(x, radius=1.0, scale=1.0):
43
+ """
44
+ Quartic cutoff function with fourth-order polynomial.
45
+
46
+ Formula: w(x) = (scale/radius⁴) * x⁴ - (2*scale/radius²) * x² + scale
47
+ where d = x/radius, x ∈ [0, radius].
48
+ """
49
+ a = scale / radius**4
50
+ c = -2 * scale / radius**2
51
+ return a * x**4 + c * x**2 + scale
52
+
53
+
54
+ def octic_cutoff(x, radius=1.0, scale=1.0):
55
+ """
56
+ Octic cutoff function with eighth-order polynomial.
57
+
58
+ Formula: w(x) = scale * (-3d⁸ + 8d⁶ - 6d⁴ + 1)
59
+ where d = x/radius, x ∈ [0, radius].
60
+ """
61
+ x = x / radius
62
+ return scale * (-3 * x**8 + 8 * x**6 - 6 * x**4 + 1)
63
+
64
+
65
+ WEIGHTING_FN_REGISTRY = {
66
+ "bump": bump_cutoff,
67
+ "half_cos": half_cos_cutoff,
68
+ "quadr": quadr_cutoff,
69
+ "quartic": quartic_cutoff,
70
+ "octic": octic_cutoff,
71
+ }
72
+
73
+
74
+ def dispatch_weighting_fn(weight_function_name: str, sq_radius: float, scale: float):
75
+ """
76
+ Select a GNO weighting function for use in output GNO
77
+ of a Mollified Graph Neural Operator-based model. See [1]_ (add later)
78
+
79
+ Parameters
80
+ ----------
81
+ weight_function_name : str Literal
82
+ name of weighting function to use, keyed to ``WEIGHTING_FN_REGISTRY`` above
83
+ sq_radius : float
84
+ squared radius of GNO neighborhoods for Nyström approximation
85
+ scale : float
86
+ factor by which to scale all weights
87
+ """
88
+ base_func = WEIGHTING_FN_REGISTRY.get(weight_function_name)
89
+ if base_func is None:
90
+ raise NotImplementedError(
91
+ f"weighting function should be one of {list(WEIGHTING_FN_REGISTRY.keys())}, got {weight_function_name}"
92
+ )
93
+ return partial(base_func, radius=sq_radius, scale=scale)
sources/neuraloperator/neuralop/layers/integral_transform.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+
5
+ from .channel_mlp import LinearChannelMLP
6
+ from .segment_csr import segment_csr
7
+
8
+
9
+ class IntegralTransform(nn.Module):
10
+ """Integral Kernel Transform (GNO).
11
+
12
+ It computes one of the following:
13
+ (a) \\int_{A(x)} k(x, y) dy
14
+ (b) \\int_{A(x)} k(x, y) * f(y) dy
15
+ (c) \\int_{A(x)} k(x, y, f(y)) dy
16
+ (d) \\int_{A(x)} k(x, y, f(y)) * f(y) dy
17
+
18
+ x : Points for which the output is defined
19
+
20
+ y : Points for which the input is defined
21
+ A(x) : A subset of all points y (depending on\
22
+ each x) over which to integrate
23
+
24
+ k : A kernel parametrized as a MLP (LinearChannelMLP)
25
+
26
+ f : Input function to integrate against given\
27
+ on the points y
28
+
29
+ If f is not given, a transform of type (a)
30
+ is computed. Otherwise transforms (b), (c),
31
+ or (d) are computed. The sets A(x) are specified
32
+ as a graph in CRS format.
33
+
34
+ Parameters
35
+ ----------
36
+ channel_mlp : torch.nn.Module, optional
37
+ MLP parametrizing the kernel k. Input dimension
38
+ should be dim x + dim y or dim x + dim y + dim f.
39
+ MLP should not be pointwise and should only operate across
40
+ channels to preserve the discretization-invariance of the
41
+ kernel integral, by default None
42
+ channel_mlp_layers : list, optional
43
+ List of layers sizes speficing a MLP which
44
+ parametrizes the kernel k. The MLP will be
45
+ instansiated by the LinearChannelMLP class, by default None
46
+ channel_mlp_non_linearity : callable, optional
47
+ Non-linear function used to be used by the
48
+ LinearChannelMLP class, by default F.gelu. Only used if channel_mlp_layers is
49
+ given and channel_mlp is None, by default torch.nn.functional.gelu
50
+ transform_type : str, optional
51
+ Which integral transform to compute. Options: 'linear_kernelonly', 'linear', 'nonlinear_kernelonly', 'nonlinear'.
52
+ The mapping is:
53
+ 'linear_kernelonly' -> (a)
54
+ 'linear' -> (b)
55
+ 'nonlinear_kernelonly' -> (c)
56
+ 'nonlinear' -> (d)
57
+ If the input f is not given then (a) is computed
58
+ by default independently of this parameter, by default 'linear'
59
+ use_torch_scatter : bool, optional
60
+ Whether to use torch-scatter to perform grouped reductions in the IntegralTransform.
61
+ If False, uses native Python reduction in neuralop.layers.segment_csr, by default True
62
+
63
+ .. warning::
64
+
65
+ torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch,
66
+ so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency`
67
+ for more information.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ channel_mlp=None,
73
+ channel_mlp_layers=None,
74
+ channel_mlp_non_linearity=F.gelu,
75
+ transform_type="linear",
76
+ weighting_fn=None,
77
+ reduction="sum",
78
+ use_torch_scatter=True,
79
+ ):
80
+ super().__init__()
81
+
82
+ assert channel_mlp is not None or channel_mlp_layers is not None
83
+
84
+ self.reduction = reduction
85
+ self.transform_type = transform_type
86
+ self.use_torch_scatter = use_torch_scatter
87
+ if (
88
+ self.transform_type != "linear_kernelonly"
89
+ and self.transform_type != "linear"
90
+ and self.transform_type != "nonlinear_kernelonly"
91
+ and self.transform_type != "nonlinear"
92
+ ):
93
+ raise ValueError(
94
+ f"Got transform_type={transform_type} but expected one of "
95
+ "[linear_kernelonly, linear, nonlinear_kernelonly, nonlinear]"
96
+ )
97
+
98
+ if channel_mlp is None:
99
+ self.channel_mlp = LinearChannelMLP(
100
+ layers=channel_mlp_layers, non_linearity=channel_mlp_non_linearity
101
+ )
102
+ else:
103
+ self.channel_mlp = channel_mlp
104
+
105
+ self.weighting_fn = weighting_fn
106
+
107
+ def forward(self, y, neighbors, x=None, f_y=None, weights=None):
108
+ """Compute a kernel integral transform. Assumes x=y if not specified.
109
+
110
+ Integral is taken w.r.t. the neighbors.
111
+
112
+ If no weights are given, a Monte-Carlo approximation is made.
113
+
114
+ .. note :: For transforms of type 0 or 2, out channels must be
115
+ the same as the channels of f
116
+
117
+ Parameters
118
+ ----------
119
+ y : torch.Tensor of shape [n, d1]
120
+ n points of dimension d1 specifying
121
+ the space to integrate over.
122
+ If batched, these must remain constant
123
+ over the whole batch so no batch dim is needed.
124
+ neighbors : dict
125
+ The sets :math:`A(x)` given in CRS format. The
126
+ dict must contain the keys "neighbors_index"
127
+ and "neighbors_row_splits." For descriptions
128
+ of the two, see NeighborSearch.
129
+ If batch > 1, the neighbors must be constant
130
+ across the entire batch.
131
+ x : torch.Tensor of shape [m, d2], default None
132
+ m points of dimension d2 over which the
133
+ output function is defined. If None,
134
+ x = y.
135
+ f_y : torch.Tensor of shape [batch, n, d3] or [n, d3], default None
136
+ Function to integrate the kernel against defined
137
+ on the points y. The kernel is assumed diagonal
138
+ hence its output shape must be d3 for the transforms
139
+ (b) or (d). If None, (a) is computed.
140
+ weights : torch.Tensor of shape [n,], default None
141
+ Weights for each point y proprtional to the
142
+ volume around f(y) being integrated. For example,
143
+ suppose d1=1 and let y_1 < y_2 < ... < y_{n+1}
144
+ be some points. Then, for a Riemann sum,
145
+ the weights are y_{j+1} - y_j. If None,
146
+ :math:`1/|A(x)|` is used.
147
+
148
+ Returns
149
+ -------
150
+ out_features : torch.Tensor of shape [batch, m, d4] or [m, d4]
151
+ Output function given on the points x.
152
+ d4 is the output size of the kernel k.
153
+ """
154
+
155
+ if x is None:
156
+ x = y
157
+
158
+ rep_features = y[neighbors["neighbors_index"]]
159
+
160
+ # batching only matters if f_y (latent embedding) values are provided
161
+ batched = False
162
+ # f_y has a batch dim IFF batched=True
163
+ if f_y is not None:
164
+ if f_y.ndim == 3:
165
+ batched = True
166
+ batch_size = f_y.shape[0]
167
+ in_features = f_y[:, neighbors["neighbors_index"], :]
168
+ elif f_y.ndim == 2:
169
+ batched = False
170
+ in_features = f_y[neighbors["neighbors_index"]]
171
+
172
+ num_reps = (
173
+ neighbors["neighbors_row_splits"][1:]
174
+ - neighbors["neighbors_row_splits"][:-1]
175
+ )
176
+
177
+ self_features = torch.repeat_interleave(x, num_reps, dim=0)
178
+
179
+ agg_features = torch.cat([rep_features, self_features], dim=-1)
180
+ if f_y is not None and (
181
+ self.transform_type == "nonlinear_kernelonly"
182
+ or self.transform_type == "nonlinear"
183
+ ):
184
+ if batched:
185
+ # repeat agg features for every example in the batch
186
+ agg_features = agg_features.repeat(
187
+ [batch_size] + [1] * agg_features.ndim
188
+ )
189
+ agg_features = torch.cat([agg_features, in_features], dim=-1)
190
+
191
+ rep_features = self.channel_mlp(agg_features)
192
+
193
+ if f_y is not None and self.transform_type != "nonlinear_kernelonly":
194
+ # if we have a batch of outputs (3d incl. batch dim) and unbatched inputs,
195
+ # create an identical batch dim in rep_features
196
+ if rep_features.ndim == 2 and batched:
197
+ rep_features = rep_features.unsqueeze(0).repeat([batch_size] + [1] * rep_features.ndim)
198
+ rep_features.mul_(in_features)
199
+
200
+ # Weight neighbors in each neighborhood, first according to the neighbor search (mollified GNO)
201
+ # and second according to individually-provided weights.
202
+ nbr_weights = neighbors.get("weights")
203
+ if nbr_weights is None:
204
+ nbr_weights = weights
205
+ if nbr_weights is None and self.weighting_fn is not None:
206
+ raise KeyError("if a weighting function is provided, your neighborhoods must contain weights.")
207
+ if nbr_weights is not None:
208
+ nbr_weights = nbr_weights.unsqueeze(-1).unsqueeze(0)
209
+ if self.weighting_fn is not None:
210
+ nbr_weights = self.weighting_fn(nbr_weights)
211
+ rep_features.mul_(nbr_weights)
212
+ reduction = "sum" # Force sum reduction for weighted GNO layers
213
+
214
+ else:
215
+ reduction = self.reduction
216
+
217
+ splits = neighbors["neighbors_row_splits"]
218
+ if batched:
219
+ splits = splits.unsqueeze(0).repeat([batch_size] + [1] * (splits.ndim))
220
+
221
+ out_features = segment_csr(
222
+ rep_features,
223
+ splits,
224
+ reduction=reduction,
225
+ use_scatter=self.use_torch_scatter,
226
+ )
227
+ return out_features
sources/neuraloperator/neuralop/layers/legacy_spectral_convolution.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ from ..utils import validate_scaling_factor
6
+
7
+ # Set warning filter to show each warning only once
8
+ import warnings
9
+
10
+ warnings.filterwarnings("once", category=UserWarning)
11
+
12
+ try:
13
+ from typing import Literal
14
+ except ImportError:
15
+ from typing_extensions import Literal
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ import tensorly as tl
21
+ from tensorly.plugins import use_opt_einsum
22
+ from tltorch.factorized_tensors.core import FactorizedTensor
23
+
24
+ from .einsum_utils import einsum_complexhalf
25
+ from .base_spectral_conv import BaseSpectralConv
26
+ from .resample import resample
27
+
28
+ tl.set_backend("pytorch")
29
+ use_opt_einsum("optimal")
30
+ einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
31
+
32
+
33
+ def _contract_dense(x, weight, separable=False):
34
+ order = tl.ndim(x)
35
+ # batch-size, in_channels, x, y...
36
+ x_syms = list(einsum_symbols[:order])
37
+
38
+ # in_channels, out_channels, x, y...
39
+ weight_syms = list(x_syms[1:]) # no batch-size
40
+
41
+ # batch-size, out_channels, x, y...
42
+ if separable:
43
+ out_syms = [x_syms[0]] + list(weight_syms)
44
+ else:
45
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
46
+ out_syms = list(weight_syms)
47
+ out_syms[0] = x_syms[0]
48
+
49
+ eq = f'{"".join(x_syms)},{"".join(weight_syms)}->{"".join(out_syms)}'
50
+
51
+ if not torch.is_tensor(weight):
52
+ weight = weight.to_tensor()
53
+
54
+ if x.dtype == torch.complex32:
55
+ # if x is half precision, run a specialized einsum
56
+ return einsum_complexhalf(eq, x, weight)
57
+ else:
58
+ return tl.einsum(eq, x, weight)
59
+
60
+
61
+ def _contract_dense_separable(x, weight, separable=True):
62
+ if not separable:
63
+ raise ValueError("This function is only for separable=True")
64
+ return x * weight
65
+
66
+
67
+ def _contract_cp(x, cp_weight, separable=False):
68
+ order = tl.ndim(x)
69
+
70
+ x_syms = str(einsum_symbols[:order])
71
+ rank_sym = einsum_symbols[order]
72
+ out_sym = einsum_symbols[order + 1]
73
+ out_syms = list(x_syms)
74
+ if separable:
75
+ factor_syms = [einsum_symbols[1] + rank_sym] # in only
76
+ else:
77
+ out_syms[1] = out_sym
78
+ factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out
79
+ factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ...
80
+ eq = f'{x_syms},{rank_sym},{",".join(factor_syms)}->{"".join(out_syms)}'
81
+
82
+ if x.dtype == torch.complex32:
83
+ return einsum_complexhalf(eq, x, cp_weight.weights, *cp_weight.factors)
84
+ else:
85
+ return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors)
86
+
87
+
88
+ def _contract_tucker(x, tucker_weight, separable=False):
89
+ order = tl.ndim(x)
90
+
91
+ x_syms = str(einsum_symbols[:order])
92
+ out_sym = einsum_symbols[order]
93
+ out_syms = list(x_syms)
94
+ if separable:
95
+ core_syms = einsum_symbols[order + 1 : 2 * order]
96
+ # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only
97
+ # x, y, ...
98
+ factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)]
99
+
100
+ else:
101
+ core_syms = einsum_symbols[order + 1 : 2 * order + 1]
102
+ out_syms[1] = out_sym
103
+ factor_syms = [
104
+ einsum_symbols[1] + core_syms[0],
105
+ out_sym + core_syms[1],
106
+ ] # out, in
107
+ # x, y, ...
108
+ factor_syms += [xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])]
109
+
110
+ eq = f'{x_syms},{core_syms},{",".join(factor_syms)}->{"".join(out_syms)}'
111
+
112
+ if x.dtype == torch.complex32:
113
+ return einsum_complexhalf(eq, x, tucker_weight.core, *tucker_weight.factors)
114
+ else:
115
+ return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors)
116
+
117
+
118
+ def _contract_tt(x, tt_weight, separable=False):
119
+ order = tl.ndim(x)
120
+
121
+ x_syms = list(einsum_symbols[:order])
122
+ weight_syms = list(x_syms[1:]) # no batch-size
123
+ if not separable:
124
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
125
+ out_syms = list(weight_syms)
126
+ out_syms[0] = x_syms[0]
127
+ else:
128
+ out_syms = list(x_syms)
129
+ rank_syms = list(einsum_symbols[order + 1 :])
130
+ tt_syms = []
131
+ for i, s in enumerate(weight_syms):
132
+ tt_syms.append([rank_syms[i], s, rank_syms[i + 1]])
133
+ eq = (
134
+ "".join(x_syms)
135
+ + ","
136
+ + ",".join("".join(f) for f in tt_syms)
137
+ + "->"
138
+ + "".join(out_syms)
139
+ )
140
+
141
+ if x.dtype == torch.complex32:
142
+ return einsum_complexhalf(eq, x, *tt_weight.factors)
143
+ else:
144
+ return tl.einsum(eq, x, *tt_weight.factors)
145
+
146
+
147
+ def get_contract_fun(weight, implementation="reconstructed", separable=False):
148
+ """Generic ND implementation of Fourier Spectral Conv contraction
149
+
150
+ Parameters
151
+ ----------
152
+ weight : tensorly-torch's FactorizedTensor
153
+ implementation : {'reconstructed', 'factorized'}, default is 'reconstructed'
154
+ whether to reconstruct the weight and do a forward pass (reconstructed)
155
+ or contract directly the factors of the factorized weight with the input (factorized)
156
+ separable : bool
157
+ whether to use the separable implementation of contraction. This arg is
158
+ only checked when `implementation=reconstructed`.
159
+
160
+ Returns
161
+ -------
162
+ function : (x, weight) -> x * weight in Fourier space
163
+ """
164
+ if implementation == "reconstructed":
165
+ if separable:
166
+ return _contract_dense_separable
167
+ else:
168
+ return _contract_dense
169
+ elif implementation == "factorized":
170
+ if torch.is_tensor(weight):
171
+ return _contract_dense
172
+ elif isinstance(weight, FactorizedTensor):
173
+ if weight.name.lower().endswith("dense"):
174
+ return _contract_dense
175
+ elif weight.name.lower().endswith("tucker"):
176
+ return _contract_tucker
177
+ elif weight.name.lower().endswith("tt"):
178
+ return _contract_tt
179
+ elif weight.name.lower().endswith("cp"):
180
+ return _contract_cp
181
+ else:
182
+ raise ValueError(f"Got unexpected factorized weight type {weight.name}")
183
+ else:
184
+ raise ValueError(
185
+ f"Got unexpected weight type of class {weight.__class__.__name__}"
186
+ )
187
+ else:
188
+ raise ValueError(
189
+ f'Got implementation={implementation}, expected "reconstructed" or "factorized"'
190
+ )
191
+
192
+
193
+ Number = Union[int, float]
194
+
195
+
196
+ class SpectralConv(BaseSpectralConv):
197
+ """Old implementation of the Spectral Convolution layer.
198
+
199
+ This implementation is deprecated and might be removed in future versions.
200
+
201
+ Parameters
202
+ ----------
203
+ in_channels : int, optional
204
+ Number of input channels
205
+ out_channels : int, optional
206
+ Number of output channels
207
+ n_modes : int tuple
208
+ total number of modes to keep in Fourier Layer, along each dim
209
+ separable : bool, default is True
210
+ init_std : float or 'auto', default is 'auto'
211
+ std to use for the init
212
+ n_layers : int, optional
213
+ Number of Fourier Layers, by default 4
214
+ incremental_n_modes : None or int tuple, default is None
215
+ * If not None, this allows to incrementally increase the number of modes
216
+ in Fourier domain during training. Has to verify n <= N for (n, m) in
217
+ zip(incremental_n_modes, n_modes).
218
+
219
+ * If None, all the n_modes are used.
220
+
221
+ This can be updated dynamically during training.
222
+ factorization : str or None, {'tucker', 'cp', 'tt'}, default is None
223
+ If None, a single dense weight is learned for the FNO.
224
+ Otherwise, that weight, used for the contraction in the Fourier domain
225
+ is learned in factorized form. In that case, `factorization` is the
226
+ tensor factorization of the parameters weight used.
227
+ joint_factorization : bool, optional
228
+ Whether all the Fourier Layers should be parametrized by a single tensor
229
+ (vs one per layer), by default False Ignored if ``factorization is None``
230
+ rank : float or rank, optional
231
+ Rank of the tensor factorization of the Fourier weights, by default 1.0
232
+ Ignored if ``factorization is None``
233
+ fixed_rank_modes : bool, optional
234
+ Modes to not factorize, by default False
235
+ Ignored if ``factorization is None``
236
+ fft_norm : str, optional
237
+ by default 'forward'
238
+ implementation : {'factorized', 'reconstructed'}, optional, default is 'factorized'
239
+ If factorization is not None, forward mode to use::
240
+ * `reconstructed` : the full weight tensor is reconstructed from the
241
+ factorization and used for the forward pass
242
+ * `factorized` : the input is directly contracted with the factors of
243
+ the decomposition
244
+ Ignored if ``factorization is None``
245
+ decomposition_kwargs : dict, optional, default is {}
246
+ Optionaly additional parameters to pass to the tensor decomposition
247
+ Ignored if ``factorization is None``
248
+ """
249
+
250
+ def __init__(
251
+ self,
252
+ in_channels,
253
+ out_channels,
254
+ n_modes,
255
+ incremental_n_modes=None,
256
+ bias=True,
257
+ n_layers=1,
258
+ separable=False,
259
+ resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None,
260
+ fno_block_precision="full",
261
+ rank=0.5,
262
+ factorization=None,
263
+ implementation="reconstructed",
264
+ fixed_rank_modes=False,
265
+ joint_factorization=False,
266
+ decomposition_kwargs: Optional[dict] = None,
267
+ init_std="auto",
268
+ fft_norm="backward",
269
+ device=None,
270
+ dtype=None,
271
+ ):
272
+ super().__init__(dtype=dtype, device=device)
273
+
274
+ self.in_channels = in_channels
275
+ self.out_channels = out_channels
276
+ self.joint_factorization = joint_factorization
277
+
278
+ # We index quadrands only
279
+ # n_modes is the total number of modes kept along each dimension
280
+ # half_n_modes is half of that except in the last mode, correponding to
281
+ # the number of modes to keep in *each* quadrant for each dim
282
+ if isinstance(n_modes, int):
283
+ n_modes = [n_modes]
284
+ self.n_modes = n_modes
285
+ self.order = len(n_modes)
286
+
287
+ half_total_n_modes = [m // 2 for m in n_modes]
288
+ self.half_total_n_modes = half_total_n_modes
289
+
290
+ # We use half_total_n_modes to build the full weights
291
+ # During training we can adjust incremental_n_modes which will also
292
+ # update half_n_modes
293
+ # So that we can train on a smaller part of the Fourier modes and total
294
+ # weights
295
+ self.incremental_n_modes = incremental_n_modes
296
+
297
+ self.fno_block_precision = fno_block_precision
298
+ self.rank = rank
299
+ self.factorization = factorization
300
+ self.n_layers = n_layers
301
+ self.implementation = implementation
302
+
303
+ self.resolution_scaling_factor: Union[
304
+ None, List[List[float]]
305
+ ] = validate_scaling_factor(resolution_scaling_factor, self.order, n_layers)
306
+
307
+ if init_std == "auto":
308
+ init_std = (2 / (in_channels + out_channels)) ** 0.5
309
+
310
+ if isinstance(fixed_rank_modes, bool):
311
+ if fixed_rank_modes:
312
+ # If bool, keep the number of layers fixed
313
+ fixed_rank_modes = [0]
314
+ else:
315
+ fixed_rank_modes = None
316
+ self.fft_norm = fft_norm
317
+
318
+ # Make sure we are using a Complex Factorized Tensor to parametrize the
319
+ # conv
320
+ if factorization is None:
321
+ factorization = "Dense" # No factorization
322
+ if not factorization.lower().startswith("complex"):
323
+ factorization = f"Complex{factorization}"
324
+
325
+ if separable:
326
+ if in_channels != out_channels:
327
+ raise ValueError(
328
+ "To use separable Fourier Conv, in_channels must be equal "
329
+ f"to out_channels, but got in_channels={in_channels} and "
330
+ f"out_channels={out_channels}",
331
+ )
332
+ weight_shape = (in_channels, *half_total_n_modes)
333
+ else:
334
+ weight_shape = (in_channels, out_channels, *half_total_n_modes)
335
+ self.separable = separable
336
+
337
+ self.n_weights_per_layer = 2 ** (self.order - 1)
338
+ tensor_kwargs = decomposition_kwargs if decomposition_kwargs is not None else {}
339
+ if joint_factorization:
340
+ self.weight = FactorizedTensor.new(
341
+ (self.n_weights_per_layer * n_layers, *weight_shape),
342
+ rank=self.rank,
343
+ factorization=factorization,
344
+ fixed_rank_modes=fixed_rank_modes,
345
+ **tensor_kwargs,
346
+ )
347
+ self.weight.normal_(0, init_std)
348
+ else:
349
+ self.weight = nn.ModuleList(
350
+ [
351
+ FactorizedTensor.new(
352
+ weight_shape,
353
+ rank=self.rank,
354
+ factorization=factorization,
355
+ fixed_rank_modes=fixed_rank_modes,
356
+ **tensor_kwargs,
357
+ )
358
+ for _ in range(self.n_weights_per_layer * n_layers)
359
+ ]
360
+ )
361
+ for w in self.weight:
362
+ w.normal_(0, init_std)
363
+ self._contract = get_contract_fun(
364
+ self.weight[0], implementation=implementation, separable=separable
365
+ )
366
+
367
+ if bias:
368
+ self.bias = nn.Parameter(
369
+ init_std
370
+ * torch.randn(*((n_layers, self.out_channels) + (1,) * self.order))
371
+ )
372
+ else:
373
+ self.bias = None
374
+
375
+ def _get_weight(self, index):
376
+ if self.incremental_n_modes is not None:
377
+ return self.weight[index][self.weight_slices]
378
+ else:
379
+ return self.weight[index]
380
+
381
+ @property
382
+ def incremental_n_modes(self):
383
+ return self._incremental_n_modes
384
+
385
+ @incremental_n_modes.setter
386
+ def incremental_n_modes(self, incremental_n_modes):
387
+ if incremental_n_modes is None:
388
+ self._incremental_n_modes = None
389
+ self.half_n_modes = [m // 2 for m in self.n_modes]
390
+
391
+ else:
392
+ if isinstance(incremental_n_modes, int):
393
+ self._incremental_n_modes = [incremental_n_modes] * len(self.n_modes)
394
+ else:
395
+ if len(incremental_n_modes) == len(self.n_modes):
396
+ self._incremental_n_modes = incremental_n_modes
397
+ else:
398
+ raise ValueError(
399
+ f"Provided {incremental_n_modes} for actual "
400
+ f"n_modes={self.n_modes}."
401
+ )
402
+ self.weight_slices = [slice(None)] * 2 + [
403
+ slice(None, n // 2) for n in self._incremental_n_modes
404
+ ]
405
+ self.half_n_modes = [m // 2 for m in self._incremental_n_modes]
406
+
407
+ def transform(self, x, layer_index=0, output_shape=None):
408
+ in_shape = list(x.shape[2:])
409
+
410
+ if self.resolution_scaling_factor is not None and output_shape is None:
411
+ out_shape = tuple(
412
+ [
413
+ round(s * r)
414
+ for (s, r) in zip(in_shape, self.resolution_scaling_factor[layer_index])
415
+ ]
416
+ )
417
+ elif output_shape is not None:
418
+ out_shape = output_shape
419
+ else:
420
+ out_shape = in_shape
421
+
422
+ if in_shape == out_shape:
423
+ return x
424
+ else:
425
+ return resample(
426
+ x,
427
+ 1.0,
428
+ list(range(2, x.ndim)),
429
+ output_shape=out_shape,
430
+ )
431
+
432
+ def forward(
433
+ self, x: torch.Tensor, indices=0, output_shape: Optional[Tuple[int]] = None
434
+ ):
435
+ """Generic forward pass for the Factorized Spectral Conv
436
+
437
+ Parameters
438
+ ----------
439
+ x : torch.Tensor
440
+ input activation of size (batch_size, channels, d1, ..., dN)
441
+ indices : int, default is 0
442
+ if joint_factorization, index of the layers for n_layers > 1
443
+
444
+ Returns
445
+ -------
446
+ tensorized_spectral_conv(x)
447
+ """
448
+ batchsize, channels, *mode_sizes = x.shape
449
+
450
+ fft_size = list(mode_sizes)
451
+ fft_size[-1] = fft_size[-1] // 2 + 1 # Redundant last coefficient
452
+
453
+ # Compute Fourier coeffcients
454
+ fft_dims = list(range(-self.order, 0))
455
+
456
+ if self.fno_block_precision == "half":
457
+ x = x.half()
458
+
459
+ x = torch.fft.rfftn(x, norm=self.fft_norm, dim=fft_dims)
460
+
461
+ if self.fno_block_precision == "mixed":
462
+ # if 'mixed', the above fft runs in full precision, but the
463
+ # following operations run at half precision
464
+ x = x.chalf()
465
+
466
+ if self.fno_block_precision in ["half", "mixed"]:
467
+ out_fft = torch.zeros(
468
+ [batchsize, self.out_channels, *fft_size],
469
+ device=x.device,
470
+ dtype=torch.chalf,
471
+ )
472
+ else:
473
+ out_fft = torch.zeros(
474
+ [batchsize, self.out_channels, *fft_size],
475
+ device=x.device,
476
+ dtype=torch.cfloat,
477
+ )
478
+
479
+ # We contract all corners of the Fourier coefs
480
+ # Except for the last mode: there, we take all coefs as redundant modes
481
+ # were already removed
482
+ mode_indexing = [((None, m), (-m, None)) for m in self.half_n_modes[:-1]] + [
483
+ ((None, self.half_n_modes[-1]),)
484
+ ]
485
+
486
+ for i, boundaries in enumerate(itertools.product(*mode_indexing)):
487
+ # Keep all modes for first 2 modes (batch-size and channels)
488
+ idx_tuple = [slice(None), slice(None)] + [slice(*b) for b in boundaries]
489
+
490
+ # For 2D: [:, :, :height, :width] and [:, :, -height:, width]
491
+ out_fft[idx_tuple] = self._contract(
492
+ x[idx_tuple],
493
+ self._get_weight(self.n_weights_per_layer * indices + i),
494
+ separable=self.separable,
495
+ )
496
+
497
+ if self.resolution_scaling_factor is not None and output_shape is None:
498
+ mode_sizes = tuple(
499
+ [
500
+ round(s * r)
501
+ for (s, r) in zip(mode_sizes, self.resolution_scaling_factor[indices])
502
+ ]
503
+ )
504
+
505
+ if output_shape is not None:
506
+ mode_sizes = output_shape
507
+
508
+ x = torch.fft.irfftn(out_fft, s=mode_sizes, norm=self.fft_norm)
509
+
510
+ if self.bias is not None:
511
+ x = x + self.bias[indices, ...]
512
+
513
+ return x
514
+
515
+ def get_conv(self, indices):
516
+ """Returns a sub-convolutional layer from the joint parametrize main-convolution
517
+
518
+ The parametrization of sub-convolutional layers is shared with the main one.
519
+ """
520
+ if self.n_layers == 1:
521
+ Warning("A single convolution is parametrized, directly use the main class.")
522
+ # raise ValueError(
523
+ # "A single convolution is parametrized, directly use the main class."
524
+ # )
525
+
526
+ return SubConv(self, indices)
527
+
528
+ def __getitem__(self, indices):
529
+ return self.get_conv(indices)
530
+
531
+
532
+ class SubConv(nn.Module):
533
+ """Class representing one of the convolutions from the mother joint
534
+ factorized convolution.
535
+
536
+ Notes
537
+ -----
538
+ This relies on the fact that nn.Parameters are not duplicated:
539
+ if the same nn.Parameter is assigned to multiple modules, they all point to
540
+ the same data, which is shared.
541
+ """
542
+
543
+ def __init__(self, main_conv, indices):
544
+ super().__init__()
545
+ self.main_conv = main_conv
546
+ self.indices = indices
547
+
548
+ def forward(self, x, **kwargs):
549
+ if kwargs:
550
+ warnings.warn(
551
+ f"SpectralConvWrapper.forward() received unexpected keyword arguments: {list(kwargs.keys())}. "
552
+ "These arguments will be ignored.",
553
+ UserWarning,
554
+ stacklevel=2,
555
+ )
556
+ return self.main_conv.forward(x, self.indices, **kwargs)
557
+
558
+ def transform(self, x, **kwargs):
559
+ if kwargs:
560
+ warnings.warn(
561
+ f"SpectralConvWrapper.transform() received unexpected keyword arguments: {list(kwargs.keys())}. "
562
+ "These arguments will be ignored.",
563
+ UserWarning,
564
+ stacklevel=2,
565
+ )
566
+ return self.main_conv.transform(x, self.indices, **kwargs)
567
+
568
+ @property
569
+ def weight(self):
570
+ return self.main_conv.get_weight(indices=self.indices)
571
+
572
+
573
+ class SpectralConv1d(SpectralConv):
574
+ """1D Spectral Conv
575
+
576
+ This is provided for reference only,
577
+ see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation
578
+ """
579
+
580
+ def forward(self, x, indices=0):
581
+ batchsize, channels, width = x.shape
582
+
583
+ x = torch.fft.rfft(x, norm=self.fft_norm)
584
+
585
+ out_fft = torch.zeros(
586
+ [batchsize, self.out_channels, width // 2 + 1],
587
+ device=x.device,
588
+ dtype=torch.cfloat,
589
+ )
590
+ slices = (
591
+ slice(None), # Equivalent to: [:,
592
+ slice(None), # ............... :,
593
+ slice(self.half_n_modes[0]), # :half_n_modes[0]]
594
+ )
595
+ out_fft[slices] = self._contract(
596
+ x[slices], self._get_weight(indices), separable=self.separable
597
+ )
598
+
599
+ if self.resolution_scaling_factor is not None:
600
+ width = round(width * self.resolution_scaling_factor[0])
601
+
602
+ x = torch.fft.irfft(out_fft, n=width, norm=self.fft_norm)
603
+
604
+ if self.bias is not None:
605
+ x = x + self.bias[indices, ...]
606
+
607
+ return x
608
+
609
+
610
+ class SpectralConv2d(SpectralConv):
611
+ """2D Spectral Conv, see :class:`neuralop.layers.SpectraConv` for the general case
612
+
613
+ This is provided for reference only,
614
+ see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation
615
+ """
616
+
617
+ def forward(self, x, indices=0):
618
+ batchsize, channels, height, width = x.shape
619
+
620
+ x = torch.fft.rfft2(x.float(), norm=self.fft_norm)
621
+
622
+ # The output will be of size (batch_size, self.out_channels,
623
+ # x.size(-2), x.size(-1)//2 + 1)
624
+ out_fft = torch.zeros(
625
+ [batchsize, self.out_channels, height, width // 2 + 1],
626
+ dtype=x.dtype,
627
+ device=x.device,
628
+ )
629
+
630
+ slices0 = (
631
+ slice(None), # Equivalent to: [:,
632
+ slice(None), # ............... :,
633
+ slice(self.half_n_modes[0]), # :half_n_modes[0],
634
+ slice(self.half_n_modes[1]), # :half_n_modes[1]]
635
+ )
636
+ """Upper block (truncate high frequencies)."""
637
+ out_fft[slices0] = self._contract(
638
+ x[slices0], self._get_weight(2 * indices), separable=self.separable
639
+ )
640
+
641
+ slices1 = (
642
+ slice(None), # Equivalent to: [:,
643
+ slice(None), # ...................... :,
644
+ slice(-self.half_n_modes[0], None), # -half_n_modes[0]:,
645
+ slice(self.half_n_modes[1]), # ...... :half_n_modes[1]]
646
+ )
647
+ """Lower block"""
648
+ out_fft[slices1] = self._contract(
649
+ x[slices1], self._get_weight(2 * indices + 1), separable=self.separable
650
+ )
651
+
652
+ if self.resolution_scaling_factor is not None:
653
+ width = round(width * self.resolution_scaling_factor[indices][0])
654
+ height = round(height * self.resolution_scaling_factor[indices][1])
655
+
656
+ x = torch.fft.irfft2(
657
+ out_fft, s=(height, width), dim=(-2, -1), norm=self.fft_norm
658
+ )
659
+
660
+ if self.bias is not None:
661
+ x = x + self.bias[indices, ...]
662
+
663
+ return x
664
+
665
+
666
+ class SpectralConv3d(SpectralConv):
667
+ """3D Spectral Conv, see :class:`neuralop.layers.SpectraConv` for the general case
668
+
669
+ This is provided for reference only,
670
+ see :class:`neuralop.layers.SpectraConv` for the preferred, general implementation
671
+ """
672
+
673
+ def forward(self, x, indices=0):
674
+ batchsize, channels, height, width, depth = x.shape
675
+
676
+ x = torch.fft.rfftn(x.float(), norm=self.fft_norm, dim=[-3, -2, -1])
677
+
678
+ out_fft = torch.zeros(
679
+ [batchsize, self.out_channels, height, width, depth // 2 + 1],
680
+ device=x.device,
681
+ dtype=torch.cfloat,
682
+ )
683
+
684
+ slices0 = (
685
+ slice(None), # Equivalent to: [:,
686
+ slice(None), # ............... :,
687
+ slice(self.half_n_modes[0]), # :half_n_modes[0],
688
+ slice(self.half_n_modes[1]), # :half_n_modes[1],
689
+ slice(self.half_n_modes[2]), # :half_n_modes[2]]
690
+ )
691
+ """Upper block -- truncate high frequencies."""
692
+ out_fft[slices0] = self._contract(
693
+ x[slices0], self._get_weight(4 * indices + 0), separable=self.separable
694
+ )
695
+
696
+ slices1 = (
697
+ slice(None), # Equivalent to: [:,
698
+ slice(None), # ...................... :,
699
+ slice(self.half_n_modes[0]), # ...... :half_n_modes[0],
700
+ slice(-self.half_n_modes[1], None), # -half_n_modes[1]:,
701
+ slice(self.half_n_modes[2]), # ...... :half_n_modes[0]]
702
+ )
703
+ """Low-pass filter for indices 2 & 4, and high-pass filter for index 3."""
704
+ out_fft[slices1] = self._contract(
705
+ x[slices1], self._get_weight(4 * indices + 1), separable=self.separable
706
+ )
707
+
708
+ slices2 = (
709
+ slice(None), # Equivalent to: [:,
710
+ slice(None), # ...................... :,
711
+ slice(-self.half_n_modes[0], None), # -half_n_modes[0]:,
712
+ slice(self.half_n_modes[1]), # ...... :half_n_modes[1],
713
+ slice(self.half_n_modes[2]), # ...... :half_n_modes[2]]
714
+ )
715
+ """Low-pass filter for indices 3 & 4, and high-pass filter for index 2."""
716
+ out_fft[slices2] = self._contract(
717
+ x[slices2], self._get_weight(4 * indices + 2), separable=self.separable
718
+ )
719
+
720
+ slices3 = (
721
+ slice(None), # Equivalent to: [:,
722
+ slice(None), # ...................... :,
723
+ slice(-self.half_n_modes[0], None), # -half_n_modes[0],
724
+ slice(-self.half_n_modes[1], None), # -half_n_modes[1],
725
+ slice(self.half_n_modes[2]), # ...... :half_n_modes[2]]
726
+ )
727
+ """Lower block -- low-cut filter in indices 2 & 3
728
+ and high-cut filter in index 4."""
729
+ out_fft[slices3] = self._contract(
730
+ x[slices3], self._get_weight(4 * indices + 3), separable=self.separable
731
+ )
732
+
733
+ if self.resolution_scaling_factor is not None:
734
+ width = round(width * self.resolution_scaling_factor[0])
735
+ height = round(height * self.resolution_scaling_factor[1])
736
+ depth = round(depth * self.resolution_scaling_factor[2])
737
+
738
+ x = torch.fft.irfftn(out_fft, s=(height, width, depth), norm=self.fft_norm)
739
+
740
+ if self.bias is not None:
741
+ x = x + self.bias[indices, ...]
742
+ return x
sources/neuraloperator/neuralop/layers/local_no_block.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Union
2
+ import warnings
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+
8
+ from .channel_mlp import ChannelMLP
9
+ from .fno_block import SubModule
10
+ from .differential_conv import FiniteDifferenceConvolution
11
+ from .discrete_continuous_convolution import EquidistantDiscreteContinuousConv2d
12
+ from .normalization_layers import AdaIN, InstanceNorm
13
+ from .skip_connections import skip_connection
14
+ from .spectral_convolution import SpectralConv
15
+ from ..utils import validate_scaling_factor
16
+
17
+
18
+ Number = Union[int, float]
19
+
20
+
21
+ class LocalNOBlocks(nn.Module):
22
+ """Local Neural Operator blocks with localized integral and differential kernels.
23
+
24
+ It is implemented as described in [3]_.
25
+
26
+ This class implements neural operator blocks that combine Fourier neural operators
27
+ with localized integral and differential kernels to capture both global and local
28
+ features in PDE solutions [3]_. The architecture addresses the over-smoothing limitations
29
+ of purely global FNOs while maintaining resolution-independence through principled
30
+ local operations.
31
+
32
+ The key innovation is the integration of two types of local operations:
33
+ 1. Differential kernels: Learn finite difference stencils that converge to
34
+ differential operators under appropriate scaling.
35
+ 2. Local integral kernels: Use discrete-continuous convolutions with locally
36
+ supported kernels to capture local interactions.
37
+
38
+ Parameters
39
+ ----------
40
+ in_channels : int
41
+ Number of input channels to Fourier layers
42
+ out_channels : int
43
+ Number of output channels after Fourier layers
44
+ n_modes : int, List[int]
45
+ Number of modes to keep along each dimension in frequency space.
46
+ Can either be specified as an int (for all dimensions)
47
+ or an iterable with one number per dimension
48
+ default_in_shape : Tuple[int]
49
+ Default input shape for spatiotemporal dimensions
50
+ resolution_scaling_factor : Optional[Union[Number, List[Number]]], optional
51
+ Factor by which to scale outputs for super-resolution, by default None
52
+ n_layers : int, optional
53
+ Number of neural operator layers to apply in sequence, by default 1
54
+ disco_layers : bool or List[bool], optional
55
+ Whether to include local integral kernel connections at each layer.
56
+ If a single bool, applies to all layers. If a list, must match n_layers.
57
+ disco_kernel_shape : Union[int, List[int]], optional
58
+ Kernel shape for local integral operations. Single int for isotropic kernels,
59
+ two ints for anisotropic kernels, by default [2,4]
60
+ domain_length : torch.Tensor, optional
61
+ Physical domain extent/length. Assumes square domain [-1, 1]^2 by default
62
+ disco_groups : int, optional
63
+ Number of groups in local integral convolution, by default 1
64
+ disco_bias : bool, optional
65
+ Whether to use bias for integral kernel, by default True
66
+ radius_cutoff : float, optional
67
+ Cutoff radius (relative to domain_length) for local integral kernel, by default None
68
+ diff_layers : bool or List[bool], optional
69
+ Whether to include differential kernel connections at each layer.
70
+ If a single bool, applies to all layers. If a list, must match n_layers.
71
+ conv_padding_mode : str, optional
72
+ Padding mode for spatial convolution kernels.
73
+ Options: 'periodic', 'circular', 'replicate', 'reflect', 'zeros'. By default 'periodic'
74
+ fin_diff_kernel_size : int, optional
75
+ Kernel size for finite difference convolution (must be odd), by default 3
76
+ mix_derivatives : bool, optional
77
+ Whether to mix derivatives across channels, by default True
78
+ max_n_modes : int or List[int], optional
79
+ Maximum number of modes to keep along each dimension, by default None
80
+ local_no_block_precision : str, optional
81
+ Floating point precision for computations, by default "full"
82
+ use_channel_mlp : bool, optional
83
+ Whether to use MLP layer after each block, by default False
84
+ channel_mlp_dropout : int, optional
85
+ Dropout parameter for channel MLP, by default 0
86
+ channel_mlp_expansion : float, optional
87
+ Expansion factor for channel MLP, by default 0.5
88
+ non_linearity : torch.nn.F module, optional
89
+ Nonlinear activation function between layers, by default F.gelu
90
+ stabilizer : Literal["tanh"], optional
91
+ Stabilizing module between layers. Options: "tanh". By default None
92
+ norm : Literal["ada_in", "group_norm", "instance_norm"], optional
93
+ Normalization layer to use, by default None
94
+ norm_groups : int, optional
95
+ Number of groups for GroupNorm, by default 1
96
+ ada_in_features : int, optional
97
+ Number of features for adaptive instance normalization, by default None
98
+ preactivation : bool, optional
99
+ Whether to call forward pass with pre-activation, by default False
100
+ if True, call nonlinear activation and norm before Fourier convolution
101
+ if False, call activation and norms after Fourier convolutions
102
+ local_no_skip : str, optional
103
+ Module to use for Local NO skip connections, by default "linear"
104
+ Options: "linear", "identity", "soft-gating", None.
105
+ If None, no skip connection is added. See layers.skip_connections for more details
106
+ channel_mlp_skip : str, optional
107
+ Module to use for ChannelMLP skip connections, by default "soft-gating"
108
+ Options: "linear", "identity", "soft-gating", None.
109
+ If None, no skip connection is added. See layers.skip_connections for more details
110
+
111
+ Other Parameters
112
+ ----------------
113
+ complex_data : bool, optional
114
+ Whether the data takes complex values in space, by default False
115
+ separable : bool, optional
116
+ Separable parameter for SpectralConv, by default False
117
+ factorization : str, optional
118
+ Factorization method for SpectralConv, by default None
119
+ Options: "factorized", "reconstructed".
120
+ rank : float, optional
121
+ Rank parameter for SpectralConv, by default 1.0
122
+ conv_module : BaseConv, optional
123
+ Convolution module for Local NO block, by default SpectralConv
124
+ joint_factorization : bool, optional
125
+ Whether to factorize all SpectralConv weights as one tensor, by default False
126
+ fixed_rank_modes : bool, optional
127
+ Fixed rank modes parameter for SpectralConv, by default False
128
+ implementation : str, optional
129
+ Implementation method for SpectralConv, by default "factorized"
130
+ decomposition_kwargs : dict, optional
131
+ Keyword arguments for tensor decomposition in SpectralConv, by default dict()
132
+ enforce_hermitian_symmetry : bool, optional
133
+ Whether to enforce Hermitian symmetry conditions when performing inverse FFT
134
+ for real-valued data. Only used when ``conv_module`` is :class:`SpectralConv`
135
+ or a subclass; ignored otherwise. When True, explicitly enforces that the 0th
136
+ frequency and Nyquist frequency are real-valued before calling irfft. When False,
137
+ relies on cuFFT's irfftn to handle symmetry automatically, which may fail on
138
+ certain GPUs or input sizes, causing line artifacts. By default True.
139
+
140
+ Notes
141
+ -----
142
+ - Differential kernels are only implemented for dimensions ≤ 3
143
+ - Local integral kernels are only implemented for 2D domains
144
+
145
+ References
146
+ ----------
147
+ .. [1] Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential
148
+ Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895.
149
+ .. [2] Kossaifi, J., Kovachki, N., Azizzadenesheli, K., Anandkumar, A. "Multi-Grid
150
+ Tensorized Fourier Neural Operator for High-Resolution PDEs" (2024).
151
+ TMLR 2024, https://openreview.net/pdf?id=AWiDlO63bH.
152
+ .. [3] Liu-Schiaffini M., Berner J., Bonev B., Kurth T., Azizzadenesheli K., Anandkumar A.;
153
+ "Neural Operators with Localized Integral and Differential Kernels" (2024).
154
+ ICML 2024, https://arxiv.org/pdf/2402.16845.
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ in_channels,
160
+ out_channels,
161
+ n_modes,
162
+ default_in_shape,
163
+ resolution_scaling_factor=None,
164
+ n_layers=1,
165
+ disco_layers=True,
166
+ disco_kernel_shape=[2, 4],
167
+ radius_cutoff=None,
168
+ domain_length=[2, 2],
169
+ disco_groups=1,
170
+ disco_bias=True,
171
+ diff_layers=True,
172
+ conv_padding_mode="periodic",
173
+ fin_diff_kernel_size=3,
174
+ mix_derivatives=True,
175
+ max_n_modes=None,
176
+ local_no_block_precision="full",
177
+ use_channel_mlp=False,
178
+ channel_mlp_dropout=0,
179
+ channel_mlp_expansion=0.5,
180
+ non_linearity=F.gelu,
181
+ stabilizer=None,
182
+ norm=None,
183
+ norm_groups=1,
184
+ ada_in_features=None,
185
+ preactivation=False,
186
+ local_no_skip="linear",
187
+ channel_mlp_skip="soft-gating",
188
+ separable=False,
189
+ factorization=None,
190
+ rank=1.0,
191
+ conv_module=SpectralConv,
192
+ fixed_rank_modes=False,
193
+ implementation="factorized",
194
+ decomposition_kwargs=dict(),
195
+ fft_norm="forward",
196
+ enforce_hermitian_symmetry=True,
197
+ ):
198
+ super().__init__()
199
+ if isinstance(n_modes, int):
200
+ n_modes = [n_modes]
201
+ self._n_modes = n_modes
202
+
203
+ assert len(n_modes) == len(default_in_shape), "Spatiotemporal dimensions must be consistent"
204
+
205
+ # If a single bool is passed for disco_layers or diff_layers, set values for all layers
206
+ if isinstance(disco_layers, bool):
207
+ disco_layers = [disco_layers] * n_layers
208
+ if isinstance(diff_layers, bool):
209
+ diff_layers = [diff_layers] * n_layers
210
+
211
+ if len(n_modes) > 3 and True in diff_layers:
212
+ raise NotImplementedError("Differential convs not implemented for dimensions higher than 3.")
213
+
214
+ if len(n_modes) != 2 and True in disco_layers:
215
+ raise NotImplementedError("Local conv layers only implemented for dimension 2.")
216
+
217
+ if conv_padding_mode not in ['circular', 'periodic', 'zeros'] and True in disco_layers:
218
+ warnings.warn("Local conv layers only support periodic or zero padding, defaulting to zero padding for local convs.")
219
+
220
+ self.n_dim = len(n_modes)
221
+
222
+ self.resolution_scaling_factor: Union[
223
+ None, List[List[float]]
224
+ ] = validate_scaling_factor(resolution_scaling_factor, self.n_dim, n_layers)
225
+
226
+ self.max_n_modes = max_n_modes
227
+ self.local_no_block_precision = local_no_block_precision
228
+ self.in_channels = in_channels
229
+ self.out_channels = out_channels
230
+ self.n_layers = n_layers
231
+ self.non_linearity = non_linearity
232
+ self.stabilizer = stabilizer
233
+ self.rank = rank
234
+ self.factorization = factorization
235
+ self.fixed_rank_modes = fixed_rank_modes
236
+ self.decomposition_kwargs = decomposition_kwargs
237
+ self.local_no_skip = local_no_skip
238
+ self.channel_mlp_skip = channel_mlp_skip
239
+ self.use_channel_mlp = use_channel_mlp
240
+ self.channel_mlp_expansion = channel_mlp_expansion
241
+ self.channel_mlp_dropout = channel_mlp_dropout
242
+ self.fft_norm = fft_norm
243
+ self.implementation = implementation
244
+ self.separable = separable
245
+ self.preactivation = preactivation
246
+ self.ada_in_features = ada_in_features
247
+ self.enforce_hermitian_symmetry = enforce_hermitian_symmetry
248
+
249
+ self.diff_layers = diff_layers
250
+ self.conv_padding_mode = conv_padding_mode
251
+ self.default_in_shape = default_in_shape
252
+ self.fin_diff_kernel_size = fin_diff_kernel_size
253
+ self.mix_derivatives = mix_derivatives
254
+
255
+ self.disco_layers = disco_layers
256
+ self.disco_kernel_shape = disco_kernel_shape
257
+ self.radius_cutoff = radius_cutoff
258
+ self.domain_length = domain_length
259
+ self.disco_groups = disco_groups
260
+ self.disco_bias = disco_bias
261
+ self.periodic = self.conv_padding_mode in ["circular", "periodic"]
262
+
263
+ assert (
264
+ len(diff_layers) == n_layers
265
+ ), f"diff_layers must either provide a single bool value or a list of booleans of length n_layers,\
266
+ got {len(diff_layers)=}"
267
+ assert (
268
+ len(disco_layers) == n_layers
269
+ ), f"disco_layers must either provide a single bool value or a list of booleans of length n_layers,\
270
+ got {len(disco_layers)=}"
271
+
272
+ # One conv per layer. Only resolution_scaling_factor varies by layer index
273
+ self.convs = nn.ModuleList(
274
+ [
275
+ conv_module(
276
+ self.in_channels,
277
+ self.out_channels,
278
+ self.n_modes,
279
+ # Per-layer scaling for super-resolution, or None if disabled
280
+ resolution_scaling_factor=(
281
+ self.resolution_scaling_factor[i]
282
+ if resolution_scaling_factor is not None
283
+ else None
284
+ ),
285
+ max_n_modes=max_n_modes,
286
+ rank=rank,
287
+ fixed_rank_modes=fixed_rank_modes,
288
+ implementation=implementation,
289
+ separable=separable,
290
+ factorization=factorization,
291
+ decomposition_kwargs=decomposition_kwargs,
292
+ # Only SpectralConv (and subclasses) accept enforce_hermitian_symmetry. Others ignore it
293
+ **(
294
+ {"enforce_hermitian_symmetry": enforce_hermitian_symmetry}
295
+ if issubclass(conv_module, SpectralConv)
296
+ else {}
297
+ ),
298
+ )
299
+ for i in range(n_layers)
300
+ ]
301
+ )
302
+
303
+ if local_no_skip is not None:
304
+ self.local_no_skips = nn.ModuleList(
305
+ [
306
+ skip_connection(
307
+ self.in_channels,
308
+ self.out_channels,
309
+ skip_type=local_no_skip,
310
+ n_dim=self.n_dim,
311
+ )
312
+ for _ in range(n_layers)
313
+ ]
314
+ )
315
+ else:
316
+ self.local_no_skips = None
317
+
318
+ self.diff_groups = 1 if mix_derivatives else in_channels
319
+ self.differential = nn.ModuleList(
320
+ [
321
+ FiniteDifferenceConvolution(
322
+ self.in_channels,
323
+ self.out_channels,
324
+ self.n_dim,
325
+ self.fin_diff_kernel_size,
326
+ self.diff_groups,
327
+ self.conv_padding_mode,
328
+ )
329
+ for _ in range(sum(self.diff_layers))
330
+ ]
331
+ )
332
+
333
+ self.local_convs = nn.ModuleList(
334
+ [
335
+ EquidistantDiscreteContinuousConv2d(
336
+ self.in_channels,
337
+ self.out_channels,
338
+ in_shape=self.default_in_shape,
339
+ out_shape=self.default_in_shape,
340
+ kernel_shape=self.disco_kernel_shape,
341
+ domain_length=self.domain_length,
342
+ radius_cutoff=self.radius_cutoff,
343
+ periodic=self.periodic,
344
+ groups=self.disco_groups,
345
+ bias=self.disco_bias,
346
+ )
347
+ for _ in range(sum(self.disco_layers))
348
+ ]
349
+ )
350
+
351
+ # Helper for calling differential layers
352
+ self.differential_idx_list = []
353
+ j = 0
354
+ for i in range(n_layers):
355
+ if self.diff_layers[i]:
356
+ self.differential_idx_list.append(j)
357
+ j += 1
358
+ else:
359
+ self.differential_idx_list.append(-1)
360
+
361
+ assert max(self.differential_idx_list) == sum(self.diff_layers) - 1
362
+
363
+ # Helper for calling local conv layers
364
+ self.disco_idx_list = []
365
+ j = 0
366
+ for i in range(n_layers):
367
+ if self.disco_layers[i]:
368
+ self.disco_idx_list.append(j)
369
+ j += 1
370
+ else:
371
+ self.disco_idx_list.append(-1)
372
+
373
+ assert max(self.disco_idx_list) == sum(self.disco_layers) - 1
374
+
375
+ if use_channel_mlp:
376
+ self.mlp = nn.ModuleList(
377
+ [
378
+ ChannelMLP(
379
+ in_channels=self.out_channels,
380
+ hidden_channels=round(self.out_channels * channel_mlp_expansion),
381
+ dropout=channel_mlp_dropout,
382
+ n_dim=self.n_dim,
383
+ )
384
+ for _ in range(n_layers)
385
+ ]
386
+ )
387
+ if channel_mlp_skip is not None:
388
+ self.channel_mlp_skips = nn.ModuleList(
389
+ [
390
+ skip_connection(
391
+ self.in_channels,
392
+ self.out_channels,
393
+ skip_type=channel_mlp_skip,
394
+ n_dim=self.n_dim,
395
+ )
396
+ for _ in range(n_layers)
397
+ ]
398
+ )
399
+ else:
400
+ self.channel_mlp_skips = None
401
+ else:
402
+ self.mlp = None
403
+
404
+ # Each block will have 2 norms if we also use an MLP
405
+ self.n_norms = 1 if self.mlp is None else 2
406
+ if norm is None:
407
+ self.norm = None
408
+ elif norm == "instance_norm":
409
+ self.norm = nn.ModuleList(
410
+ [InstanceNorm() for _ in range(n_layers * self.n_norms)]
411
+ )
412
+ elif norm == "group_norm":
413
+ self.norm = nn.ModuleList(
414
+ [
415
+ nn.GroupNorm(num_groups=norm_groups, num_channels=self.out_channels)
416
+ for _ in range(n_layers * self.n_norms)
417
+ ]
418
+ )
419
+ elif norm == "ada_in":
420
+ self.norm = nn.ModuleList(
421
+ [
422
+ AdaIN(ada_in_features, out_channels)
423
+ for _ in range(n_layers * self.n_norms)
424
+ ]
425
+ )
426
+ else:
427
+ raise ValueError(
428
+ f"Got norm={norm} but expected None or one of "
429
+ "[instance_norm, group_norm, ada_in]"
430
+ )
431
+
432
+ def set_ada_in_embeddings(self, *embeddings):
433
+ """Sets the embeddings of each Ada-IN norm layers
434
+
435
+ Parameters
436
+ ----------
437
+ embeddings : tensor or list of tensor
438
+ if a single embedding is given, it will be used for each norm layer
439
+ otherwise, each embedding will be used for the corresponding norm layer
440
+ """
441
+ if len(embeddings) == 1:
442
+ for norm in self.norm:
443
+ norm.set_embedding(embeddings[0])
444
+ else:
445
+ for norm, embedding in zip(self.norm, embeddings):
446
+ norm.set_embedding(embedding)
447
+
448
+ def forward(self, x, index=0, output_shape=None):
449
+ if self.preactivation:
450
+ return self.forward_with_preactivation(x, index, output_shape)
451
+ else:
452
+ return self.forward_with_postactivation(x, index, output_shape)
453
+
454
+ def forward_with_postactivation(self, x, index=0, output_shape=None):
455
+ if self.local_no_skips is not None:
456
+ x_skip_local_no = self.local_no_skips[index](x)
457
+ x_skip_local_no = self.convs[index].transform(x_skip_local_no, output_shape=output_shape)
458
+
459
+ if self.mlp is not None and self.channel_mlp_skips is not None:
460
+ x_skip_mlp = self.channel_mlp_skips[index](x)
461
+ x_skip_mlp = self.convs[index].transform(x_skip_mlp, output_shape=output_shape)
462
+
463
+ if self.stabilizer == "tanh":
464
+ x = torch.tanh(x)
465
+
466
+ x_local_no = self.convs[index](x, output_shape=output_shape)
467
+
468
+ if self.differential_idx_list[index] != -1:
469
+ grid_width_scaling_factor = 1 / (x.shape[-1] / self.default_in_shape[0])
470
+ x_differential = self.differential[self.differential_idx_list[index]](x, grid_width_scaling_factor)
471
+ x_differential = self.convs[index].transform(x_differential, output_shape=output_shape)
472
+ else:
473
+ x_differential = 0
474
+
475
+ if self.disco_idx_list[index] != -1:
476
+ x_localconv = self.local_convs[self.disco_idx_list[index]](x)
477
+ x_localconv = self.convs[index].transform(x_localconv, output_shape=output_shape)
478
+ else:
479
+ x_localconv = 0
480
+
481
+ x_local_no_diff_disco = x_local_no + x_differential + x_localconv
482
+
483
+ if self.norm is not None:
484
+ x_local_no_diff_disco = self.norm[self.n_norms * index](x_local_no_diff_disco)
485
+
486
+ x = (
487
+ x_local_no_diff_disco + x_skip_local_no
488
+ if self.local_no_skips is not None
489
+ else x_local_no_diff_disco
490
+ )
491
+
492
+ if (self.mlp is not None) or (index < (self.n_layers - 1)):
493
+ x = self.non_linearity(x)
494
+
495
+ if self.mlp is not None:
496
+ if self.channel_mlp_skips is not None:
497
+ x = self.mlp[index](x) + x_skip_mlp
498
+ else:
499
+ x = self.mlp[index](x)
500
+
501
+ if self.norm is not None:
502
+ x = self.norm[self.n_norms * index + 1](x)
503
+
504
+ if index < (self.n_layers - 1):
505
+ x = self.non_linearity(x)
506
+
507
+ return x
508
+
509
+ def forward_with_preactivation(self, x, index=0, output_shape=None):
510
+ # Apply non-linear activation (and norm)
511
+ # before this block's convolution/forward pass:
512
+ x = self.non_linearity(x)
513
+
514
+ if self.norm is not None:
515
+ x = self.norm[self.n_norms * index](x)
516
+
517
+ if self.differential_idx_list[index] != -1:
518
+ grid_width_scaling_factor = 1 / (x.shape[-1] / self.default_grid_res)
519
+ x_differential = self.differential[self.differential_idx_list[index]](x, grid_width_scaling_factor)
520
+ else:
521
+ x_differential = 0
522
+
523
+ if self.disco_idx_list[index] != -1:
524
+ x_localconv = self.local_convs[self.disco_idx_list[index]](x)
525
+ else:
526
+ x_localconv = 0
527
+
528
+ if self.local_no_skips is not None:
529
+ x_skip_local_no = self.local_no_skips[index](x)
530
+ x_skip_local_local_no = self.convs[index].transform(x_skip_local_no + x_differential + x_localconv, output_shape=output_shape)
531
+ else:
532
+ x_skip_local_local_no = self.convs[index].transform(x_differential + x_localconv, output_shape=output_shape)
533
+
534
+ if self.mlp is not None:
535
+ if self.channel_mlp_skips is not None:
536
+ x_skip_mlp = self.channel_mlp_skips[index](x)
537
+ x_skip_mlp = self.convs[index].transform(x_skip_mlp, output_shape=output_shape)
538
+
539
+ if self.stabilizer == "tanh":
540
+ x = torch.tanh(x)
541
+
542
+ x_local_no = self.convs[index](x, output_shape=output_shape)
543
+
544
+ x = (
545
+ x_local_no + x_skip_local_local_no
546
+ if self.local_no_skips is not None
547
+ else x_local_no
548
+ )
549
+
550
+ if self.mlp is not None:
551
+ if index < (self.n_layers - 1):
552
+ x = self.non_linearity(x)
553
+
554
+ if self.norm is not None:
555
+ x = self.norm[self.n_norms * index + 1](x)
556
+
557
+ if self.channel_mlp_skips is not None:
558
+ x = self.mlp[index](x) + x_skip_mlp
559
+ else:
560
+ x = self.mlp[index](x)
561
+
562
+ return x
563
+
564
+ @property
565
+ def n_modes(self):
566
+ return self._n_modes
567
+
568
+ @n_modes.setter
569
+ def n_modes(self, n_modes):
570
+ for i in range(self.n_layers):
571
+ self.convs[i].n_modes = n_modes
572
+ self._n_modes = n_modes
573
+
574
+ def get_block(self, indices):
575
+ """Returns a sub-NO Block layer from the jointly parametrized main block
576
+
577
+ The parametrization of an LocalNOBlock layer is shared with the main one.
578
+ """
579
+ if self.n_layers == 1:
580
+ raise ValueError(
581
+ "A single layer is parametrized, directly use the main class."
582
+ )
583
+
584
+ return SubModule(self, indices)
585
+
586
+ def __getitem__(self, indices):
587
+ return self.get_block(indices)
sources/neuraloperator/neuralop/layers/neighbor_search.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+ # only import open3d if built
5
+ open3d_built = False
6
+ try:
7
+ from open3d.ml.torch.layers import FixedRadiusSearch
8
+
9
+ open3d_built = True
10
+ except:
11
+ pass
12
+
13
+
14
+ # Uses open3d by default which, as of October 2024, requires torch 2.0 and cuda11.*
15
+ class NeighborSearch(nn.Module):
16
+ """Neighborhood search between two arbitrary coordinate meshes.
17
+
18
+ For each point `x` in `queries`, returns a set of the indices of all points `y` in `data`
19
+ within the ball of radius r `B_r(x)`
20
+
21
+ Parameters
22
+ ----------
23
+ use_open3d : bool, optional
24
+ Whether to use open3d or native PyTorch implementation, by default True
25
+ NOTE: open3d implementation requires 3d data
26
+ return_norm : bool, optional
27
+ Whether to return normalized distances, by default False
28
+ """
29
+
30
+ def __init__(self, use_open3d=True, return_norm=False):
31
+ super().__init__()
32
+ if use_open3d and open3d_built: # slightly faster, works on GPU in 3d only
33
+ self.search_fn = FixedRadiusSearch()
34
+ self.use_open3d = use_open3d
35
+ else: # slower fallback, works on GPU and CPU
36
+ self.search_fn = native_neighbor_search
37
+ self.use_open3d = False
38
+ self.return_norm = return_norm
39
+
40
+ def forward(self, data, queries, radius):
41
+ """
42
+ Find the neighbors, in data, of each point in queries
43
+ within a ball of radius. Returns in CRS format.
44
+
45
+ Parameters
46
+ ----------
47
+ data : torch.Tensor of shape [n, d]
48
+ Search space of possible neighbors
49
+ NOTE: open3d requires d=3
50
+ queries : torch.Tensor of shape [m, d]
51
+ Points for which to find neighbors
52
+ NOTE: open3d requires d=3
53
+ radius : float
54
+ Radius of each ball: B(queries[j], radius)
55
+
56
+ Returns
57
+ -------
58
+ return_dict : dict
59
+ Dictionary with keys: neighbors_index, neighbors_row_splits
60
+ neighbors_index: torch.Tensor with dtype=torch.int64
61
+ Index of each neighbor in data for every point
62
+ in queries. Neighbors are ordered in the same orderings
63
+ as the points in queries. Open3d and torch_cluster
64
+ implementations can differ by a permutation of the
65
+ neighbors for every point.
66
+ neighbors_row_splits: torch.Tensor of shape [m+1] with dtype=torch.int64
67
+ The value at index j is the sum of the number of
68
+ neighbors up to query point j-1. First element is 0
69
+ and last element is the total number of neighbors.
70
+ """
71
+ return_dict = {}
72
+
73
+ if self.use_open3d:
74
+ search_return = self.search_fn(data, queries, radius)
75
+ return_dict["neighbors_index"] = search_return.neighbors_index.long()
76
+ return_dict["neighbors_row_splits"] = search_return.neighbors_row_splits.long()
77
+
78
+ else:
79
+ return_dict = self.search_fn(data, queries, radius, self.return_norm)
80
+
81
+ return return_dict
82
+
83
+
84
+ def native_neighbor_search(
85
+ data: torch.Tensor, queries: torch.Tensor, radius: float, return_norm: bool = False
86
+ ):
87
+ """
88
+ Native PyTorch implementation of a neighborhood search
89
+ between two arbitrary coordinate meshes.
90
+
91
+ Parameters
92
+ ----------
93
+ data : torch.Tensor
94
+ vector of data points from which to find neighbors
95
+ queries : torch.Tensor
96
+ centers of neighborhoods
97
+ radius : float
98
+ size of each neighborhood
99
+ """
100
+ nbr_dict = {}
101
+
102
+ # compute pairwise distances
103
+ all_dists = torch.cdist(queries, data).to(queries.device) # shaped num query points x num data points
104
+ # keep zero-distance points
105
+ eps = 1e-7
106
+ all_dists = torch.where(all_dists == 0., eps, all_dists)
107
+ dists = torch.where(all_dists <= radius, all_dists, 0.) # i,j is 1 if j is i's neighbor
108
+ nbr_indices = dists.nonzero()[:,1:].reshape(-1,) # only keep the column indices
109
+ if return_norm:
110
+ weights = dists[dists.nonzero(as_tuple=True)]
111
+ nbr_dict["weights"] = weights **2 # weighting function computed on squared norms
112
+ in_nbr = torch.where(dists > 0, 1., 0.,)
113
+ nbrhd_sizes = torch.cumsum(torch.sum(in_nbr, dim=1), dim=0) # num points in each neighborhood, summed cumulatively
114
+ splits = torch.cat((torch.tensor([0.]).to(queries.device), nbrhd_sizes))
115
+
116
+ nbr_dict["neighbors_index"] = nbr_indices.long().to(queries.device)
117
+ nbr_dict["neighbors_row_splits"] = splits.long()
118
+
119
+ return nbr_dict
sources/neuraloperator/neuralop/layers/normalization_layers.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class AdaIN(nn.Module):
6
+ """Adaptive Instance Normalization (AdaIN) layer for style transfer in neural operators.
7
+
8
+ AdaIN performs instance normalization followed by adaptive scaling and shifting
9
+ based on an external embedding vector. This allows for style transfer by
10
+ modulating the output characteristics based on a conditioning signal.
11
+
12
+ The layer first normalizes the input using instance normalization, then applies
13
+ learned scaling (weight) and shifting (bias) parameters derived from an embedding
14
+ vector through a multi-layer perceptron.
15
+
16
+ Parameters
17
+ ----------
18
+ embed_dim : int
19
+ Dimension of the embedding vector used for style conditioning
20
+ in_channels : int
21
+ Number of input channels to normalize
22
+ mlp : nn.Module, optional
23
+ Multi-layer perceptron that maps embedding to (weight, bias) parameters.
24
+ Should output 2*in_channels values. If None, a default MLP is created
25
+ with architecture: Linear(embed_dim, 512) -> GELU -> Linear(512, 2*in_channels)
26
+ eps : float, optional
27
+ Small value added to the denominator for numerical stability in normalization.
28
+ Default is 1e-5.
29
+ """
30
+
31
+ def __init__(self, embed_dim, in_channels, mlp=None, eps=1e-5):
32
+ super().__init__()
33
+ self.in_channels = in_channels
34
+ self.embed_dim = embed_dim
35
+ self.eps = eps
36
+
37
+ if mlp is None:
38
+ mlp = nn.Sequential(
39
+ nn.Linear(embed_dim, 512),
40
+ nn.GELU(),
41
+ nn.Linear(512, 2*in_channels)
42
+ )
43
+ self.mlp = mlp
44
+
45
+ self.embedding = None
46
+
47
+ def set_embedding(self, x):
48
+ """Set the embedding vector for style conditioning."""
49
+ self.embedding = x.reshape(self.embed_dim,)
50
+
51
+ def forward(self, x):
52
+ """Apply adaptive instance normalization to the input tensor."""
53
+ assert self.embedding is not None, "AdaIN: update embeddding before running forward"
54
+
55
+ weight, bias = torch.split(self.mlp(self.embedding), self.in_channels, dim=0)
56
+
57
+ return nn.functional.group_norm(x, self.in_channels, weight, bias, eps=self.eps)
58
+
59
+
60
+ class InstanceNorm(nn.Module):
61
+ """Dimension-agnostic instance normalization layer for neural operators.
62
+
63
+ InstanceNorm normalizes each sample in the batch independently, computing
64
+ mean and variance across spatial dimensions for each sample and channel
65
+ separately. This is useful when the statistical properties of each sample
66
+ are distinct and should be treated separately.
67
+
68
+ Parameters
69
+ ----------
70
+ **kwargs : dict, optional
71
+ Additional parameters to pass to torch.nn.functional.instance_norm().
72
+ Common parameters include:
73
+ - eps : float, optional
74
+ Small value added to the denominator for numerical stability.
75
+ Default is 1e-5.
76
+ - momentum : float, optional
77
+ Value used for the running_mean and running_var computation.
78
+ Default is 0.1.
79
+ - use_input_stats : bool, optional
80
+ If True, use input statistics. Default is True.
81
+ - weight : torch.Tensor, optional
82
+ Weight tensor for affine transformation. If None, no scaling applied.
83
+ - bias : torch.Tensor, optional
84
+ Bias tensor for affine transformation. If None, no bias applied.
85
+ """
86
+
87
+ def __init__(self, **kwargs):
88
+ super().__init__()
89
+ self.kwargs = kwargs
90
+
91
+ def forward(self, x):
92
+ """Apply instance normalization to the input tensor."""
93
+ size = x.shape
94
+ x = torch.nn.functional.instance_norm(x, **self.kwargs)
95
+ assert x.shape == size
96
+ return x
97
+
98
+
99
+ class BatchNorm(nn.Module):
100
+ """Dimension-agnostic batch normalization layer for neural operators.
101
+
102
+ BatchNorm normalizes data across the entire batch, computing a single mean
103
+ and standard deviation for all samples combined. This is the most common
104
+ form of normalization and is effective when batch statistics are a good
105
+ approximation of the overall data distribution.
106
+
107
+ For dimensions > 3, the layer automatically flattens spatial dimensions
108
+ and uses BatchNorm1d, as PyTorch doesn't implement batch norm for 4D+ tensors.
109
+
110
+ Parameters
111
+ ----------
112
+ n_dim : int
113
+ Spatial dimension of input data (e.g., 1 for 1D, 2 for 2D, 3 for 3D).
114
+ Determined by FNOBlocks.n_dim. If n_dim > 3, spatial dimensions are
115
+ flattened and BatchNorm1d is used.
116
+ num_features : int
117
+ Number of channels in the input tensor to be normalized
118
+ **kwargs : dict, optional
119
+ Additional parameters to pass to the underlying batch normalization layer.
120
+ Common parameters include:
121
+ - eps : float, optional
122
+ Small value added to the denominator for numerical stability.
123
+ Default is 1e-5.
124
+ - momentum : float, optional
125
+ Value used for the running_mean and running_var computation.
126
+ Default is 0.1.
127
+ - affine : bool, optional
128
+ If True, apply learnable affine transformation. Default is True.
129
+ - track_running_stats : bool, optional
130
+ If True, track running statistics. Default is True.
131
+ """
132
+
133
+ def __init__(self, n_dim: int, num_features: int, **kwargs):
134
+ super().__init__()
135
+ self.n_dim = n_dim
136
+ self.num_features = num_features
137
+ self.kwargs = kwargs
138
+
139
+ if self.n_dim <= 3:
140
+ self.norm = getattr(torch.nn, f"BatchNorm{n_dim}d")(
141
+ num_features=num_features, **kwargs
142
+ )
143
+ else:
144
+ print(
145
+ "Warning: torch does not implement batch norm for dimensions higher than 3.\
146
+ We manually flatten the spatial dimension of 4+D tensors to apply batch norm. "
147
+ )
148
+ self.norm = torch.nn.BatchNorm1d(num_features=num_features, **kwargs)
149
+
150
+ def forward(self, x):
151
+ """Apply batch normalization to the input tensor."""
152
+ size = x.shape
153
+ num_channels = size[1]
154
+
155
+ # in 4+D, we flatten and use batchnorm1d.
156
+ if self.n_dim >= 4:
157
+ x = x.reshape(size[0], size[1], -1)
158
+ x = self.norm(x)
159
+
160
+ # if flattening occurred, unflatten
161
+ if self.n_dim >= 4:
162
+ x = x.reshape(size)
163
+
164
+ assert x.shape == size
165
+ return x
sources/neuraloperator/neuralop/layers/padding.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from neuralop.utils import validate_scaling_factor
7
+
8
+
9
+ class DomainPadding(nn.Module):
10
+ """Applies domain padding scaled automatically to the input's resolution.
11
+
12
+ Parameters
13
+ ----------
14
+ domain_padding : float or list
15
+ Typically, between zero and one, percentage of padding to use
16
+ if a list, make sure if matches the dim of (d1, ..., dN)
17
+ resolution_scaling_factor : int, optional
18
+ Resolution scaling factor, by default 1
19
+
20
+ Notes
21
+ -----
22
+ This class works for any input resolution. Expects inputs of shape
23
+ (batch-size, channels, d1, ...., dN)
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ domain_padding: Union[float, list],
29
+ resolution_scaling_factor: Union[int, List[int]] = 1,
30
+ ):
31
+ super().__init__()
32
+ self.domain_padding = domain_padding
33
+ if resolution_scaling_factor is None:
34
+ resolution_scaling_factor = 1
35
+ self.resolution_scaling_factor: Union[int, List[int]] = resolution_scaling_factor
36
+
37
+ # dict(f'{resolution}'=padding) such that padded = F.pad(x, indices)
38
+ self._padding = dict()
39
+
40
+ # dict(f'{resolution}'=indices_to_unpad) such that unpadded = x[indices]
41
+ self._unpad_indices = dict()
42
+
43
+ def forward(self, x):
44
+ """
45
+ forward pass: pad the input
46
+ """
47
+ self.pad(x)
48
+
49
+ def pad(self, x, verbose=False):
50
+ """Take an input and pad it by the desired fraction
51
+
52
+ The amount of padding will be automatically scaled with the resolution
53
+ """
54
+ resolution = x.shape[2:]
55
+
56
+ # if domain_padding is list, then to pass on
57
+ if isinstance(self.domain_padding, (float, int)):
58
+ self.domain_padding = [float(self.domain_padding)] * len(resolution)
59
+
60
+ assert len(self.domain_padding) == len(resolution), (
61
+ "domain_padding length must match the number of spatial/time dimensions "
62
+ "(excluding batch, ch)"
63
+ )
64
+
65
+ resolution_scaling_factor = self.resolution_scaling_factor
66
+ if not isinstance(self.resolution_scaling_factor, list):
67
+ # if unset by the user, scaling_factor will be 1 be default,
68
+ # so `resolution_scaling_factor` should never be None.
69
+ resolution_scaling_factor: List[float] = validate_scaling_factor(
70
+ self.resolution_scaling_factor, len(resolution), n_layers=None
71
+ )
72
+
73
+ try:
74
+ padding = self._padding[f"{resolution}"]
75
+ return F.pad(x, padding, mode="constant")
76
+
77
+ except KeyError:
78
+ padding = [round(p * r) for (p, r) in zip(self.domain_padding, resolution)]
79
+
80
+ if verbose:
81
+ print(
82
+ f"Padding inputs of resolution={resolution} with "
83
+ f"padding={padding}, symmetric"
84
+ )
85
+
86
+ output_pad = padding
87
+
88
+ output_pad = [
89
+ round(i * j) for (i, j) in zip(resolution_scaling_factor, output_pad)
90
+ ]
91
+
92
+ # padding is being applied in reverse order
93
+ # (so we must reverse the padding list)
94
+ padding = padding[::-1]
95
+
96
+ # the F.pad(x, padding) funtion pads the tensor 'x' in reverse order
97
+ # of the "padding" list i.e. the last axis of tensor 'x' will be
98
+ # padded by the amount mention at the first position of the
99
+ # 'padding' vector. The details about F.pad can be found here:
100
+ # https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
101
+
102
+ # Pad both sides (symmetric mode)
103
+ unpad_list = list()
104
+ for p in output_pad:
105
+ if p == 0:
106
+ padding_end = None
107
+ padding_start = None
108
+ else:
109
+ padding_end = p
110
+ padding_start = -p
111
+ unpad_list.append(slice(padding_end, padding_start, None))
112
+ unpad_indices = (Ellipsis,) + tuple(unpad_list)
113
+
114
+ padding = [i for p in padding for i in (p, p)]
115
+
116
+ self._padding[f"{resolution}"] = padding
117
+
118
+ padded = F.pad(x, padding, mode="constant")
119
+
120
+ output_shape = padded.shape[2:]
121
+
122
+ output_shape = [
123
+ round(i * j) for (i, j) in zip(resolution_scaling_factor, output_shape)
124
+ ]
125
+
126
+ self._unpad_indices[f"{[i for i in output_shape]}"] = unpad_indices
127
+
128
+ return padded
129
+
130
+ def unpad(self, x):
131
+ """Remove the padding from padding inputs"""
132
+ unpad_indices = self._unpad_indices[f"{list(x.shape[2:])}"]
133
+ return x[unpad_indices]
sources/neuraloperator/neuralop/layers/resample.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import itertools
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ def resample(x, res_scale, axis, output_shape=None):
8
+ """A module for generic n-dimentional interpolation.
9
+
10
+ For 1D and 2D inputs, the ``resample`` function uses PyTorch’s built-in spatial interpolators
11
+ for efficiency, applying linear interpolation for 1D data and bicubic interpolation for 2D data
12
+ directly in the spatial domain.
13
+
14
+ For 3D or higher-dimensional inputs, the ``resample`` function switches to a spectral interpolation
15
+ method based on the Fourier transform. The input is transformed into the frequency domain using a
16
+ real n-dimensional FFT, which decomposes the signal into its frequency components. By resizing
17
+ this frequency representation and then applying an inverse FFT, the function achieves smooth,
18
+ alias-free interpolation that preserves the signal’s overall structure.
19
+
20
+ Parameters
21
+ ----------
22
+ x : torch.Tensor
23
+ input activation of size (batch_size, channels, d1, ..., dN)
24
+ res_scale: int or tuple
25
+ Scaling factor along each of the dimensions in 'axis' parameter. If res_scale is scaler, then isotropic
26
+ scaling is performed
27
+ axis: axis or dimensions along which interpolation will be performed.
28
+ output_shape : None or tuple[int]
29
+ """
30
+
31
+ if isinstance(res_scale, (float, int)):
32
+ if axis is None:
33
+ axis = list(range(2, x.ndim))
34
+ res_scale = [res_scale] * len(axis)
35
+ elif isinstance(axis, int):
36
+ axis = [axis]
37
+ res_scale = [res_scale]
38
+ else:
39
+ res_scale = [res_scale] * len(axis)
40
+ else:
41
+ assert len(res_scale) == len(axis), "leght of res_scale and axis are not same"
42
+
43
+ old_size = x.shape[-len(axis) :]
44
+ if output_shape is None:
45
+ new_size = tuple([int(round(s * r)) for (s, r) in zip(old_size, res_scale)])
46
+ else:
47
+ new_size = output_shape
48
+
49
+ if len(axis) == 1:
50
+ return F.interpolate(x, size=new_size[0], mode="linear", align_corners=True)
51
+ if len(axis) == 2:
52
+ return F.interpolate(x, size=new_size, mode="bicubic", align_corners=True)
53
+
54
+ X = torch.fft.rfftn(x.float(), norm="forward", dim=axis)
55
+
56
+ new_fft_size = list(new_size)
57
+ new_fft_size[-1] = new_fft_size[-1] // 2 + 1 # Redundant last coefficient
58
+ new_fft_size_c = [min(i, j) for (i, j) in zip(new_fft_size, X.shape[-len(axis) :])]
59
+ out_fft = torch.zeros(
60
+ [x.shape[0], x.shape[1], *new_fft_size], device=x.device, dtype=torch.cfloat
61
+ )
62
+
63
+ mode_indexing = [((None, m//2), (-m//2, None)) for m in new_fft_size_c[:-1]] + [((None, new_fft_size_c[-1]), )]
64
+ for i, boundaries in enumerate(itertools.product(*mode_indexing)):
65
+ idx_tuple = [slice(None), slice(None)] + [slice(*b) for b in boundaries]
66
+
67
+ idx_tuple = tuple(idx_tuple)
68
+ out_fft[idx_tuple] = X[idx_tuple]
69
+ y = torch.fft.irfftn(out_fft, s=new_size, norm="forward", dim=axis)
70
+
71
+ return y
72
+
73
+
74
+ def iterative_resample(x, res_scale, axis):
75
+ if isinstance(axis, list) and isinstance(res_scale, (float, int)):
76
+ res_scale = [res_scale] * len(axis)
77
+ if not isinstance(axis, list) and isinstance(res_scale,list):
78
+ raise Exception("Axis is not a list but Scale factors are")
79
+ if isinstance(axis, list) and isinstance(res_scale,list) and len(res_scale) != len(axis):
80
+ raise Exception("Axis and Scal factor are in different sizes")
81
+
82
+ if isinstance(axis, list):
83
+ for i in range(len(res_scale)):
84
+ rs = res_scale[i]
85
+ a = axis[i]
86
+ x = resample(x, rs, a)
87
+ return x
88
+
89
+ old_res = x.shape[axis]
90
+ X = torch.fft.rfft(x, dim=axis, norm="forward")
91
+ newshape = list(x.shape)
92
+ new_res = int(round(res_scale * newshape[axis]))
93
+ newshape[axis] = new_res // 2 + 1
94
+
95
+ Y = torch.zeros(newshape, dtype=X.dtype, device=x.device)
96
+
97
+ modes = min(new_res, old_res)
98
+ sl = [slice(None)] * x.ndim
99
+ sl[axis] = slice(0, modes // 2 + 1)
100
+ Y[tuple(sl)] = X[tuple(sl)]
101
+ y = torch.fft.irfft(Y, n=new_res, dim=axis, norm="forward")
102
+ return y
sources/neuraloperator/neuralop/layers/rno_block.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ from ..layers.spectral_convolution import SpectralConv
7
+ from ..layers.fno_block import FNOBlocks
8
+ from ..layers.complex import cselu
9
+
10
+
11
+ class RNOCell(nn.Module):
12
+ """N-Dimensional Recurrent Neural Operator cell. The RNO cell takes in an
13
+ input and history function, and it outputs the next step of the hidden function.
14
+
15
+ The RNO cell implements the GRU-like recurrence relation with Fourier layers:
16
+ z_t = σ(f1(x_t) + f2(h_{t-1}) + b1) [update gate]
17
+ r_t = σ(f3(x_t) + f4(h_{t-1}) + b2) [reset gate]
18
+ h̃_t = selu(f5(x_t) + f6(r_t ⊙ h_{t-1}) + b3) [candidate state]
19
+ h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ h̃_t [next state]
20
+
21
+ where σ is the sigmoid function, ⊙ is element-wise multiplication,
22
+ and f1-f6 are FNO blocks (Fourier neural operators).
23
+
24
+ Parameters
25
+ ----------
26
+ n_modes : int tuple
27
+ number of modes to keep in Fourier Layer, along each dimension
28
+ The dimensionality of the RNO is inferred from ``len(n_modes)``
29
+ hidden_channels : int
30
+ number of hidden channels in the RNO
31
+
32
+ Other Parameters
33
+ ----------------
34
+ resolution_scaling_factor : Union[Number, List[Number]], optional
35
+ Factor by which to scale outputs for super-resolution, by default None
36
+ max_n_modes : int or List[int], optional
37
+ Maximum number of modes to keep along each dimension, by default None
38
+ fno_block_precision : str, optional
39
+ Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full"
40
+ use_channel_mlp : bool, optional
41
+ Whether to use an MLP layer after each FNO block, by default True
42
+ channel_mlp_dropout : float, optional
43
+ Dropout parameter for self.channel_mlp, by default 0
44
+ channel_mlp_expansion : float, optional
45
+ Expansion parameter for self.channel_mlp, by default 0.5
46
+ non_linearity : torch.nn.F module, optional
47
+ Nonlinear activation function to use between layers, by default F.gelu
48
+ stabilizer : Literal["tanh"], optional
49
+ Stabilizing module to use between certain layers. Options: "tanh", None, by default None
50
+ norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional
51
+ Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None
52
+ norm_groups : int, optional
53
+ Number of groups for GroupNorm, by default 1
54
+ ada_in_features : int, optional
55
+ Number of features for adaptive instance norm above, by default None
56
+ preactivation : bool, optional
57
+ Whether to call forward pass with pre-activation, by default False
58
+ If True, call nonlinear activation and norm before Fourier convolution
59
+ If False, call activation and norms after Fourier convolutions
60
+ fno_skip : str, optional
61
+ Module to use for FNO skip connections. Options: "linear", "soft-gating", "identity", None, by default "linear"
62
+ If None, no skip connection is added. See layers.skip_connections for more details
63
+ channel_mlp_skip : str, optional
64
+ Module to use for ChannelMLP skip connections. Options: "linear", "soft-gating", "identity", None, by default "soft-gating"
65
+ If None, no skip connection is added. See layers.skip_connections for more details
66
+ complex_data : bool, optional
67
+ Whether the FNO's data takes on complex values in space, by default False
68
+ separable : bool, optional
69
+ Separable parameter for SpectralConv, by default False
70
+ factorization : str, optional
71
+ Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None
72
+ rank : float, optional
73
+ Rank parameter for SpectralConv, by default 1.0
74
+ conv_module : BaseConv, optional
75
+ Module to use for convolutions in FNO block, by default SpectralConv
76
+ joint_factorization : bool, optional
77
+ Whether to factorize all spectralConv weights as one tensor, by default False
78
+ fixed_rank_modes : bool, optional
79
+ Fixed_rank_modes parameter for SpectralConv, by default False
80
+ implementation : str, optional
81
+ Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized"
82
+ decomposition_kwargs : dict, optional
83
+ Kwargs for tensor decomposition in SpectralConv, by default dict()
84
+ enforce_hermitian_symmetry : bool, optional
85
+ Whether to enforce Hermitian symmetry conditions when performing inverse FFT
86
+ for real-valued data. Only used when ``conv_module`` is :class:`SpectralConv`
87
+ or a subclass; ignored otherwise. When True, explicitly enforces that the 0th
88
+ frequency and Nyquist frequency are real-valued before calling irfft. When False,
89
+ relies on cuFFT's irfftn to handle symmetry automatically, which may fail on
90
+ certain GPUs or input sizes, causing line artifacts. By default True.
91
+
92
+ References
93
+ ----------
94
+ .. [1] Paper: https://arxiv.org/abs/2308.08794
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ n_modes,
100
+ hidden_channels,
101
+ resolution_scaling_factor=None,
102
+ max_n_modes=None,
103
+ fno_block_precision="full",
104
+ use_channel_mlp=True,
105
+ channel_mlp_dropout=0,
106
+ channel_mlp_expansion=0.5,
107
+ non_linearity=F.gelu,
108
+ stabilizer=None,
109
+ norm=None,
110
+ norm_groups=1,
111
+ ada_in_features=None,
112
+ preactivation=False,
113
+ fno_skip="linear",
114
+ channel_mlp_skip="soft-gating",
115
+ complex_data=False,
116
+ separable=False,
117
+ factorization=None,
118
+ rank=1.0,
119
+ conv_module=SpectralConv,
120
+ fixed_rank_modes=False,
121
+ implementation="factorized",
122
+ decomposition_kwargs=dict(),
123
+ enforce_hermitian_symmetry=True,
124
+ ):
125
+ super().__init__()
126
+ self.hidden_channels = hidden_channels
127
+ scaling_factor = (
128
+ None if not resolution_scaling_factor else [resolution_scaling_factor]
129
+ )
130
+ fno_kwargs = {
131
+ "n_layers": 1,
132
+ "max_n_modes": max_n_modes,
133
+ "fno_block_precision": fno_block_precision,
134
+ "use_channel_mlp": use_channel_mlp,
135
+ "channel_mlp_dropout": channel_mlp_dropout,
136
+ "channel_mlp_expansion": channel_mlp_expansion,
137
+ "non_linearity": non_linearity,
138
+ "stabilizer": stabilizer,
139
+ "norm": norm,
140
+ "norm_groups": norm_groups,
141
+ "preactivation": preactivation,
142
+ "fno_skip": fno_skip,
143
+ "channel_mlp_skip": channel_mlp_skip,
144
+ "complex_data": complex_data,
145
+ "separable": separable,
146
+ "factorization": factorization,
147
+ "rank": rank,
148
+ "conv_module": conv_module,
149
+ "fixed_rank_modes": fixed_rank_modes,
150
+ "implementation": implementation,
151
+ "decomposition_kwargs": decomposition_kwargs,
152
+ "enforce_hermitian_symmetry": enforce_hermitian_symmetry,
153
+ }
154
+
155
+ # For super-resolution: the hidden state h is always stored at the scaled resolution,
156
+ # while input x remains at the original resolution. Therefore, only f1, f3, and f5
157
+ # (which process x) need resolution scaling, while f2, f4, and f6 (which process h)
158
+ # operate at the already-scaled resolution.
159
+
160
+ self.input_gates = nn.ModuleList()
161
+ self.hidden_gates = nn.ModuleList()
162
+ self.biases = nn.ParameterList()
163
+
164
+ # 3 gates: Update (z), Reset (r), Candidate (h_tilde)
165
+ # Each gate involves one FNOBlock processing x (input_gate)
166
+ # and one FNOBlock processing h (hidden_gate)
167
+ for _ in range(3):
168
+ self.input_gates.append(
169
+ FNOBlocks(
170
+ in_channels=hidden_channels,
171
+ out_channels=hidden_channels,
172
+ n_modes=n_modes,
173
+ resolution_scaling_factor=scaling_factor,
174
+ **fno_kwargs,
175
+ )
176
+ )
177
+ self.hidden_gates.append(
178
+ FNOBlocks(
179
+ in_channels=hidden_channels,
180
+ out_channels=hidden_channels,
181
+ n_modes=n_modes,
182
+ resolution_scaling_factor=None,
183
+ **fno_kwargs,
184
+ )
185
+ )
186
+ if complex_data:
187
+ self.biases.append(nn.Parameter(torch.randn(()) + 1j * torch.randn(())))
188
+ else:
189
+ self.biases.append(nn.Parameter(torch.randn(())))
190
+
191
+ def forward(self, x, h):
192
+ """Forward pass for RNO cell.
193
+
194
+ Parameters
195
+ ----------
196
+ x : torch.Tensor
197
+ Input function at current timestep with shape (batch, hidden_channels, *spatial_dims)
198
+ h : torch.Tensor
199
+ Hidden state from previous timestep with shape (batch, hidden_channels, *spatial_dims_h)
200
+ where spatial_dims_h may differ from spatial_dims if resolution_scaling_factor is set
201
+
202
+ Returns
203
+ -------
204
+ torch.Tensor
205
+ Updated hidden state with shape (batch, hidden_channels, *spatial_dims_h)
206
+ """
207
+ # Update gate
208
+ update_gate = torch.sigmoid(
209
+ self.input_gates[0](x) + self.hidden_gates[0](h) + self.biases[0]
210
+ )
211
+
212
+ # Reset gate
213
+ reset_gate = torch.sigmoid(
214
+ self.input_gates[1](x) + self.hidden_gates[1](h) + self.biases[1]
215
+ )
216
+
217
+ # Candidate state
218
+ h_combined = self.input_gates[2](x) + self.hidden_gates[2](reset_gate * h) + self.biases[2]
219
+
220
+ if x.dtype == torch.cfloat:
221
+ candidate_state = cselu(h_combined) # complex SELU for complex data
222
+ else:
223
+ candidate_state = F.selu(h_combined) # regular SELU for real data
224
+
225
+ h_next = (1.0 - update_gate) * h + update_gate * candidate_state
226
+
227
+ return h_next
228
+
229
+
230
+ class RNOBlock(nn.Module):
231
+ """N-Dimensional Recurrent Neural Operator layer. The RNO layer extends the
232
+ action of the RNO cell to take in some sequence of time-steps as input
233
+ and output the next output function.
234
+
235
+ The layer applies the RNO cell recurrently over a sequence of inputs:
236
+ For t = 1 to T:
237
+ h_t = RNOCell(x_t, h_{t-1})
238
+
239
+ where the cell implements:
240
+ z_t = σ(f1(x_t) + f2(h_{t-1}) + b1) [update gate]
241
+ r_t = σ(f3(x_t) + f4(h_{t-1}) + b2) [reset gate]
242
+ h̃_t = selu(f5(x_t) + f6(r_t ⊙ h_{t-1}) + b3) [candidate state]
243
+ h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ h̃_t [next state]
244
+
245
+ Parameters
246
+ ----------
247
+ n_modes : int tuple
248
+ number of modes to keep in Fourier Layer, along each dimension
249
+ The dimensionality of the RNO is inferred from ``len(n_modes)``
250
+ hidden_channels : int
251
+ number of hidden channels in the RNO
252
+ return_sequences : boolean, optional
253
+ Whether to return the sequence of hidden states associated with processing
254
+ the inputs sequence of functions. Default: False
255
+
256
+ Other Parameters
257
+ ----------------
258
+ resolution_scaling_factor : Union[Number, List[Number]], optional
259
+ Factor by which to scale outputs for super-resolution, by default None
260
+ max_n_modes : int or List[int], optional
261
+ Maximum number of modes to keep along each dimension, by default None
262
+ fno_block_precision : str, optional
263
+ Floating point precision to use for computations. Options: "full", "half", "mixed", by default "full"
264
+ use_channel_mlp : bool, optional
265
+ Whether to use an MLP layer after each FNO block, by default True
266
+ channel_mlp_dropout : float, optional
267
+ Dropout parameter for self.channel_mlp, by default 0
268
+ channel_mlp_expansion : float, optional
269
+ Expansion parameter for self.channel_mlp, by default 0.5
270
+ non_linearity : torch.nn.F module, optional
271
+ Nonlinear activation function to use between layers, by default F.gelu
272
+ stabilizer : Literal["tanh"], optional
273
+ Stabilizing module to use between certain layers. Options: "tanh", None, by default None
274
+ norm : Literal["ada_in", "group_norm", "instance_norm", "batch_norm"], optional
275
+ Normalization layer to use. Options: "ada_in", "group_norm", "instance_norm", "batch_norm", None, by default None
276
+ norm_groups : int, optional
277
+ Number of groups for GroupNorm, by default 1
278
+ ada_in_features : int, optional
279
+ Number of features for adaptive instance norm above, by default None
280
+ preactivation : bool, optional
281
+ Whether to call forward pass with pre-activation, by default False
282
+ If True, call nonlinear activation and norm before Fourier convolution
283
+ If False, call activation and norms after Fourier convolutions
284
+ fno_skip : str, optional
285
+ Module to use for FNO skip connections. Options: "linear", "soft-gating", "identity", None, by default "linear"
286
+ If None, no skip connection is added. See layers.skip_connections for more details
287
+ channel_mlp_skip : str, optional
288
+ Module to use for ChannelMLP skip connections. Options: "linear", "soft-gating", "identity", None, by default "soft-gating"
289
+ If None, no skip connection is added. See layers.skip_connections for more details
290
+ complex_data : bool, optional
291
+ Whether the FNO's data takes on complex values in space, by default False
292
+ separable : bool, optional
293
+ Separable parameter for SpectralConv, by default False
294
+ factorization : str, optional
295
+ Factorization parameter for SpectralConv. Options: "tucker", "cp", "tt", None, by default None
296
+ rank : float, optional
297
+ Rank parameter for SpectralConv, by default 1.0
298
+ conv_module : BaseConv, optional
299
+ Module to use for convolutions in FNO block, by default SpectralConv
300
+ joint_factorization : bool, optional
301
+ Whether to factorize all spectralConv weights as one tensor, by default False
302
+ fixed_rank_modes : bool, optional
303
+ Fixed_rank_modes parameter for SpectralConv, by default False
304
+ implementation : str, optional
305
+ Implementation parameter for SpectralConv. Options: "factorized", "reconstructed", by default "factorized"
306
+ decomposition_kwargs : dict, optional
307
+ Kwargs for tensor decomposition in SpectralConv, by default dict()
308
+ enforce_hermitian_symmetry : bool, optional
309
+ Whether to enforce Hermitian symmetry conditions when performing inverse FFT
310
+ for real-valued data. Only used when ``conv_module`` is :class:`SpectralConv`
311
+ or a subclass; ignored otherwise. When True, explicitly enforces that the 0th
312
+ frequency and Nyquist frequency are real-valued before calling irfft. When False,
313
+ relies on cuFFT's irfftn to handle symmetry automatically, which may fail on
314
+ certain GPUs or input sizes, causing line artifacts. By default True.
315
+
316
+ References
317
+ ----------
318
+ .. [1] Paper: https://arxiv.org/abs/2308.08794
319
+ """
320
+
321
+ def __init__(
322
+ self,
323
+ n_modes,
324
+ hidden_channels,
325
+ return_sequences=False,
326
+ resolution_scaling_factor=None,
327
+ max_n_modes=None,
328
+ fno_block_precision="full",
329
+ use_channel_mlp=True,
330
+ channel_mlp_dropout=0,
331
+ channel_mlp_expansion=0.5,
332
+ non_linearity=F.gelu,
333
+ stabilizer=None,
334
+ norm=None,
335
+ norm_groups=1,
336
+ ada_in_features=None,
337
+ preactivation=False,
338
+ fno_skip="linear",
339
+ channel_mlp_skip="soft-gating",
340
+ complex_data=False,
341
+ separable=False,
342
+ factorization=None,
343
+ rank=1.0,
344
+ conv_module=SpectralConv,
345
+ fixed_rank_modes=False,
346
+ implementation="factorized",
347
+ decomposition_kwargs=dict(),
348
+ enforce_hermitian_symmetry=True,
349
+ ):
350
+ super().__init__()
351
+
352
+ self.hidden_channels = hidden_channels
353
+ self.return_sequences = return_sequences
354
+ self.resolution_scaling_factor = resolution_scaling_factor
355
+
356
+ self.cell = RNOCell(
357
+ n_modes,
358
+ hidden_channels,
359
+ resolution_scaling_factor=resolution_scaling_factor,
360
+ max_n_modes=max_n_modes,
361
+ fno_block_precision=fno_block_precision,
362
+ use_channel_mlp=use_channel_mlp,
363
+ channel_mlp_dropout=channel_mlp_dropout,
364
+ channel_mlp_expansion=channel_mlp_expansion,
365
+ non_linearity=non_linearity,
366
+ stabilizer=stabilizer,
367
+ norm=norm,
368
+ norm_groups=norm_groups,
369
+ preactivation=preactivation,
370
+ fno_skip=fno_skip,
371
+ channel_mlp_skip=channel_mlp_skip,
372
+ complex_data=complex_data,
373
+ separable=separable,
374
+ factorization=factorization,
375
+ rank=rank,
376
+ conv_module=conv_module,
377
+ fixed_rank_modes=fixed_rank_modes,
378
+ implementation=implementation,
379
+ decomposition_kwargs=decomposition_kwargs,
380
+ enforce_hermitian_symmetry=enforce_hermitian_symmetry,
381
+ )
382
+ if complex_data:
383
+ self.bias_h = nn.Parameter(torch.randn(()) + 1j * torch.randn(()))
384
+ else:
385
+ self.bias_h = nn.Parameter(torch.randn(()))
386
+
387
+ def forward(self, x, h=None):
388
+ """Forward pass for RNO layer.
389
+
390
+ Parameters
391
+ ----------
392
+ x : torch.Tensor
393
+ Input sequence with shape (batch, timesteps, hidden_channels, *spatial_dims)
394
+ h : torch.Tensor, optional
395
+ Initial hidden state with shape (batch, hidden_channels, *spatial_dims_h).
396
+ If None, initialized to zeros with added bias. Default: None
397
+
398
+ Returns
399
+ -------
400
+ torch.Tensor
401
+ If return_sequences=True: hidden states for all timesteps with shape
402
+ (batch, timesteps, hidden_channels, *spatial_dims_h)
403
+ If return_sequences=False: final hidden state with shape
404
+ (batch, hidden_channels, *spatial_dims_h)
405
+ """
406
+ batch_size, timesteps, dim = x.shape[:3]
407
+ dom_sizes = x.shape[3:]
408
+
409
+ # Initialize hidden state if not provided
410
+ if h is None:
411
+ # Compute the spatial dimensions for h (scaled if resolution_scaling_factor is set)
412
+ if not self.resolution_scaling_factor:
413
+ h_shape = (batch_size, self.hidden_channels, *dom_sizes)
414
+ else:
415
+ scaled_sizes = tuple(
416
+ [int(round(self.resolution_scaling_factor * s)) for s in dom_sizes]
417
+ )
418
+ h_shape = (batch_size, self.hidden_channels, *scaled_sizes)
419
+ h = torch.zeros(h_shape, dtype=x.dtype).to(x.device)
420
+ h += self.bias_h
421
+
422
+ outputs = []
423
+ # Process each timestep sequentially through the RNO cell
424
+ for i in range(timesteps):
425
+ h = self.cell(x[:, i], h) # Update hidden state with current input
426
+ if self.return_sequences:
427
+ outputs.append(h)
428
+
429
+ if self.return_sequences:
430
+ return torch.stack(outputs, dim=1)
431
+ else:
432
+ return h
sources/neuraloperator/neuralop/layers/segment_csr.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+ import importlib
3
+
4
+ import torch
5
+ from torch import einsum
6
+
7
+
8
+ def segment_csr(
9
+ src: torch.Tensor,
10
+ indptr: torch.Tensor,
11
+ reduction: Literal["mean", "sum"],
12
+ use_scatter=True,
13
+ ):
14
+ """segment_csr reduces all entries of a CSR-formatted
15
+ matrix by summing or averaging over neighbors.
16
+
17
+ Used to reduce features over neighborhoods
18
+ in neuralop.layers.IntegralTransform
19
+
20
+ If use_scatter is set to False or torch_scatter is not
21
+ properly built, segment_csr falls back to a naive PyTorch implementation
22
+
23
+ Note: the native version is mainly intended for running tests on
24
+ CPU-only GitHub CI runners to get around a versioning issue.
25
+ torch_scatter should be installed and built if possible.
26
+
27
+ Parameters
28
+ ----------
29
+ src : torch.Tensor
30
+ tensor of features for each point
31
+ indptr : torch.Tensor
32
+ splits representing start and end indices
33
+ of each neighborhood in src
34
+ reduction : Literal['mean', 'sum']
35
+ How to reduce a neighborhood. Options: 'mean', 'sum'. If mean,
36
+ reduce by taking the average of all neighbors. Otherwise take the sum.
37
+ use_scatter : bool, optional
38
+ Whether to use torch-scatter.segment_csr. If False, uses native Python reduction, by default True
39
+
40
+ .. warning::
41
+
42
+ torch-scatter is an optional dependency that conflicts with the newest versions of PyTorch,
43
+ so you must handle the conflict explicitly in your environment. See :ref:`torch_scatter_dependency`
44
+ for more information.
45
+ """
46
+ if reduction not in ["mean", "sum"]:
47
+ raise ValueError("reduce must be one of 'mean', 'sum'")
48
+
49
+ if importlib.util.find_spec("torch_scatter") is not None and use_scatter:
50
+ """only import torch_scatter when cuda is available"""
51
+ import torch_scatter.segment_csr as scatter_segment_csr
52
+
53
+ return scatter_segment_csr(src, indptr, reduce=reduction)
54
+
55
+ else:
56
+ if use_scatter:
57
+ print(
58
+ "Warning: use_scatter is True but torch_scatter is not properly built. \
59
+ Defaulting to naive PyTorch implementation"
60
+ )
61
+ # if batched, shape [b, n_reps, channels]
62
+ # otherwise shape [n_reps, channels]
63
+ if src.ndim == 3:
64
+ batched = True
65
+ point_dim = 1
66
+ else:
67
+ batched = False
68
+ point_dim = 0
69
+
70
+ # if batched, shape [b, n_out, channels]
71
+ # otherwise shape [n_out, channels]
72
+ output_shape = list(src.shape)
73
+ n_out = indptr.shape[point_dim] - 1
74
+ output_shape[point_dim] = n_out
75
+
76
+ out = torch.zeros(output_shape, device=src.device)
77
+
78
+ for i in range(n_out):
79
+ # reduce all indices pointed to in indptr from src into out
80
+ if batched:
81
+ from_idx = (slice(None), slice(indptr[0, i], indptr[0, i + 1]))
82
+ ein_str = "bio->bo"
83
+ start = indptr[0, i]
84
+ n_nbrs = indptr[0, i + 1] - start
85
+ to_idx = (slice(None), i)
86
+ else:
87
+ from_idx = slice(indptr[i], indptr[i + 1])
88
+ ein_str = "io->o"
89
+ start = indptr[i]
90
+ n_nbrs = indptr[i + 1] - start
91
+ to_idx = i
92
+ src_from = src[from_idx]
93
+ if n_nbrs > 0:
94
+ to_reduce = einsum(ein_str, src_from)
95
+ if reduction == "mean":
96
+ to_reduce /= n_nbrs
97
+ out[to_idx] += to_reduce
98
+ return out
sources/neuraloperator/neuralop/layers/skip_connections.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ def skip_connection(
6
+ in_features, out_features, n_dim=2, bias=False, skip_type="soft-gating"
7
+ ):
8
+ """A wrapper for several types of skip connections.
9
+ Returns an nn.Module skip connections, one of {'identity', 'linear', soft-gating'}
10
+
11
+ Parameters
12
+ ----------
13
+ in_features : int
14
+ Number of input features
15
+ out_features : int
16
+ Number of output features
17
+ n_dim : int, optional
18
+ Dimensionality of the input (excluding batch-size and channels).
19
+ n_dim=2 corresponds to having Module2D, by default 2
20
+ bias : bool, optional
21
+ Whether to use a bias, by default False
22
+ skip_type : {'identity', 'linear', 'soft-gating'}, optional
23
+ Kind of skip connection to use. Options: 'identity', 'linear', 'soft-gating', by default "soft-gating"
24
+
25
+ Returns
26
+ -------
27
+ nn.Module
28
+ module that takes in x and returns skip(x)
29
+ """
30
+ if skip_type.lower() == "soft-gating":
31
+ return SoftGating(
32
+ in_features=in_features,
33
+ out_features=out_features,
34
+ bias=bias,
35
+ n_dim=n_dim,
36
+ )
37
+ elif skip_type.lower() == "linear":
38
+ return Flattened1dConv(
39
+ in_channels=in_features,
40
+ out_channels=out_features,
41
+ kernel_size=1,
42
+ bias=bias,
43
+ )
44
+ elif skip_type.lower() == "identity":
45
+ return nn.Identity()
46
+ else:
47
+ raise ValueError(
48
+ f"Got skip-connection type={skip_type}, expected one of"
49
+ f" {'soft-gating', 'linear', 'id'}."
50
+ )
51
+
52
+
53
+ class SoftGating(nn.Module):
54
+ """Applies soft-gating by weighting the channels of the given input.
55
+
56
+ Given an input x of size `(batch-size, channels, height, width)`,
57
+ this returns `x * w `
58
+ where w is of shape `(1, channels, 1, 1)`
59
+
60
+ Parameters
61
+ ----------
62
+ in_features : int
63
+ Number of input features
64
+ out_features : None
65
+ This is provided for API compatibility with nn.Linear only
66
+ n_dim : int, optional
67
+ Dimensionality of the input (excluding batch-size and channels).
68
+ n_dim=2 corresponds to having Module2D, by default 2
69
+ bias : bool, optional
70
+ Whether to use a bias, by default False
71
+ """
72
+
73
+ def __init__(self, in_features, out_features=None, n_dim=2, bias=False):
74
+ super().__init__()
75
+ if out_features is not None and in_features != out_features:
76
+ raise ValueError(
77
+ f"Got in_features={in_features} and out_features={out_features}, "
78
+ "but these two must be the same for soft-gating"
79
+ )
80
+ self.in_features = in_features
81
+ self.out_features = out_features
82
+ self.weight = nn.Parameter(torch.ones(1, self.in_features, *(1,) * n_dim))
83
+ if bias:
84
+ self.bias = nn.Parameter(torch.ones(1, self.in_features, *(1,) * n_dim))
85
+ else:
86
+ self.bias = None
87
+
88
+ def forward(self, x):
89
+ """Applies soft-gating to a batch of activations"""
90
+ if self.bias is not None:
91
+ return self.weight * x + self.bias
92
+ else:
93
+ return self.weight * x
94
+
95
+
96
+ class Flattened1dConv(nn.Module):
97
+ def __init__(self, in_channels: int, out_channels: int, kernel_size, bias=False):
98
+ """Flattened1dConv is a Conv-based skip layer for
99
+ input tensors of ndim > 3 (batch, channels, d1, ...) that flattens all dimensions
100
+ past the batch and channel dims into one dimension, applies the Conv1d,
101
+ and un-flattens.
102
+
103
+ Parameters
104
+ ----------
105
+ in_channels : int
106
+ in_channels of Conv1d
107
+ out_channels : int
108
+ out_channels of Conv1d
109
+ kernel_size : int
110
+ kernel_size of Conv1d
111
+ bias : bool, optional
112
+ bias of Conv1d, by default False
113
+ """
114
+ super().__init__()
115
+ self.conv = nn.Conv1d(
116
+ in_channels=in_channels,
117
+ out_channels=out_channels,
118
+ kernel_size=kernel_size,
119
+ bias=bias,
120
+ )
121
+
122
+ def forward(self, x):
123
+ # x.shape: b, c, x1, ..., xn x_ndim > 1
124
+ size = list(x.shape)
125
+ # flatten everything past 1st data dim
126
+ x = x.view(*size[:2], -1)
127
+ x = self.conv(x)
128
+ # reshape x into an Nd tensor b, c, x1, x2, ...
129
+ x = x.view(size[0], self.conv.out_channels, *size[2:])
130
+ return x
sources/neuraloperator/neuralop/layers/spectral_convolution.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ from ..utils import validate_scaling_factor
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ import tensorly as tl
9
+ from tensorly.plugins import use_opt_einsum
10
+ from tltorch.factorized_tensors.core import FactorizedTensor
11
+
12
+ from .einsum_utils import einsum_complexhalf
13
+ from .base_spectral_conv import BaseSpectralConv
14
+ from .resample import resample
15
+
16
+ tl.set_backend("pytorch")
17
+ use_opt_einsum("optimal")
18
+ einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
19
+
20
+
21
+ def _contract_dense(x, weight, separable=False):
22
+ order = tl.ndim(x)
23
+ # batch-size, in_channels, x, y...
24
+ x_syms = list(einsum_symbols[:order])
25
+
26
+ # in_channels, out_channels, x, y...
27
+ weight_syms = list(x_syms[1:]) # no batch-size
28
+
29
+ # batch-size, out_channels, x, y...
30
+ if separable:
31
+ out_syms = [x_syms[0]] + list(weight_syms)
32
+ else:
33
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
34
+ out_syms = list(weight_syms)
35
+ out_syms[0] = x_syms[0]
36
+
37
+ eq = f'{"".join(x_syms)},{"".join(weight_syms)}->{"".join(out_syms)}'
38
+
39
+ if not torch.is_tensor(weight):
40
+ weight = weight.to_tensor()
41
+
42
+ if x.dtype == torch.complex32:
43
+ # if x is half precision, run a specialized einsum
44
+ return einsum_complexhalf(eq, x, weight)
45
+ else:
46
+ return tl.einsum(eq, x, weight)
47
+
48
+
49
+ def _contract_dense_separable(x, weight, separable):
50
+ if not torch.is_tensor(weight):
51
+ weight = weight.to_tensor()
52
+ return x * weight
53
+
54
+
55
+ def _contract_cp(x, cp_weight, separable=False):
56
+ order = tl.ndim(x)
57
+
58
+ x_syms = str(einsum_symbols[:order])
59
+ rank_sym = einsum_symbols[order]
60
+ out_sym = einsum_symbols[order + 1]
61
+ out_syms = list(x_syms)
62
+ if separable:
63
+ factor_syms = [einsum_symbols[1] + rank_sym] # in only
64
+ else:
65
+ out_syms[1] = out_sym
66
+ factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out
67
+ factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ...
68
+ eq = f'{x_syms},{rank_sym},{",".join(factor_syms)}->{"".join(out_syms)}'
69
+
70
+ if x.dtype == torch.complex32:
71
+ return einsum_complexhalf(eq, x, cp_weight.weights, *cp_weight.factors)
72
+ else:
73
+ return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors)
74
+
75
+
76
+ def _contract_tucker(x, tucker_weight, separable=False):
77
+ order = tl.ndim(x)
78
+
79
+ x_syms = str(einsum_symbols[:order])
80
+ out_sym = einsum_symbols[order]
81
+ out_syms = list(x_syms)
82
+ if separable:
83
+ core_syms = einsum_symbols[order + 1 : 2 * order]
84
+ # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only
85
+ # x, y, ...
86
+ factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)]
87
+
88
+ else:
89
+ core_syms = einsum_symbols[order + 1 : 2 * order + 1]
90
+ out_syms[1] = out_sym
91
+ factor_syms = [
92
+ einsum_symbols[1] + core_syms[0],
93
+ out_sym + core_syms[1],
94
+ ] # out, in
95
+ # x, y, ...
96
+ factor_syms += [xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])]
97
+
98
+ eq = f'{x_syms},{core_syms},{",".join(factor_syms)}->{"".join(out_syms)}'
99
+
100
+ if x.dtype == torch.complex32:
101
+ return einsum_complexhalf(eq, x, tucker_weight.core, *tucker_weight.factors)
102
+ else:
103
+ return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors)
104
+
105
+
106
+ def _contract_tt(x, tt_weight, separable=False):
107
+ order = tl.ndim(x)
108
+
109
+ x_syms = list(einsum_symbols[:order])
110
+ weight_syms = list(x_syms[1:]) # no batch-size
111
+ if not separable:
112
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
113
+ out_syms = list(weight_syms)
114
+ out_syms[0] = x_syms[0]
115
+ else:
116
+ out_syms = list(x_syms)
117
+ rank_syms = list(einsum_symbols[order + 1 :])
118
+ tt_syms = []
119
+ for i, s in enumerate(weight_syms):
120
+ tt_syms.append([rank_syms[i], s, rank_syms[i + 1]])
121
+ eq = (
122
+ "".join(x_syms)
123
+ + ","
124
+ + ",".join("".join(f) for f in tt_syms)
125
+ + "->"
126
+ + "".join(out_syms)
127
+ )
128
+
129
+ if x.dtype == torch.complex32:
130
+ return einsum_complexhalf(eq, x, *tt_weight.factors)
131
+ else:
132
+ return tl.einsum(eq, x, *tt_weight.factors)
133
+
134
+
135
+ def get_contract_fun(weight, implementation="reconstructed", separable=False):
136
+ """Generic ND implementation of Fourier Spectral Conv contraction
137
+
138
+ Parameters
139
+ ----------
140
+ weight : tensorly-torch's FactorizedTensor
141
+ implementation : {'reconstructed', 'factorized'}, default is 'reconstructed'
142
+ whether to reconstruct the weight and do a forward pass (reconstructed)
143
+ or contract directly the factors of the factorized weight with the input (factorized)
144
+ separable: bool
145
+ if True, performs contraction with individual tensor factors.
146
+ if False,
147
+ Returns
148
+ -------
149
+ function : (x, weight) -> x * weight in Fourier space
150
+ """
151
+ if implementation == "reconstructed":
152
+ if separable:
153
+ return _contract_dense_separable
154
+ else:
155
+ return _contract_dense
156
+ elif implementation == "factorized":
157
+ if torch.is_tensor(weight):
158
+ return _contract_dense
159
+ elif isinstance(weight, FactorizedTensor):
160
+ if weight.name.lower().endswith("dense"):
161
+ return _contract_dense
162
+ elif weight.name.lower().endswith("tucker"):
163
+ return _contract_tucker
164
+ elif weight.name.lower().endswith("tt"):
165
+ return _contract_tt
166
+ elif weight.name.lower().endswith("cp"):
167
+ return _contract_cp
168
+ else:
169
+ raise ValueError(f"Got unexpected factorized weight type {weight.name}")
170
+ else:
171
+ raise ValueError(
172
+ f"Got unexpected weight type of class {weight.__class__.__name__}"
173
+ )
174
+ else:
175
+ raise ValueError(
176
+ f'Got implementation={implementation}, expected "reconstructed" or "factorized"'
177
+ )
178
+
179
+
180
+ Number = Union[int, float]
181
+
182
+
183
+ class SpectralConv(BaseSpectralConv):
184
+ """SpectralConv implements the Spectral Convolution component of a Fourier layer
185
+ described.
186
+
187
+ It is implemented as described in [1]_ and [2]_.
188
+
189
+ Parameters
190
+ ----------
191
+ in_channels : int
192
+ Number of input channels
193
+ out_channels : int
194
+ Number of output channels
195
+ n_modes : int or int tuple
196
+ Number of modes to use for contraction in Fourier domain during training.
197
+
198
+ .. warning::
199
+
200
+ We take care of the redundancy in the Fourier modes, therefore, for an input
201
+ of size I_1, ..., I_N, please provide modes M_K that are I_1 < M_K <= I_N
202
+ We will automatically keep the right amount of modes: specifically, for the
203
+ last mode only, if you specify M_N modes we will use M_N // 2 + 1 modes
204
+ as the real FFT is redundant along that last dimension. See the theory guide for mode truncation details.
205
+
206
+
207
+ .. note::
208
+
209
+ Provided modes should be even integers. odd numbers will be rounded to the closest even number.
210
+
211
+ This can be updated dynamically during training.
212
+
213
+ complex_data : bool, optional
214
+ Whether data takes on complex values in the spatial domain, by default False.
215
+ If True, uses different logic for FFT contraction and uses full FFT instead of real-valued.
216
+ max_n_modes : int tuple or None, optional
217
+ If not None, maximum number of modes to keep in Fourier Layer along each dim
218
+ (n_modes cannot be increased beyond that). If None, all n_modes are used.
219
+ By default None.
220
+ bias : bool, optional
221
+ Whether to add a learnable bias to the output, by default True.
222
+ separable : bool, optional
223
+ Whether to use separable implementation of contraction.
224
+ If True, contracts factors of factorized tensor weight individually.
225
+ By default False.
226
+ resolution_scaling_factor : float, list of float, or None, optional
227
+ Scaling factor(s) for resolution scaling. If provided, the output resolution
228
+ will be scaled by this factor along each spatial dimension.
229
+ By default None.
230
+ fno_block_precision : str, optional
231
+ Precision mode for FNO block operations. Options: 'full', 'half', 'mixed'.
232
+ By default 'full'.
233
+ rank : float, optional
234
+ Rank of the tensor factorization of the Fourier weights, by default 1.0.
235
+ Ignored if ``factorization is None``.
236
+ factorization : str or None, optional
237
+ Tensor factorization type. Options: {'tucker', 'cp', 'tt'}.
238
+ If None, a single dense weight is learned for the FNO.
239
+ Otherwise, that weight, used for the contraction in the Fourier domain
240
+ is learned in factorized form. In that case, `factorization` is the
241
+ tensor factorization of the parameters weight used.
242
+ By default None.
243
+ implementation : {'factorized', 'reconstructed'}, optional
244
+ If factorization is not None, forward mode to use:
245
+ * `reconstructed` : the full weight tensor is reconstructed from the
246
+ factorization and used for the forward pass
247
+ * `factorized` : the input is directly contracted with the factors of
248
+ the decomposition
249
+ Ignored if ``factorization is None``.
250
+ By default 'reconstructed'.
251
+ enforce_hermitian_symmetry : bool, optional
252
+ Whether to enforce Hermitian symmetry conditions when performing inverse FFT
253
+ for real-valued data. When True, explicitly enforces that the 0th frequency
254
+ and Nyquist frequency are real-valued before calling irfft.
255
+ When False, relies on cuFFT's irfftn to handle symmetry automatically,
256
+ which may fail on certain GPUs or input sizes, causing line artifacts.
257
+ Setting to True splits the inverse FFT into ifftn along (n-1) dimensions
258
+ followed by irfft on the last dimension, with a small computational overhead.
259
+ By default True.
260
+ fixed_rank_modes : bool, optional
261
+ Modes to not factorize, by default False.
262
+ Ignored if ``factorization is None``.
263
+ decomposition_kwargs : dict or None, optional
264
+ Optional additional parameters to pass to the tensor decomposition.
265
+ Ignored if ``factorization is None``.
266
+ By default None.
267
+ init_std : float or 'auto', optional
268
+ Standard deviation to use for weight initialization, by default 'auto'.
269
+ If 'auto', uses (2 / (in_channels + out_channels)) ** 0.5.
270
+ fft_norm : str, optional
271
+ FFT normalization parameter, by default 'forward'.
272
+ device : torch.device or None, optional
273
+ Device to place the layer on, by default None.
274
+
275
+ References
276
+ ----------
277
+ .. [1] Li, Z. et al. "Fourier Neural Operator for Parametric Partial Differential
278
+ Equations" (2021). ICLR 2021, https://arxiv.org/pdf/2010.08895.
279
+
280
+ .. [2] Kossaifi, J., Kovachki, N., Azizzadenesheli, K., Anandkumar, A. "Multi-Grid
281
+ Tensorized Fourier Neural Operator for High-Resolution PDEs" (2024).
282
+ TMLR 2024, https://openreview.net/pdf?id=AWiDlO63bH.
283
+ """
284
+
285
+ def __init__(
286
+ self,
287
+ in_channels,
288
+ out_channels,
289
+ n_modes,
290
+ complex_data=False,
291
+ max_n_modes=None,
292
+ bias=True,
293
+ separable=False,
294
+ resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None,
295
+ fno_block_precision="full",
296
+ rank=1.0,
297
+ factorization=None,
298
+ implementation="reconstructed",
299
+ enforce_hermitian_symmetry=True,
300
+ fixed_rank_modes=False,
301
+ decomposition_kwargs: Optional[dict] = None,
302
+ init_std="auto",
303
+ fft_norm="forward",
304
+ device=None,
305
+ ):
306
+ super().__init__(device=device)
307
+
308
+ self.in_channels = in_channels
309
+ self.out_channels = out_channels
310
+
311
+ self.complex_data = complex_data
312
+
313
+ # n_modes is the total number of modes kept along each dimension
314
+ self.n_modes = n_modes
315
+ self.order = len(self.n_modes)
316
+
317
+ if max_n_modes is None:
318
+ max_n_modes = self.n_modes
319
+ elif isinstance(max_n_modes, int):
320
+ max_n_modes = [max_n_modes]
321
+ self.max_n_modes = max_n_modes
322
+
323
+ self.fno_block_precision = fno_block_precision
324
+ self.rank = rank
325
+ self.factorization = factorization
326
+ self.implementation = implementation
327
+ self.enforce_hermitian_symmetry = enforce_hermitian_symmetry
328
+
329
+ self.resolution_scaling_factor: Union[
330
+ None, List[List[float]]
331
+ ] = validate_scaling_factor(resolution_scaling_factor, self.order)
332
+
333
+ if init_std == "auto":
334
+ init_std = (2 / (in_channels + out_channels)) ** 0.5
335
+
336
+ if isinstance(fixed_rank_modes, bool):
337
+ if fixed_rank_modes:
338
+ # If bool, keep the number of layers fixed
339
+ fixed_rank_modes = [0]
340
+ else:
341
+ fixed_rank_modes = None
342
+ self.fft_norm = fft_norm
343
+
344
+ if factorization is None:
345
+ factorization = "Dense" # No factorization
346
+
347
+ if separable:
348
+ if in_channels != out_channels:
349
+ raise ValueError(
350
+ "To use separable Fourier Conv, in_channels must be equal "
351
+ f"to out_channels, but got in_channels={in_channels} and "
352
+ f"out_channels={out_channels}",
353
+ )
354
+ weight_shape = (in_channels, *max_n_modes)
355
+ else:
356
+ weight_shape = (in_channels, out_channels, *max_n_modes)
357
+ self.separable = separable
358
+
359
+ tensor_kwargs = decomposition_kwargs if decomposition_kwargs is not None else {}
360
+
361
+ # Create/init spectral weight tensor
362
+ self.weight = FactorizedTensor.new(
363
+ weight_shape,
364
+ rank=self.rank,
365
+ factorization=factorization,
366
+ fixed_rank_modes=fixed_rank_modes,
367
+ **tensor_kwargs,
368
+ dtype=torch.cfloat,
369
+ )
370
+ self.weight.normal_(0, init_std)
371
+
372
+ self._contract = get_contract_fun(
373
+ self.weight, implementation=implementation, separable=separable
374
+ )
375
+
376
+ if bias:
377
+ self.bias = nn.Parameter(
378
+ init_std * torch.randn(*(tuple([self.out_channels]) + (1,) * self.order))
379
+ )
380
+ else:
381
+ self.bias = None
382
+
383
+ def transform(self, x, output_shape=None):
384
+ in_shape = list(x.shape[2:])
385
+
386
+ if self.resolution_scaling_factor is not None and output_shape is None:
387
+ out_shape = tuple(
388
+ [round(s * r) for (s, r) in zip(in_shape, self.resolution_scaling_factor)]
389
+ )
390
+ elif output_shape is not None:
391
+ out_shape = output_shape
392
+ else:
393
+ out_shape = in_shape
394
+
395
+ if in_shape == out_shape:
396
+ return x
397
+ else:
398
+ return resample(x, 1.0, list(range(2, x.ndim)), output_shape=out_shape)
399
+
400
+ @property
401
+ def n_modes(self):
402
+ return self._n_modes
403
+
404
+ @n_modes.setter
405
+ def n_modes(self, n_modes):
406
+ if isinstance(n_modes, int): # Should happen for 1D FNO only
407
+ n_modes = [n_modes]
408
+ else:
409
+ n_modes = list(n_modes)
410
+ # the real FFT is skew-symmetric, so the last mode has a redundacy if our data is real in space
411
+ # As a design choice we do the operation here to avoid users dealing with the +1
412
+ # if we use the full FFT we cannot cut off informtion from the last mode
413
+ if not self.complex_data:
414
+ n_modes[-1] = n_modes[-1] // 2 + 1
415
+ self._n_modes = n_modes
416
+
417
+ def forward(self, x: torch.Tensor, output_shape: Optional[Tuple[int]] = None):
418
+ """Generic forward pass for the Factorized Spectral Conv
419
+
420
+ Parameters
421
+ ----------
422
+ x : torch.Tensor
423
+ input activation of size (batch_size, channels, d1, ..., dN)
424
+
425
+ Returns
426
+ -------
427
+ tensorized_spectral_conv(x)
428
+ """
429
+ batchsize, channels, *mode_sizes = x.shape
430
+
431
+ fft_size = list(mode_sizes)
432
+ if not self.complex_data:
433
+ fft_size[-1] = fft_size[-1] // 2 + 1 # Redundant last coefficient in real spatial data
434
+ fft_dims = list(range(-self.order, 0))
435
+
436
+ if self.fno_block_precision == "half":
437
+ x = x.half()
438
+
439
+ if self.complex_data:
440
+ x = torch.fft.fftn(x, norm=self.fft_norm, dim=fft_dims)
441
+ dims_to_fft_shift = fft_dims
442
+ else:
443
+ x = torch.fft.rfftn(x, norm=self.fft_norm, dim=fft_dims)
444
+ # When x is real in spatial domain, the last half of the last dim is redundant.
445
+ # See :ref:`fft_shift_explanation` for discussion of the FFT shift.
446
+ dims_to_fft_shift = fft_dims[:-1]
447
+
448
+ if self.order > 1:
449
+ x = torch.fft.fftshift(x, dim=dims_to_fft_shift)
450
+
451
+ if self.fno_block_precision == "mixed":
452
+ # if 'mixed', the above fft runs in full precision, but the
453
+ # following operations run at half precision
454
+ x = x.chalf()
455
+
456
+ if self.fno_block_precision in ["half", "mixed"]:
457
+ out_dtype = torch.chalf
458
+ else:
459
+ out_dtype = torch.cfloat
460
+ out_fft = torch.zeros(
461
+ [batchsize, self.out_channels, *fft_size], device=x.device, dtype=out_dtype
462
+ )
463
+
464
+ # if current modes are less than max, start indexing modes closer to the center of the weight tensor
465
+ starts = [
466
+ (max_modes - min(size, n_mode))
467
+ for (size, n_mode, max_modes) in zip(fft_size, self.n_modes, self.max_n_modes)
468
+ ]
469
+ # if contraction is separable, weights have shape (channels, modes_x, ...)
470
+ # otherwise they have shape (in_channels, out_channels, modes_x, ...)
471
+ if self.separable:
472
+ slices_w = [slice(None)] # channels
473
+ else:
474
+ slices_w = [slice(None), slice(None)] # in_channels, out_channels
475
+ if self.complex_data:
476
+ slices_w += [
477
+ slice(start // 2, -start // 2) if start else slice(start, None)
478
+ for start in starts
479
+ ]
480
+ else:
481
+ # The last mode already has redundant half removed in real FFT
482
+ slices_w += [
483
+ slice(start // 2, -start // 2) if start else slice(start, None)
484
+ for start in starts[:-1]
485
+ ]
486
+ slices_w += [slice(None, -starts[-1]) if starts[-1] else slice(None)]
487
+
488
+ slices_w = tuple(slices_w)
489
+ weight = self.weight[slices_w]
490
+
491
+ ### Pick the first n_modes modes of FFT signal along each dim
492
+
493
+ # if separable conv, weight tensor only has one channel dim
494
+ if self.separable:
495
+ weight_start_idx = 1
496
+ # otherwise drop first two dims (in_channels, out_channels)
497
+ else:
498
+ weight_start_idx = 2
499
+
500
+ slices_x = [slice(None), slice(None)] # Batch_size, channels
501
+
502
+ for all_modes, kept_modes in zip(fft_size, list(weight.shape[weight_start_idx:])):
503
+ # After fft-shift, the 0th frequency is located at n // 2 in each direction
504
+ # We select n_modes modes around the 0th frequency (kept at index n//2) by grabbing indices
505
+ # n//2 - n_modes//2 to n//2 + n_modes//2 if n_modes is even
506
+ # n//2 - n_modes//2 to n//2 + n_modes//2 + 1 if n_modes is odd
507
+ center = all_modes // 2
508
+ negative_freqs = kept_modes // 2
509
+ positive_freqs = kept_modes // 2 + kept_modes % 2
510
+
511
+ # this slice represents the desired indices along each dim
512
+ slices_x += [slice(center - negative_freqs, center + positive_freqs)]
513
+
514
+ if weight.shape[-1] < fft_size[-1]:
515
+ slices_x[-1] = slice(None, weight.shape[-1])
516
+ else:
517
+ slices_x[-1] = slice(None)
518
+
519
+ slices_x = tuple(slices_x)
520
+ out_fft[slices_x] = self._contract(
521
+ x[slices_x], weight, separable=self.separable
522
+ )
523
+
524
+ if self.resolution_scaling_factor is not None and output_shape is None:
525
+ mode_sizes = tuple([round(s * r) for (s, r) in zip(mode_sizes, self.resolution_scaling_factor)])
526
+
527
+ if output_shape is not None:
528
+ mode_sizes = output_shape
529
+
530
+
531
+ if self.order > 1:
532
+ out_fft = torch.fft.ifftshift(out_fft, dim=fft_dims[:-1])
533
+
534
+
535
+ # Inverse FFT
536
+ if self.complex_data:
537
+ # For complex data, we can use ifftn.
538
+ x = torch.fft.ifftn(out_fft, s=mode_sizes, dim=fft_dims, norm=self.fft_norm)
539
+
540
+ else:
541
+ # For real data, we need to enforce Hermitian symmetry conditions for irfft.
542
+ # On certain GPUs and for certain input sizes, this is not handled within irfftn in cuFFT,
543
+ # and as a result causes line artifacts.
544
+ # To fix this, we split the ifftn into a ifftn in (n-1) dimensions and a irfft in the last dimension,
545
+ # although it incurs a small additional computational cost.
546
+
547
+ if self.enforce_hermitian_symmetry:
548
+ out_fft = torch.fft.ifftn(out_fft, s=mode_sizes[:-1], dim=fft_dims[:-1], norm=self.fft_norm)
549
+
550
+ # Enforce Hermitian symmetry conditions for irfft
551
+ # 0th frequency must be real
552
+ out_fft[..., 0].imag.zero_()
553
+
554
+ # Nyquist frequency must be real if the spatial size is even
555
+ if mode_sizes[-1] % 2 == 0:
556
+ out_fft[..., -1].imag.zero_()
557
+
558
+ # Now that the Hermitian symmetry conditions are enforced, we can use irfft on the last dimension.
559
+ x = torch.fft.irfft(out_fft, n=mode_sizes[-1], dim=fft_dims[-1], norm=self.fft_norm)
560
+
561
+ else:
562
+
563
+ # If Hemrmitian symmetry is not a concern, we can use irfftn on all dimensions.
564
+ x = torch.fft.irfftn(out_fft, s=mode_sizes, dim=fft_dims, norm=self.fft_norm)
565
+
566
+
567
+ if self.bias is not None:
568
+ x = x + self.bias
569
+
570
+ return x
sources/neuraloperator/neuralop/layers/spectral_projection.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.nn.functional as F
4
+
5
+
6
+ def spectral_projection_divergence_free(u, domain_size, constraint_modes):
7
+ """Apply spectral projection layer to make a velocity field divergence-free.
8
+
9
+ Parameters
10
+ ----------
11
+ u : torch.Tensor
12
+ Input velocity field [batch, 2, height, width] where the last two
13
+ dimensions represent the 2D velocity components (u_x, u_y)
14
+ domain_size : float or tuple of float
15
+ Physical domain size. If float, assumes square domain with same size for height and width.
16
+ If tuple, should be (height_size, width_size) for non-square domains.
17
+ constraint_modes : tuple
18
+ Number of modes to use for constraint resolution (height_modes, width_modes).
19
+ If larger than input dimensions, they are truncated to the input dimensions.
20
+
21
+ Returns
22
+ -------
23
+ torch.Tensor
24
+ Divergence-free projected velocity field with [batch, 2, height, width] shape.
25
+ The output maintains the same shape as the input while satisfying ∇·u = 0.
26
+
27
+ Notes
28
+ -----
29
+ **Mathematical formulation:** Helmholtz-Hodge projection in spectral domain:
30
+ û_proj = û - (k·û)/|k|² * k. Enforces ∇·u = 0 by removing the irrotational component.
31
+ **Periodicity:** Velocity fields are assumed periodic. For non-periodic fields, extend
32
+ via Fourier continuation (neuralop.layers.fourier_continuation), project, then truncate.
33
+
34
+ References
35
+ ----------
36
+ The method is based on the spectral projection approach described in:
37
+
38
+ [1] Towards Enforcing Hard Physics Constraints in Operator Learning Frameworks
39
+ V. Duruisseaux, M. Liu-Schiaffini, J. Berner, and A. Anandkumar
40
+ ICML 2024 AI for Science Workshop
41
+ https://openreview.net/pdf?id=Zvxm14Rd1F
42
+
43
+ [2] Enforcing physical constraints in CNNs through differentiable PDE layer.
44
+ C. M. Jiang, K. Kashinath, P. Prabhat, and P. Marcus
45
+ ICLR 2020 Workshop on Integration of Deep Neural Models and Differential Equations, 2020.
46
+ https://openreview.net/pdf?id=q2noHUqMkK
47
+
48
+
49
+ """
50
+
51
+ device = u.device
52
+ dtype = u.dtype
53
+ batch_size, channels, height, width = u.shape
54
+
55
+ # Get domain size
56
+ if isinstance(domain_size, (int, float)):
57
+ # Square domain: use same size for both dimensions
58
+ domain_height = domain_width = float(domain_size)
59
+ elif isinstance(domain_size, (tuple, list)) and len(domain_size) == 2:
60
+ # Non-square domain: separate sizes for height and width
61
+ domain_height, domain_width = float(domain_size[0]), float(domain_size[1])
62
+
63
+ # Ensure constraint modes do not exceed input dimensions
64
+ constraint_modes = (min(constraint_modes[0], height), min(constraint_modes[1], width))
65
+
66
+ # 2D FFT over height and width
67
+ u_ft = torch.fft.fftn(u, dim=(2, 3))
68
+
69
+ # Extract lower modes for both dimensions where the constraint is applied
70
+ if (height != constraint_modes[0]) or (width != constraint_modes[1]):
71
+ u_ft = torch.fft.fftshift(u_ft, dim=(2, 3))
72
+ u_ft = u_ft[:, :,
73
+ (height - constraint_modes[0])//2 : (height - constraint_modes[0])//2 + constraint_modes[0],
74
+ (width - constraint_modes[1])//2 : (width - constraint_modes[1])//2 + constraint_modes[1]]
75
+ u_ft = torch.fft.ifftshift(u_ft, dim=(2, 3))
76
+
77
+ # Set up wavenumber grids for spectral operations
78
+ ky = 2*np.pi * torch.fft.fftfreq(constraint_modes[0], d=domain_height/constraint_modes[0]).to(dtype).to(device)
79
+ kx = 2*np.pi * torch.fft.fftfreq(constraint_modes[1], d=domain_width/constraint_modes[1]).to(dtype).to(device)
80
+ KX, KY = torch.meshgrid(kx, ky, indexing='ij' if constraint_modes[0] == constraint_modes[1] else 'xy')
81
+
82
+
83
+ # Apply Helmholtz-Hodge projection: û_proj = û - (k·û)/|k|² * k
84
+ k_dot_u = KX * u_ft[:, 0, :, :] + KY * u_ft[:, 1, :, :]
85
+ k_squared = KX**2 + KY**2 + 1e-8 # Add small epsilon to avoid division by zero
86
+
87
+ projected_u_ft = u_ft - (k_dot_u / k_squared).unsqueeze(1) * torch.stack([KX, KY], dim=0).unsqueeze(0)
88
+
89
+ # Handle zero mode explicitly
90
+ projected_u_ft[:, :, 0, 0] = 0.0
91
+
92
+
93
+ # Pad zeros back to full resolution if needed
94
+ if height != constraint_modes[0] or width != constraint_modes[1]:
95
+ projected_u_ft = torch.fft.fftshift(projected_u_ft)
96
+ pad_h = height - constraint_modes[0]
97
+ pad_w = width - constraint_modes[1]
98
+ projected_u_ft = F.pad(projected_u_ft, [pad_w//2, pad_w - pad_w//2, pad_h//2, pad_h - pad_h//2])
99
+ projected_u_ft = torch.fft.ifftshift(projected_u_ft)
100
+
101
+ # Transform back to physical space
102
+ return torch.fft.ifftn(projected_u_ft, dim=(2, 3)).real
sources/neuraloperator/neuralop/layers/spherical_convolution.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch_harmonics import RealSHT, InverseRealSHT
6
+
7
+ import tensorly as tl
8
+ from tensorly.plugins import use_opt_einsum
9
+ from tltorch.factorized_tensors.core import FactorizedTensor
10
+
11
+ from neuralop.utils import validate_scaling_factor
12
+ from .base_spectral_conv import BaseSpectralConv
13
+
14
+ tl.set_backend("pytorch")
15
+ use_opt_einsum("optimal")
16
+
17
+ einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
18
+
19
+
20
+ def _contract_dense(x, weight, separable=False, dhconv=True):
21
+ order = tl.ndim(x)
22
+ # batch-size, in_channels, x, y...
23
+ x_syms = list(einsum_symbols[:order])
24
+
25
+ # in_channels, out_channels, x, y...
26
+ weight_syms = list(x_syms[1:]) # no batch-size
27
+
28
+ # batch-size, out_channels, x, y...
29
+ if separable:
30
+ out_syms = [x_syms[0]] + list(weight_syms)
31
+ else:
32
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
33
+ out_syms = list(weight_syms)
34
+ out_syms[0] = x_syms[0]
35
+ if dhconv:
36
+ weight_syms.pop()
37
+
38
+ eq = "".join(x_syms) + "," + "".join(weight_syms) + "->" + "".join(out_syms)
39
+
40
+ if not torch.is_tensor(weight):
41
+ weight = weight.to_tensor()
42
+
43
+ return tl.einsum(eq, x, weight)
44
+
45
+
46
+ def _contract_dense_separable(x, weight, separable=True, dhconv=False):
47
+ if not separable:
48
+ raise ValueError("This function is only for separable=True")
49
+ if dhconv:
50
+ return x * weight.unsqueeze(-1)
51
+ return x * weight
52
+
53
+
54
+ def _contract_cp(x, cp_weight, separable=False, dhconv=True):
55
+ order = tl.ndim(x)
56
+
57
+ x_syms = str(einsum_symbols[:order])
58
+ rank_sym = einsum_symbols[order]
59
+ out_sym = einsum_symbols[order + 1]
60
+ out_syms = list(x_syms)
61
+
62
+ if separable:
63
+ factor_syms = [einsum_symbols[1] + rank_sym] # in only
64
+ else:
65
+ out_syms[1] = out_sym
66
+ factor_syms = [einsum_symbols[1] + rank_sym, out_sym + rank_sym] # in, out
67
+
68
+ if dhconv:
69
+ factor_syms += [xs + rank_sym for xs in x_syms[2:-1]] # x, y, ...
70
+ else:
71
+ factor_syms += [xs + rank_sym for xs in x_syms[2:]] # x, y, ...
72
+
73
+ eq = (
74
+ x_syms + "," + rank_sym + "," + ",".join(factor_syms) + "->" + "".join(out_syms)
75
+ )
76
+
77
+ return tl.einsum(eq, x, cp_weight.weights, *cp_weight.factors)
78
+
79
+
80
+ def _contract_tucker(x, tucker_weight, separable=False, dhconv=False):
81
+ order = tl.ndim(x)
82
+
83
+ x_syms = str(einsum_symbols[:order])
84
+ out_sym = einsum_symbols[order]
85
+ out_syms = list(x_syms)
86
+ if separable:
87
+ core_syms = einsum_symbols[order + 1 : 2 * order]
88
+ # factor_syms = [einsum_symbols[1]+core_syms[0]] #in only
89
+ factor_syms = [xs + rs for (xs, rs) in zip(x_syms[1:], core_syms)] # x, y, ...
90
+
91
+ elif dhconv:
92
+ core_syms = einsum_symbols[order + 1 : 2 * order]
93
+ out_syms[1] = out_sym
94
+ factor_syms = [
95
+ einsum_symbols[1] + core_syms[0],
96
+ out_sym + core_syms[1],
97
+ ] # out, in
98
+ factor_syms += [
99
+ xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])
100
+ ] # x, y, ...
101
+ else:
102
+ core_syms = einsum_symbols[order + 1 : 2 * order + 1]
103
+ out_syms[1] = out_sym
104
+ factor_syms = [
105
+ einsum_symbols[1] + core_syms[0],
106
+ out_sym + core_syms[1],
107
+ ] # out, in
108
+ factor_syms += [
109
+ xs + rs for (xs, rs) in zip(x_syms[2:], core_syms[2:])
110
+ ] # x, y, ...
111
+
112
+ eq = (
113
+ x_syms
114
+ + ","
115
+ + core_syms
116
+ + ","
117
+ + ",".join(factor_syms)
118
+ + "->"
119
+ + "".join(out_syms)
120
+ )
121
+
122
+ return tl.einsum(eq, x, tucker_weight.core, *tucker_weight.factors)
123
+
124
+
125
+ def _contract_tt(x, tt_weight, separable=False, dhconv=False):
126
+ order = tl.ndim(x)
127
+
128
+ x_syms = list(einsum_symbols[:order])
129
+ weight_syms = list(x_syms[1:]) # no batch-size
130
+ if not separable:
131
+ weight_syms.insert(1, einsum_symbols[order]) # outputs
132
+ out_syms = list(weight_syms)
133
+ out_syms[0] = x_syms[0]
134
+ else:
135
+ out_syms = list(x_syms)
136
+
137
+ if dhconv:
138
+ weight_syms = weight_syms[:-1] # no batch-size, no y dim
139
+
140
+ rank_syms = list(einsum_symbols[order + 1 :])
141
+ tt_syms = []
142
+ for i, s in enumerate(weight_syms):
143
+ tt_syms.append([rank_syms[i], s, rank_syms[i + 1]])
144
+ eq = (
145
+ "".join(x_syms)
146
+ + ","
147
+ + ",".join("".join(f) for f in tt_syms)
148
+ + "->"
149
+ + "".join(out_syms)
150
+ )
151
+
152
+ return tl.einsum(eq, x, *tt_weight.factors)
153
+
154
+
155
+ def get_contract_fun(weight, implementation="reconstructed", separable=False):
156
+ """Generic ND implementation of Fourier Spectral Conv contraction
157
+
158
+ Parameters
159
+ ----------
160
+ weight : tensorly-torch's FactorizedTensor
161
+ implementation : {'reconstructed', 'factorized'}, default is 'reconstructed'
162
+ whether to reconstruct the weight and do a forward pass (reconstructed)
163
+ or contract directly the factors of the factorized weight with the input
164
+ (factorized)
165
+ separable : bool
166
+ whether to use the separable implementation of contraction. This arg is
167
+ only checked when `implementation=reconstructed`.
168
+
169
+ Returns
170
+ -------
171
+ function : (x, weight) -> x * weight in Fourier space
172
+ """
173
+ if implementation == "reconstructed":
174
+ if separable:
175
+ return _contract_dense_separable
176
+ else:
177
+ return _contract_dense
178
+ elif implementation == "factorized":
179
+ if torch.is_tensor(weight):
180
+ return _contract_dense
181
+ elif isinstance(weight, FactorizedTensor):
182
+ if weight.name.lower().endswith("dense"):
183
+ return _contract_dense
184
+ elif weight.name.lower().endswith("tucker"):
185
+ return _contract_tucker
186
+ elif weight.name.lower().endswith("tt"):
187
+ return _contract_tt
188
+ elif weight.name.lower().endswith("cp"):
189
+ return _contract_cp
190
+ else:
191
+ raise ValueError(f"Got unexpected factorized weight type {weight.name}")
192
+ else:
193
+ raise ValueError(
194
+ f"Got unexpected weight type of class {weight.__class__.__name__}"
195
+ )
196
+ else:
197
+ raise ValueError(
198
+ f'Got implementation={implementation}, expected "reconstructed" or '
199
+ f'"factorized"'
200
+ )
201
+
202
+
203
+ Number = Union[int, float]
204
+
205
+
206
+ class SHT(nn.Module):
207
+ """A wrapper for the Spherical Harmonics transform.
208
+
209
+ Allows to call it with an interface similar to that of FFT
210
+ """
211
+
212
+ def __init__(self, dtype=torch.float32, device=None):
213
+ super().__init__()
214
+ self.device = device
215
+ self.dtype = dtype
216
+ self._SHT_cache = nn.ModuleDict()
217
+ self._iSHT_cache = nn.ModuleDict()
218
+
219
+ def sht(self, x, s=None, norm="ortho", grid="equiangular"):
220
+ *_, height, width = x.shape # height = latitude, width = longitude
221
+ if s is None:
222
+ if grid == "equiangular":
223
+ modes_width = height // 2
224
+ else:
225
+ modes_width = height
226
+ modes_height = height
227
+ else:
228
+ modes_height, modes_width = s
229
+
230
+ cache_key = f"{height}_{width}_{modes_height}_{modes_width}_{norm}_{grid}"
231
+
232
+ try:
233
+ sht = self._SHT_cache[cache_key]
234
+ except KeyError:
235
+ sht = (
236
+ RealSHT(
237
+ nlat=height,
238
+ nlon=width,
239
+ lmax=modes_height,
240
+ mmax=modes_width,
241
+ grid=grid,
242
+ norm=norm,
243
+ )
244
+ .to(device=x.device)
245
+ .to(dtype=self.dtype)
246
+ )
247
+ self._SHT_cache[cache_key] = sht
248
+
249
+ return sht(x)
250
+
251
+ def isht(self, x, s=None, norm="ortho", grid="equiangular"):
252
+ *_, modes_height, modes_width = x.shape # height = latitude, width = longitude
253
+ if s is None:
254
+ if grid == "equiangular":
255
+ width = modes_width * 2
256
+ else:
257
+ width = modes_width
258
+ height = modes_height
259
+ else:
260
+ height, width = s
261
+
262
+ cache_key = f"{height}_{width}_{modes_height}_{modes_width}_{norm}_{grid}"
263
+
264
+ try:
265
+ isht = self._iSHT_cache[cache_key]
266
+ except KeyError:
267
+ isht = (
268
+ InverseRealSHT(
269
+ nlat=height,
270
+ nlon=width,
271
+ lmax=modes_height,
272
+ mmax=modes_width,
273
+ grid=grid,
274
+ norm=norm,
275
+ )
276
+ .to(device=x.device)
277
+ .to(dtype=self.dtype)
278
+ )
279
+ self._iSHT_cache[cache_key] = isht
280
+
281
+ return isht(x)
282
+
283
+
284
+ class SphericalConv(BaseSpectralConv):
285
+ """Spherical Convolution for the SFNO.
286
+
287
+ It is implemented as described in [1]_.
288
+
289
+ Parameters
290
+ ----------
291
+ sht_norm : str, {'ortho'}
292
+ sht_grids : str or str list, default is "equiangular", {"equiangular", "legendre-gauss"}
293
+ * If str, the same grid is used for all layers
294
+ * If list, should have n_layers + 1 values, corresponding to the input and output grid of each layer
295
+ e.g. for 1 layer, ["input_grid", "output_grid"]
296
+
297
+ See SpectralConv for full list of other parameters
298
+
299
+ References
300
+ ----------
301
+ .. [1] Spherical Fourier Neural Operators: Learning Stable Dynamics on the Sphere,
302
+ Boris Bonev, Thorsten Kurth, Christian Hundt, Jaideep Pathak, Maximilian Baust, Karthik Kashinath, Anima Anandkumar,
303
+ ICML 2023.
304
+ """
305
+
306
+ def __init__(
307
+ self,
308
+ in_channels,
309
+ out_channels,
310
+ n_modes,
311
+ max_n_modes=None,
312
+ bias=True,
313
+ separable=False,
314
+ resolution_scaling_factor: Optional[Union[Number, List[Number]]] = None,
315
+ fno_block_precision="full",
316
+ rank=0.5,
317
+ factorization="cp",
318
+ implementation="reconstructed",
319
+ fixed_rank_modes=False,
320
+ joint_factorization=False,
321
+ decomposition_kwargs=dict(),
322
+ init_std="auto",
323
+ sht_norm="ortho",
324
+ sht_grids="equiangular",
325
+ device=None,
326
+ dtype=torch.float32,
327
+ complex_data=False, # dummy param until we unify dtype interface
328
+ ):
329
+ super().__init__(dtype=dtype, device=device)
330
+
331
+ self.in_channels = in_channels
332
+ self.out_channels = out_channels
333
+ self.joint_factorization = joint_factorization
334
+
335
+ if isinstance(n_modes, int):
336
+ n_modes = [n_modes]
337
+ self._n_modes = n_modes
338
+ self.order = len(n_modes)
339
+
340
+ if max_n_modes is None:
341
+ max_n_modes = self.n_modes
342
+ elif isinstance(max_n_modes, int):
343
+ max_n_modes = [max_n_modes]
344
+ self.max_n_modes = max_n_modes
345
+
346
+ self.rank = rank
347
+ self.factorization = factorization
348
+ self.implementation = implementation
349
+
350
+ self.resolution_scaling_factor: Union[
351
+ None, List[List[float]]
352
+ ] = validate_scaling_factor(resolution_scaling_factor, self.order)
353
+
354
+ if init_std == "auto":
355
+ init_std = (2 / (in_channels + out_channels)) ** 0.5
356
+
357
+ if isinstance(fixed_rank_modes, bool):
358
+ if fixed_rank_modes:
359
+ # If bool, keep the number of layers fixed
360
+ fixed_rank_modes = [0]
361
+ else:
362
+ fixed_rank_modes = None
363
+
364
+ # Make sure we are using a Complex Factorized Tensor to parametrize the conv
365
+ if factorization is None:
366
+ factorization = "Dense" # No factorization
367
+ if not factorization.lower().startswith("complex"):
368
+ factorization = f"Complex{factorization}"
369
+
370
+ if separable:
371
+ if in_channels != out_channels:
372
+ raise ValueError(
373
+ "To use separable Fourier Conv, in_channels must be equal "
374
+ f"to out_channels, but got in_channels={in_channels} "
375
+ f"and out_channels={out_channels}",
376
+ )
377
+ weight_shape = (in_channels, *self.n_modes[:-1])
378
+ else:
379
+ weight_shape = (in_channels, out_channels, *self.n_modes[:-1])
380
+ self.separable = separable
381
+ self.weight = FactorizedTensor.new(
382
+ weight_shape,
383
+ rank=self.rank,
384
+ factorization=factorization,
385
+ fixed_rank_modes=fixed_rank_modes,
386
+ **decomposition_kwargs,
387
+ )
388
+ self.weight.normal_(0, init_std)
389
+
390
+ self._contract = get_contract_fun(
391
+ self.weight, implementation=implementation, separable=separable
392
+ )
393
+
394
+ if bias:
395
+ self.bias = nn.Parameter(
396
+ init_std
397
+ * torch.randn(*(tuple([self.out_channels]) + (1,) * self.order))
398
+ )
399
+ else:
400
+ self.bias = None
401
+
402
+ self.sht_norm = sht_norm
403
+ if isinstance(sht_grids, str):
404
+ sht_grids = [sht_grids] * 2
405
+ self.sht_grids = sht_grids
406
+ self.sht_handle = SHT(dtype=self.dtype, device=self.device)
407
+
408
+ def transform(self, x, output_shape=None):
409
+ *_, in_height, in_width = x.shape
410
+
411
+ if self.resolution_scaling_factor is not None and output_shape is None:
412
+ height = round(in_height * self.resolution_scaling_factor[0])
413
+ width = round(in_width * self.resolution_scaling_factor[1])
414
+ elif output_shape is not None:
415
+ height, width = output_shape[0], output_shape[1]
416
+ else:
417
+ height, width = in_height, in_width
418
+
419
+ # Return the identity if the resolution and grid of the input and output are the same
420
+ if ((in_height, in_width) == (height, width)) and (self.sht_grids[0] == self.sht_grids[1]):
421
+ return x
422
+ else:
423
+ coefs = self.sht_handle.sht(
424
+ x, s=self.n_modes, norm=self.sht_norm, grid=self.sht_grids[0]
425
+ )
426
+ return self.sht_handle.isht(
427
+ coefs, s=(height, width), norm=self.sht_norm, grid=self.sht_grids[1]
428
+ )
429
+
430
+ def forward(self, x, output_shape=None):
431
+ """Generic forward pass for the Factorized Spectral Conv
432
+
433
+ Parameters
434
+ ----------
435
+ x : torch.Tensor
436
+ input activation of size (batch_size, channels, d1, ..., dN)
437
+
438
+ Returns
439
+ -------
440
+ tensorized_spectral_conv(x)
441
+ """
442
+ batchsize, channels, height, width = x.shape
443
+
444
+ if self.resolution_scaling_factor is not None and output_shape is None:
445
+ scaling_factors = self.resolution_scaling_factor
446
+ height = round(height * scaling_factors[0])
447
+ width = round(width * scaling_factors[1])
448
+ elif output_shape is not None:
449
+ height, width = output_shape[0], output_shape[1]
450
+
451
+ out_fft = self.sht_handle.sht(
452
+ x,
453
+ s=(self.n_modes[0], self.n_modes[1] // 2),
454
+ norm=self.sht_norm,
455
+ grid=self.sht_grids[0],
456
+ )
457
+
458
+ out_fft = self._contract(
459
+ out_fft[:, :, : self.n_modes[0], : self.n_modes[1] // 2],
460
+ self.weight[:, :, : self.n_modes[0]],
461
+ separable=self.separable,
462
+ dhconv=True,
463
+ )
464
+
465
+ x = self.sht_handle.isht(
466
+ out_fft, s=(height, width), norm=self.sht_norm, grid=self.sht_grids[1]
467
+ )
468
+
469
+ if self.bias is not None:
470
+ x = x + self.bias
471
+
472
+ return x
473
+
474
+ @property
475
+ def n_modes(self):
476
+ return self._n_modes
477
+
478
+ @n_modes.setter
479
+ def n_modes(self, n_modes):
480
+ if isinstance(n_modes, int): # Should happen for 1D FNO only
481
+ n_modes = [n_modes]
482
+ else:
483
+ n_modes = list(n_modes)
484
+ self._n_modes = n_modes
sources/neuraloperator/neuralop/layers/tests/__init__.py ADDED
File without changes
sources/neuraloperator/neuralop/layers/tests/test_attention_layer.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ..attention_kernel_integral import AttentionKernelIntegral
4
+ from ..embeddings import RotaryEmbedding2D
5
+
6
+
7
+ def test_AttentionWithRoPE():
8
+ """Test for Attention kernel integral with rotary position embeddings
9
+
10
+ Checks the output size
11
+ """
12
+ head_n_channels = 32
13
+ channels = 32
14
+ num_heads = 4
15
+ n_dim = 2
16
+ num_points = 64
17
+ batch_size = 4
18
+
19
+ attn_layer = AttentionKernelIntegral(channels, channels, num_heads, head_n_channels)
20
+ pos_emb_module = RotaryEmbedding2D(head_n_channels // n_dim)
21
+
22
+ x = torch.randn(batch_size, num_points, channels)
23
+ pos = torch.randn(batch_size, num_points, n_dim)
24
+
25
+ freqs_0 = pos_emb_module(pos[..., 0])
26
+ assert freqs_0.shape == (batch_size, num_points, head_n_channels // n_dim)
27
+
28
+ freqs_1 = pos_emb_module(pos[..., 1])
29
+ assert freqs_1.shape == (batch_size, num_points, head_n_channels // n_dim)
30
+
31
+ res = attn_layer(x, pos, positional_embedding_module=pos_emb_module)
32
+ assert res.shape == (batch_size, num_points, channels)
sources/neuraloperator/neuralop/layers/tests/test_coda_layer.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ..coda_layer import *
4
+ from ..spectral_convolution import *
5
+
6
+ device = "cuda" if torch.backends.cuda.is_built() else "cpu"
7
+ # device = 'cpu'
8
+
9
+
10
+ @pytest.mark.parametrize("token_codimension", [1, 2, 5])
11
+ @pytest.mark.parametrize("n_dim", [2, 3])
12
+ @pytest.mark.parametrize("norm", ["instance_norm", None])
13
+ @pytest.mark.parametrize("nonlinear_attention", ["True", "False"])
14
+ @pytest.mark.parametrize("per_channel_attention", ["False", "True"])
15
+ @pytest.mark.parametrize("output_scale", [1, 2])
16
+ def test_Codano(
17
+ token_codimension,
18
+ n_dim,
19
+ norm,
20
+ nonlinear_attention,
21
+ per_channel_attention,
22
+ output_scale,
23
+ ):
24
+ """
25
+ Test CoDA-NO layers
26
+ """
27
+ n_modes = [64] * n_dim
28
+ n_heads = 3
29
+ head_codimension = 3
30
+ codimension_size = None
31
+ permutation_eq = True
32
+ temperature = 1.0
33
+
34
+ layer = CODALayer(
35
+ n_modes=n_modes,
36
+ n_heads=n_heads,
37
+ token_codimension=token_codimension,
38
+ head_codimension=head_codimension,
39
+ norm=norm,
40
+ codimension_size=codimension_size,
41
+ per_channel_attention=per_channel_attention,
42
+ permutation_eq=permutation_eq,
43
+ temperature=temperature,
44
+ nonlinear_attention=nonlinear_attention,
45
+ ).to(device)
46
+
47
+ spatial_res = [64] * n_dim
48
+ x = torch.randn(2, 10, *spatial_res).to(device)
49
+ output_shape = [int(s * output_scale) for s in spatial_res]
50
+ out = layer(x, output_shape)
51
+ assert list(out.shape[-n_dim:]) == output_shape
52
+
53
+ # test different spatial resolution
54
+ spatial_res = [48] * n_dim
55
+ x = torch.randn(2, 10, *spatial_res).to(device)
56
+ out = layer(x)
57
+ assert out.shape == x.shape
sources/neuraloperator/neuralop/layers/tests/test_disco_conv.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+
4
+ # Skip tests if torch_harmonics is not installed
5
+ try:
6
+ import torch_harmonics
7
+ except ModuleNotFoundError:
8
+ pytest.skip(
9
+ "Skipping because torch_harmonics is not installed", allow_module_level=True
10
+ )
11
+
12
+ from ..discrete_continuous_convolution import (
13
+ DiscreteContinuousConv2d,
14
+ DiscreteContinuousConvTranspose2d,
15
+ EquidistantDiscreteContinuousConv2d,
16
+ EquidistantDiscreteContinuousConvTranspose2d,
17
+ )
18
+
19
+ from ..embeddings import regular_grid_2d
20
+
21
+ # global params
22
+ batch_size = 4
23
+ in_channels = 6
24
+ out_channels = 3
25
+ side_length_in = 64
26
+ side_length_out = 48
27
+
28
+ device = "cuda" if torch.backends.cuda.is_built() else "cpu"
29
+
30
+
31
+ @pytest.mark.parametrize(
32
+ "conv_type", [DiscreteContinuousConv2d, DiscreteContinuousConvTranspose2d]
33
+ )
34
+ @pytest.mark.parametrize("groups", [1, 3])
35
+ @pytest.mark.parametrize("basis_type", ["piecewise_linear", "morlet", "zernike"])
36
+ def test_regular_disco_conv2d(conv_type, groups, basis_type):
37
+ # create regular grids of in and output coords
38
+ grid_in = torch.stack(
39
+ regular_grid_2d(spatial_dims=[side_length_in, side_length_in])
40
+ )
41
+ grid_out = torch.stack(
42
+ regular_grid_2d(spatial_dims=[side_length_out, side_length_out])
43
+ )
44
+
45
+ # reshape grids to point clouds (channels, n_pts)
46
+ grid_in = grid_in.view(2, -1)
47
+ grid_out = grid_out.view(2, -1)
48
+
49
+ # quad weights: one weight per point
50
+ quadrature_weights = torch.randn(grid_in.shape[1])
51
+
52
+ conv_layer = conv_type(
53
+ in_channels=in_channels,
54
+ out_channels=out_channels,
55
+ basis_type=basis_type,
56
+ grid_in=grid_in,
57
+ grid_out=grid_out,
58
+ kernel_shape=3,
59
+ quadrature_weights=quadrature_weights,
60
+ groups=groups,
61
+ )
62
+
63
+ # start with a grid, pass to forward as a point cloud
64
+ x = torch.randn(batch_size, in_channels, side_length_in, side_length_in)
65
+ x = x.reshape(batch_size, in_channels, -1)
66
+
67
+ res = conv_layer(x)
68
+ assert res.shape == (batch_size, out_channels, side_length_out**2)
69
+
70
+
71
+ @pytest.mark.parametrize(
72
+ "conv_type",
73
+ [EquidistantDiscreteContinuousConv2d, EquidistantDiscreteContinuousConvTranspose2d],
74
+ )
75
+ @pytest.mark.parametrize("groups", [1, 3])
76
+ @pytest.mark.parametrize("basis_type", ["piecewise_linear", "morlet", "zernike"])
77
+ def test_equidistant_disco_conv2d(conv_type, groups, basis_type):
78
+ in_shape = (side_length_in, side_length_in)
79
+ if conv_type == EquidistantDiscreteContinuousConv2d:
80
+ out_shape = (side_length_in // 2, side_length_in // 2)
81
+ else:
82
+ out_shape = (side_length_in * 2, side_length_in * 2)
83
+
84
+ conv_layer = conv_type(
85
+ in_channels=in_channels,
86
+ out_channels=out_channels,
87
+ in_shape=in_shape,
88
+ out_shape=out_shape,
89
+ basis_type=basis_type,
90
+ kernel_shape=3,
91
+ groups=groups,
92
+ )
93
+
94
+ # start with a grid, pass to forward as a grid
95
+ x = torch.randn(batch_size, in_channels, *in_shape)
96
+
97
+ res = conv_layer(x)
98
+ assert res.shape == (batch_size, out_channels, *out_shape)
sources/neuraloperator/neuralop/layers/tests/test_finite_difference_conv.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ####### ####### #######
2
+ # This script discretizes a parabola on a 2d grid and check to see that
3
+ # the output converges to the theoretical limit.
4
+ ####### ####### #######
5
+
6
+ import pytest
7
+ import numpy as np
8
+ import torch
9
+ import math
10
+
11
+ from ..differential_conv import FiniteDifferenceConvolution
12
+
13
+
14
+ def get_grid(S, batchsize, device):
15
+ gridx = torch.tensor(np.linspace(0, 1, S), dtype=torch.float)
16
+ gridx = gridx.reshape(1, 1, S, 1).repeat([batchsize, 1, 1, S])
17
+ gridy = torch.tensor(np.linspace(0, 1, S), dtype=torch.float)
18
+ gridy = gridy.reshape(1, 1, 1, S).repeat([batchsize, 1, S, 1])
19
+ return torch.cat((gridx, gridy), dim=1).to(device)
20
+
21
+
22
+ @pytest.mark.parametrize("resolution", [500, 700, 1000])
23
+ def test_convergence_FiniteDifferenceConvolution_subtract_middle(resolution):
24
+ torch.manual_seed(0)
25
+ device = torch.device("cpu")
26
+
27
+ num_channels = 10
28
+ kernel_size = 3
29
+ coeff = torch.rand((num_channels,))
30
+
31
+ differential_block = FiniteDifferenceConvolution(
32
+ in_channels=num_channels,
33
+ out_channels=1,
34
+ n_dim=2,
35
+ kernel_size=kernel_size,
36
+ groups=1, # mixing derivatives
37
+ ).to(device)
38
+
39
+ with torch.no_grad():
40
+ weight = differential_block.conv.weight[0] # [0] because output channels is 1
41
+
42
+ diff_block_output_list = []
43
+ grid_width = 1 / resolution
44
+ grid = get_grid(resolution, 1, device)
45
+
46
+ channels = [
47
+ torch.sum(coeff[i] * torch.square(grid), dim=1) for i in range(num_channels)
48
+ ]
49
+ parabola = torch.stack(channels, dim=1).to(device)
50
+
51
+ diff_block_output = differential_block(parabola, grid_width)
52
+ diff_block_output_list.append(diff_block_output)
53
+
54
+ theoretical_value = 0
55
+ for k in range(num_channels):
56
+ direction_k = 0
57
+ for i in range(kernel_size):
58
+ for j in range(kernel_size):
59
+ direction_k += weight[k, i, j] * torch.tensor(
60
+ [[[[i - kernel_size // 2, j - kernel_size // 2]]]]
61
+ ).to(device)
62
+ direction_k = direction_k.movedim(-1, 1).repeat([1, 1, resolution, resolution])
63
+ theoretical_value += 2 * coeff[k] * torch.sum(grid * direction_k, dim=1)
64
+
65
+ error = 1/(resolution-2) * torch.norm(diff_block_output.squeeze()[1:-1, 1:-1] - theoretical_value.squeeze()[1:-1, 1:-1]).item()
66
+
67
+ assert math.isclose(0, error, abs_tol=0.1)
sources/neuraloperator/neuralop/layers/tests/test_fno_block.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ..fno_block import FNOBlocks
4
+
5
+
6
+ def test_FNOBlock_resolution_scaling_factor():
7
+ """Test FNOBlocks with upsampled or downsampled outputs"""
8
+ max_n_modes = [8, 8, 8, 8]
9
+ n_modes = [4, 4, 4, 4]
10
+
11
+ size = [10] * 4
12
+ channel_mlp_dropout = 0
13
+ channel_mlp_expansion = 0.5
14
+ channel_mlp_skip = "linear"
15
+ for dim in [1, 2, 3, 4]:
16
+ block = FNOBlocks(
17
+ 3,
18
+ 4,
19
+ max_n_modes[:dim],
20
+ max_n_modes=max_n_modes[:dim],
21
+ n_layers=1,
22
+ channel_mlp_skip=channel_mlp_skip,
23
+ )
24
+
25
+ assert block.convs[0].n_modes[:-1] == max_n_modes[: dim - 1]
26
+ assert block.convs[0].n_modes[-1] == max_n_modes[dim - 1] // 2 + 1
27
+
28
+ block.n_modes = n_modes[:dim]
29
+ assert block.convs[0].n_modes[:-1] == n_modes[: dim - 1]
30
+ assert block.convs[0].n_modes[-1] == n_modes[dim - 1] // 2 + 1
31
+
32
+ block.n_modes = max_n_modes[:dim]
33
+ assert block.convs[0].n_modes[:-1] == max_n_modes[: dim - 1]
34
+ assert block.convs[0].n_modes[-1] == max_n_modes[dim - 1] // 2 + 1
35
+
36
+ # Downsample outputs
37
+ block = FNOBlocks(
38
+ 3,
39
+ 4,
40
+ n_modes[:dim],
41
+ n_layers=1,
42
+ resolution_scaling_factor=0.5,
43
+ use_channel_mlp=True,
44
+ channel_mlp_dropout=channel_mlp_dropout,
45
+ channel_mlp_expansion=channel_mlp_expansion,
46
+ channel_mlp_skip=channel_mlp_skip,
47
+ )
48
+
49
+ x = torch.randn(2, 3, *size[:dim])
50
+ res = block(x)
51
+ assert list(res.shape[2:]) == [m // 2 for m in size[:dim]]
52
+
53
+ # Upsample outputs
54
+ block = FNOBlocks(
55
+ 3,
56
+ 4,
57
+ n_modes[:dim],
58
+ n_layers=1,
59
+ resolution_scaling_factor=2,
60
+ channel_mlp_dropout=channel_mlp_dropout,
61
+ channel_mlp_expansion=channel_mlp_expansion,
62
+ channel_mlp_skip=channel_mlp_skip,
63
+ )
64
+
65
+ x = torch.randn(2, 3, *size[:dim])
66
+ res = block(x)
67
+ assert res.shape[1] == 4 # Check out channels
68
+ assert list(res.shape[2:]) == [m * 2 for m in size[:dim]]
69
+
70
+
71
+ @pytest.mark.parametrize("n_dim", [1, 2, 3, 4])
72
+ @pytest.mark.parametrize(
73
+ "norm", ["instance_norm", "ada_in", "group_norm", "batch_norm"]
74
+ )
75
+ def test_FNOBlock_norm(norm, n_dim):
76
+ """Test SpectralConv with upsampled or downsampled outputs"""
77
+ modes = (8, 8, 8)
78
+ size = [10] * 3
79
+ channel_mlp_dropout = 0
80
+ channel_mlp_expansion = 0.5
81
+ channel_mlp_skip = "linear"
82
+ ada_in_features = 4
83
+ block = FNOBlocks(
84
+ 3,
85
+ 4,
86
+ modes[:n_dim],
87
+ n_layers=1,
88
+ norm=norm,
89
+ ada_in_features=ada_in_features,
90
+ channel_mlp_dropout=channel_mlp_dropout,
91
+ channel_mlp_expansion=channel_mlp_expansion,
92
+ channel_mlp_skip=channel_mlp_skip,
93
+ )
94
+
95
+ if norm == "ada_in":
96
+ embedding = torch.randn(ada_in_features)
97
+ block.set_ada_in_embeddings(embedding)
98
+
99
+ x = torch.randn(2, 3, *size[:n_dim])
100
+ res = block(x)
101
+ assert list(res.shape[2:]) == size[:n_dim]
102
+
103
+
104
+ @pytest.mark.parametrize("norm_groups", [1, 2, 4, 8])
105
+ def test_FNOBlock_group_norm(norm_groups):
106
+ """Test FNOBlocks with group_norm and custom norm_groups"""
107
+ modes = (8, 8, 8)
108
+ hidden_channels = 16
109
+ n_layers = 1
110
+
111
+ block = FNOBlocks(
112
+ in_channels=hidden_channels,
113
+ out_channels=hidden_channels,
114
+ n_modes=modes,
115
+ n_layers=n_layers,
116
+ norm="group_norm",
117
+ norm_groups=norm_groups,
118
+ )
119
+
120
+ # Check that GroupNorm layers are correctly initialized
121
+ assert block.norm is not None
122
+ for norm_layer in block.norm:
123
+ assert isinstance(norm_layer, torch.nn.GroupNorm)
124
+ assert norm_layer.num_groups == norm_groups
125
+ assert norm_layer.num_channels == hidden_channels
126
+
127
+
128
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
129
+ def test_FNOBlock_complex_data(n_dim):
130
+ """Test FNO layers with complex input data"""
131
+ modes = (8, 8, 8)
132
+ size = [10] * 3
133
+ channel_mlp_dropout = 0
134
+ channel_mlp_expansion = 0.5
135
+ channel_mlp_skip = "linear"
136
+ # Instantiate a complex-valued FNO block
137
+ block = FNOBlocks(
138
+ 3,
139
+ 4,
140
+ modes[:n_dim],
141
+ n_layers=1,
142
+ channel_mlp_dropout=channel_mlp_dropout,
143
+ channel_mlp_expansion=channel_mlp_expansion,
144
+ channel_mlp_skip=channel_mlp_skip,
145
+ complex_data=True,
146
+ )
147
+
148
+ x = torch.randn(2, 3, *size[:n_dim], dtype=torch.cfloat)
149
+ res = block(x)
150
+
151
+ assert list(res.shape[2:]) == size[:n_dim]
152
+
153
+
154
+ @pytest.mark.parametrize("fno_skip", ["linear", None])
155
+ @pytest.mark.parametrize("channel_mlp_skip", ["linear", None])
156
+ def test_FNOBlock_skip_connections(fno_skip, channel_mlp_skip):
157
+ """Test FNOBlocks with different skip connection options including None"""
158
+ modes = (8, 8, 8)
159
+ size = [10, 10, 10]
160
+
161
+ # Skip test cases that are incompatible
162
+ # Soft-gating requires same input/output channels
163
+ if fno_skip == "soft-gating" or channel_mlp_skip == "soft-gating":
164
+ pytest.skip("Soft-gating requires same input/output channels")
165
+
166
+ # Test with channel MLP enabled
167
+ block = FNOBlocks(
168
+ 3,
169
+ 4,
170
+ modes,
171
+ n_layers=2,
172
+ fno_skip=fno_skip,
173
+ channel_mlp_skip=channel_mlp_skip,
174
+ use_channel_mlp=True,
175
+ channel_mlp_expansion=0.5,
176
+ channel_mlp_dropout=0.0,
177
+ )
178
+
179
+ x = torch.randn(2, 3, *size)
180
+ res = block(x)
181
+
182
+ # Check output shape
183
+ assert res.shape == (2, 4, *size)
184
+
185
+ # Test with channel MLP disabled
186
+ block_no_mlp = FNOBlocks(
187
+ 3,
188
+ 4,
189
+ modes,
190
+ n_layers=2,
191
+ fno_skip=fno_skip,
192
+ channel_mlp_skip=channel_mlp_skip,
193
+ use_channel_mlp=False,
194
+ )
195
+
196
+ res_no_mlp = block_no_mlp(x)
197
+ assert res_no_mlp.shape == (2, 4, *size)
198
+
199
+
200
+ @pytest.mark.parametrize("fno_skip", ["linear", None])
201
+ @pytest.mark.parametrize("channel_mlp_skip", ["linear", None])
202
+ def test_FNOBlock_skip_connections_preactivation(fno_skip, channel_mlp_skip):
203
+ """Test FNOBlocks with preactivation and different skip connection options"""
204
+ modes = (8, 8, 8)
205
+ size = [10, 10, 10]
206
+
207
+ # Test with preactivation enabled
208
+ block = FNOBlocks(
209
+ 3,
210
+ 4,
211
+ modes,
212
+ n_layers=2,
213
+ fno_skip=fno_skip,
214
+ channel_mlp_skip=channel_mlp_skip,
215
+ use_channel_mlp=True,
216
+ channel_mlp_expansion=0.5,
217
+ channel_mlp_dropout=0.0,
218
+ preactivation=True,
219
+ )
220
+
221
+ x = torch.randn(2, 3, *size)
222
+ res = block(x)
223
+
224
+ # Check output shape
225
+ assert res.shape == (2, 4, *size)
226
+
227
+
228
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
229
+ def test_FNOBlock_conv_bias_kernel(n_dim):
230
+ """Test local convolutional bias kernels beside spectral convolution."""
231
+ modes = (8, 8, 8)
232
+ size = [10, 10, 10]
233
+ conv_bias_kernel = 3
234
+
235
+ block = FNOBlocks(
236
+ 3,
237
+ 4,
238
+ modes[:n_dim],
239
+ n_layers=2,
240
+ conv_bias_kernel=conv_bias_kernel,
241
+ fno_skip="linear",
242
+ use_channel_mlp=False,
243
+ )
244
+
245
+ x = torch.randn(2, 3, *size[:n_dim])
246
+ res = block(x)
247
+
248
+ assert res.shape == (2, 4, *size[:n_dim])
249
+ assert block.conv_bias_kernel == conv_bias_kernel
250
+ assert block.fno_skips[0].kernel_size == (conv_bias_kernel,) * n_dim
sources/neuraloperator/neuralop/layers/tests/test_fourier_continuation.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytest
3
+ from ..fourier_continuation import FCLegendre, FCGram
4
+
5
+
6
+ @pytest.mark.parametrize("FC_class", [FCLegendre, FCGram])
7
+ @pytest.mark.parametrize("dim", [1, 2, 3])
8
+ @pytest.mark.parametrize("d", [3, 4])
9
+ def test_fourier_continuation(FC_class, dim: int, d: int):
10
+ if dim == 1:
11
+ batch_size = 3
12
+ length_signal = 101
13
+ add_pts = 50
14
+
15
+ x = torch.linspace(0, 1, length_signal).repeat(batch_size, 1)
16
+ f = torch.sin(16 * x) - torch.cos(8 * x)
17
+
18
+ Extension = FC_class(d=d, n_additional_pts=add_pts)
19
+
20
+ f_extend = Extension(f, dim=1)
21
+
22
+ # Check shape
23
+ assert f_extend.shape[-1] == f.shape[-1] + add_pts
24
+ # Check values of original signal
25
+ torch.testing.assert_close(f, f_extend[..., add_pts // 2 : -add_pts // 2])
26
+
27
+ if dim == 2:
28
+ batch_size = 3
29
+ length_signal = 101
30
+ add_pts = 50
31
+
32
+ x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1).repeat(batch_size, 1, length_signal)
33
+ y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal).repeat(batch_size, length_signal, 1)
34
+ f = torch.sin(12 * x) - torch.cos(14 * y) + 3*x*y
35
+
36
+ Extension = FC_class(d=d, n_additional_pts=add_pts)
37
+
38
+ f_extend = Extension(f, dim=2)
39
+
40
+ # Check shape
41
+ assert f_extend.shape[-1] == f.shape[-1] + add_pts
42
+ assert f_extend.shape[-2] == f.shape[-2] + add_pts
43
+ # Check values of original signal
44
+ torch.testing.assert_close(
45
+ f, f_extend[..., add_pts // 2 : -add_pts // 2, add_pts // 2 : -add_pts // 2]
46
+ )
47
+
48
+ if dim == 3:
49
+ batch_size = 2
50
+ length_signal = 81
51
+ add_pts = 50
52
+
53
+ # Create 3D grid
54
+ x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1, 1).repeat(batch_size, 1, length_signal, length_signal)
55
+ y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal, 1).repeat(batch_size, length_signal, 1, length_signal)
56
+ z = torch.linspace(0, 1, length_signal).view(1, 1, 1, length_signal).repeat(batch_size, length_signal, length_signal, 1)
57
+
58
+ # Create 3D function
59
+ f = torch.exp(-2*z) + 2*z*x + torch.sin(12*x*y) + y*torch.sin(10*y*z)
60
+
61
+ Extension = FC_class(d=d, n_additional_pts=add_pts)
62
+
63
+ f_extend = Extension(f, dim=3)
64
+
65
+ # Check shape
66
+ assert f_extend.shape[-1] == f.shape[-1] + add_pts
67
+ assert f_extend.shape[-2] == f.shape[-2] + add_pts
68
+ assert f_extend.shape[-3] == f.shape[-3] + add_pts
69
+ # Check values of original signal
70
+ torch.testing.assert_close(
71
+ f,
72
+ f_extend[
73
+ ...,
74
+ add_pts // 2 : -add_pts // 2,
75
+ add_pts // 2 : -add_pts // 2,
76
+ add_pts // 2 : -add_pts // 2,
77
+ ],
78
+ )
79
+
80
+
81
+ @pytest.mark.parametrize("FC_class", [FCLegendre, FCGram])
82
+ @pytest.mark.parametrize(
83
+ "dim_tuple",
84
+ [(1,), (2,), (1, 2), (1, 3), (2, 3), (-1,), (-2,), (-1, -2), (-1, -3), (1, -1)],
85
+ )
86
+ @pytest.mark.parametrize("d", [3, 4])
87
+ def test_fourier_continuation_tuple_dims(FC_class, dim_tuple, d: int):
88
+ """
89
+ Test Fourier continuation with tuple dimensions.
90
+
91
+ Tests various combinations of positive and negative axis indices
92
+ to ensure the extension works correctly along specific axes.
93
+ """
94
+ batch_size = 2
95
+ add_pts = 30
96
+
97
+ # Create a 4D tensor for comprehensive testing
98
+ x = torch.randn(batch_size, 20, 25, 30)
99
+
100
+ try:
101
+ Extension = FC_class(d=d, n_additional_pts=add_pts)
102
+ except FileNotFoundError as e:
103
+ if FC_class.__name__ == "FCGram":
104
+ pytest.skip(f"FCGram matrices not available: {e}")
105
+ else:
106
+ raise
107
+
108
+ # Extend along specified dimensions
109
+ f_extend = Extension(x, dim=dim_tuple)
110
+
111
+ # Calculate expected shape
112
+ expected_shape = list(x.shape)
113
+ for dim in dim_tuple:
114
+ # Convert negative indices to positive
115
+ if dim < 0:
116
+ dim = x.ndim + dim
117
+ expected_shape[dim] += add_pts
118
+
119
+ # Check shape
120
+ assert f_extend.shape == tuple(
121
+ expected_shape
122
+ ), f"Expected shape {tuple(expected_shape)}, got {f_extend.shape}"
123
+
124
+ # Test restrict functionality
125
+ f_restricted = Extension.restrict(f_extend, dim=dim_tuple)
126
+
127
+ # Check that restrict returns original shape
128
+ assert (
129
+ f_restricted.shape == x.shape
130
+ ), f"Restrict failed: expected {x.shape}, got {f_restricted.shape}"
131
+
132
+ # Check that restrict returns original values
133
+ torch.testing.assert_close(
134
+ x, f_restricted, msg="Restrict did not return original values"
135
+ )
sources/neuraloperator/neuralop/layers/tests/test_gno_block.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.autograd import grad
3
+ import pytest
4
+ from tensorly import tenalg
5
+
6
+ tenalg.set_backend("einsum")
7
+
8
+ # Parameterize use of torch_scatter if it is built
9
+ try:
10
+ from torch_scatter import segment_csr
11
+
12
+ use_torch_scatter = [True, False]
13
+ except:
14
+ use_torch_scatter = [False]
15
+
16
+ from ..gno_block import GNOBlock
17
+
18
+ # Fixed variables
19
+ in_channels = 3
20
+ out_channels = 3
21
+ mlp_hidden_layers = [16, 16, 16]
22
+
23
+ # data parameters
24
+ n_in = 100
25
+ n_out = 100
26
+
27
+ # test open3d mode if built
28
+ try:
29
+ from neighbor_search import FixedRadiusSearch
30
+
31
+ open3d_built = True
32
+ except:
33
+ open3d_built = False
34
+
35
+ if open3d_built:
36
+ use_open3d_parametrize = [True, False]
37
+ else:
38
+ use_open3d_parametrize = [False]
39
+
40
+
41
+ @pytest.mark.parametrize("batch_size", [1, 4])
42
+ @pytest.mark.parametrize("gno_coord_dim", [2, 3])
43
+ @pytest.mark.parametrize("gno_pos_embed_type", ["nerf", "transformer", None])
44
+ @pytest.mark.parametrize(
45
+ "gno_transform_type", ["linear", "nonlinear_kernelonly", "nonlinear"]
46
+ )
47
+ @pytest.mark.parametrize("use_open3d", use_open3d_parametrize)
48
+ @pytest.mark.parametrize("use_torch_scatter", use_torch_scatter)
49
+ def test_gno_block(
50
+ gno_transform_type,
51
+ gno_coord_dim,
52
+ gno_pos_embed_type,
53
+ batch_size,
54
+ use_open3d,
55
+ use_torch_scatter,
56
+ ):
57
+ if torch.backends.cuda.is_built():
58
+ device = torch.device("cuda:0")
59
+ else:
60
+ device = torch.device("cpu:0")
61
+
62
+ use_open3d = use_open3d and (gno_coord_dim == 3)
63
+
64
+ gno_block = GNOBlock(
65
+ in_channels=in_channels,
66
+ out_channels=out_channels, # dummy var currently
67
+ coord_dim=gno_coord_dim,
68
+ pos_embedding_type=gno_pos_embed_type,
69
+ radius=0.25,
70
+ channel_mlp_layers=mlp_hidden_layers,
71
+ transform_type=gno_transform_type,
72
+ use_open3d_neighbor_search=use_open3d,
73
+ use_torch_scatter_reduce=use_torch_scatter,
74
+ ).to(device)
75
+
76
+ # create input geometry and output queries
77
+ input_geom_shape = [n_in, gno_coord_dim]
78
+ input_geom = torch.randn(*input_geom_shape, device=device)
79
+
80
+ output_queries_shape = [n_out, gno_coord_dim]
81
+ output_queries = torch.randn(*output_queries_shape, device=device)
82
+
83
+ f_y = None
84
+ if gno_transform_type != "linear":
85
+ # create data and features
86
+ f_y_shape = [batch_size, n_in, in_channels]
87
+ f_y = torch.randn(*f_y_shape, device=device)
88
+ # require and retain grad to check for backprop
89
+ f_y.requires_grad_(True)
90
+
91
+ out = gno_block(y=input_geom, x=output_queries, f_y=f_y)
92
+
93
+ # Check output size
94
+ # Batched outputs only matter in the nonlinear kernel use case
95
+ if gno_transform_type != "linear":
96
+ assert list(out.shape) == [batch_size, n_out, out_channels]
97
+ else:
98
+ assert list(out.shape) == [n_out, out_channels]
99
+
100
+ # Check backward pass
101
+ assert out.isfinite().all()
102
+ if batch_size > 1:
103
+ loss = out[0].sum()
104
+ else:
105
+ loss = out.sum()
106
+ loss.backward()
107
+
108
+ if batch_size > 1 and gno_transform_type != "linear":
109
+ # assert f_y[1:] accumulates no grad if it's used
110
+ assert not f_y.grad[1:].nonzero().any()
sources/neuraloperator/neuralop/layers/tests/test_grid_embeddings.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import torch
4
+ from torch.testing import assert_close
5
+ import pytest
6
+
7
+ from ..embeddings import GridEmbedding2D, GridEmbeddingND
8
+
9
+ # Testing grid-based pos encoding: choose a random grid
10
+ # point and assert the proper encoding is applied there
11
+
12
+
13
+ def test_GridEmbedding2D():
14
+ grid_boundaries = [[0, 1], [0, 1]]
15
+ pos_embed = GridEmbedding2D(in_channels=1, grid_boundaries=grid_boundaries)
16
+
17
+ input_res = (20, 20)
18
+ x = torch.randn(1, 1, *input_res)
19
+ x = pos_embed(x)
20
+
21
+ index = [random.randint(0, res-1) for res in input_res]
22
+ true_coords = x[0,1:,index[0], index[1]].squeeze() # grab pos encoding channels at coord index
23
+ expected_coords = torch.tensor([i/j for i,j in zip(index,input_res)])
24
+ assert_close(true_coords, expected_coords)
25
+
26
+
27
+ @pytest.mark.parametrize("dim", [1, 2, 3, 4])
28
+ def test_GridEmbeddingND(dim):
29
+ grid_boundaries = [[0, 1]] * dim
30
+ pos_embed = GridEmbeddingND(in_channels=1, dim=dim, grid_boundaries=grid_boundaries)
31
+
32
+ input_res = [20] * dim
33
+ x = torch.randn(1, 1, *input_res)
34
+ x = pos_embed(x)
35
+
36
+ index = [random.randint(0, res - 1) for res in input_res]
37
+ # grab pos encoding channels at coord index
38
+ pos_channels = x[0, 1:, ...]
39
+ indices = (slice(None), *index)
40
+ true_coords = pos_channels[indices]
41
+ expected_coords = torch.tensor([i / j for i, j in zip(index, input_res)])
42
+ assert_close(true_coords, expected_coords)
sources/neuraloperator/neuralop/layers/tests/test_legacy_spectral_convolution.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from tltorch import FactorizedTensor
4
+ from ..legacy_spectral_convolution import (
5
+ SpectralConv3d,
6
+ SpectralConv2d,
7
+ SpectralConv1d,
8
+ SpectralConv,
9
+ )
10
+
11
+
12
+ @pytest.mark.parametrize(
13
+ "factorization", ["ComplexDense", "ComplexCP", "ComplexTucker", "ComplexTT"]
14
+ )
15
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
16
+ def test_SpectralConv(factorization, implementation):
17
+ """Test for SpectralConv of any order
18
+
19
+ Compares Factorized and Dense convolution output
20
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
21
+
22
+ Checks the output size
23
+
24
+ Verifies that dynamically changing the number of Fourier modes doesn't break the conv
25
+ """
26
+ modes = (10, 8, 6, 6)
27
+ incremental_modes = (6, 6, 4, 4)
28
+
29
+ # Test for Conv1D to Conv4D
30
+ for dim in [1, 2, 3, 4]:
31
+ conv = SpectralConv(
32
+ 3,
33
+ 3,
34
+ modes[:dim],
35
+ n_layers=1,
36
+ bias=False,
37
+ implementation=implementation,
38
+ factorization=factorization,
39
+ )
40
+
41
+ conv_dense = SpectralConv(
42
+ 3,
43
+ 3,
44
+ modes[:dim],
45
+ n_layers=1,
46
+ bias=False,
47
+ implementation="reconstructed",
48
+ factorization=None,
49
+ )
50
+
51
+ for i in range(2 ** (dim - 1)):
52
+ conv_dense.weight[i] = FactorizedTensor.from_tensor(
53
+ conv.weight[i].to_tensor(), rank=None, factorization="ComplexDense"
54
+ )
55
+
56
+ x = torch.randn(2, 3, *(12,) * dim)
57
+
58
+ res_dense = conv_dense(x)
59
+ res = conv(x)
60
+ res_shape = res.shape
61
+
62
+ torch.testing.assert_close(res_dense, res)
63
+
64
+ # Dynamically reduce the number of modes in Fourier space
65
+ conv.incremental_n_modes = incremental_modes[:dim]
66
+ res = conv(x)
67
+ assert res_shape == res.shape
68
+
69
+ # Downsample outputs
70
+ block = SpectralConv(3, 4, modes[:dim], n_layers=1, resolution_scaling_factor=0.5)
71
+
72
+ x = torch.randn(2, 3, *(12, )*dim)
73
+ res = block(x)
74
+ assert list(res.shape[2:]) == [12 // 2] * dim
75
+
76
+ # Upsample outputs
77
+ block = SpectralConv(3, 4, modes[:dim], n_layers=1, resolution_scaling_factor=2)
78
+
79
+ x = torch.randn(2, 3, *(12,) * dim)
80
+ res = block(x)
81
+ assert res.shape[1] == 4 # Check out channels
82
+ assert list(res.shape[2:]) == [12 * 2] * dim
83
+
84
+
85
+ def test_SpectralConv_resolution_scaling_factor():
86
+ """Test SpectralConv with upsampled or downsampled outputs"""
87
+ modes = (4, 4, 4, 4)
88
+ size = [6] * 4
89
+ for dim in [1, 2, 3, 4]:
90
+ # Downsample outputs
91
+ conv = SpectralConv(
92
+ 3, 3, modes[:dim], n_layers=1, resolution_scaling_factor=0.5
93
+ )
94
+
95
+ x = torch.randn(2, 3, *size[:dim])
96
+ res = conv(x)
97
+ assert list(res.shape[2:]) == [m // 2 for m in size[:dim]]
98
+
99
+ # Upsample outputs
100
+ conv = SpectralConv(3, 3, modes[:dim], n_layers=1, resolution_scaling_factor=2)
101
+
102
+ x = torch.randn(2, 3, *size[:dim])
103
+ res = conv(x)
104
+ assert list(res.shape[2:]) == [m * 2 for m in size[:dim]]
105
+
106
+
107
+ @pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"])
108
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
109
+ def test_SpectralConv3D(factorization, implementation):
110
+ """Compare generic SpectralConv with hand written SpectralConv2D
111
+
112
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
113
+ Note that this implies the order in which the conv is done in the manual implementation matches the automatic one,
114
+ take with a grain of salt
115
+ """
116
+ conv = SpectralConv(
117
+ 3,
118
+ 6,
119
+ (4, 5, 2),
120
+ n_layers=1,
121
+ bias=False,
122
+ implementation=implementation,
123
+ factorization=factorization,
124
+ )
125
+
126
+ conv_dense = SpectralConv3d(
127
+ 3,
128
+ 6,
129
+ (4, 5, 2),
130
+ n_layers=1,
131
+ bias=False,
132
+ implementation="reconstructed",
133
+ factorization=None,
134
+ )
135
+ for i, w in enumerate(conv.weight):
136
+ rec = w.to_tensor()
137
+ dtype = rec.dtype
138
+ assert dtype == torch.cfloat
139
+ conv_dense.weight[i] = FactorizedTensor.from_tensor(
140
+ rec, rank=None, factorization="ComplexDense"
141
+ )
142
+
143
+ x = torch.randn(2, 3, 12, 12, 12)
144
+ res_dense = conv_dense(x)
145
+ res = conv(x)
146
+ torch.testing.assert_close(res_dense, res)
147
+
148
+
149
+ @pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"])
150
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
151
+ def test_SpectralConv2D(factorization, implementation):
152
+ """Compare generic SpectralConv with hand written SpectralConv2D
153
+
154
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
155
+ Note that this implies the order in which the conv is done in the manual implementation matches the automatic one,
156
+ take with a grain of salt
157
+ """
158
+ conv = SpectralConv(
159
+ 10,
160
+ 11,
161
+ (4, 5),
162
+ n_layers=1,
163
+ bias=False,
164
+ implementation=implementation,
165
+ factorization=factorization,
166
+ )
167
+
168
+ conv_dense = SpectralConv2d(
169
+ 10,
170
+ 11,
171
+ (4, 5),
172
+ n_layers=1,
173
+ bias=False,
174
+ implementation="reconstructed",
175
+ factorization=None,
176
+ )
177
+ for i, w in enumerate(conv.weight):
178
+ rec = w.to_tensor()
179
+ dtype = rec.dtype
180
+ assert dtype == torch.cfloat
181
+ conv_dense.weight[i] = FactorizedTensor.from_tensor(
182
+ rec, rank=None, factorization="ComplexDense"
183
+ )
184
+
185
+ x = torch.randn(2, 10, 12, 12)
186
+ res_dense = conv_dense(x)
187
+ res = conv(x)
188
+ torch.testing.assert_close(res_dense, res)
189
+
190
+
191
+ @pytest.mark.parametrize("factorization", ["ComplexCP", "ComplexTucker"])
192
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
193
+ def test_SpectralConv1D(factorization, implementation):
194
+ """Test for SpectralConv1D
195
+
196
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
197
+ """
198
+ conv = SpectralConv(
199
+ 10,
200
+ 11,
201
+ (5,),
202
+ n_layers=1,
203
+ bias=False,
204
+ implementation=implementation,
205
+ factorization=factorization,
206
+ )
207
+
208
+ conv_dense = SpectralConv1d(
209
+ 10,
210
+ 11,
211
+ (5,),
212
+ n_layers=1,
213
+ bias=False,
214
+ implementation="reconstructed",
215
+ factorization=None,
216
+ )
217
+ for i, w in enumerate(conv.weight):
218
+ rec = w.to_tensor()
219
+ dtype = rec.dtype
220
+ assert dtype == torch.cfloat
221
+ conv_dense.weight[i] = FactorizedTensor.from_tensor(
222
+ rec, rank=None, factorization="ComplexDense"
223
+ )
224
+
225
+ x = torch.randn(2, 10, 12)
226
+ res_dense = conv_dense(x)
227
+ res = conv(x)
228
+ torch.testing.assert_close(res_dense, res)
sources/neuraloperator/neuralop/layers/tests/test_local_no_block.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+
4
+ try:
5
+ import torch_harmonics
6
+ except ModuleNotFoundError:
7
+ pytest.skip(
8
+ "Skipping because torch_harmonics is not installed", allow_module_level=True
9
+ )
10
+
11
+ from ..local_no_block import LocalNOBlocks
12
+
13
+
14
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
15
+ def test_LocalNOBlock_resolution_scaling_factor(n_dim):
16
+ """Test LocalNOBlocks with upsampled or downsampled outputs"""
17
+ max_n_modes = [8, 8, 8]
18
+ n_modes = [4, 4, 4]
19
+
20
+ size = [10] * 3
21
+ channel_mlp_dropout = 0
22
+ channel_mlp_expansion = 0.5
23
+ channel_mlp_skip = "linear"
24
+ block = LocalNOBlocks(
25
+ 3,
26
+ 4,
27
+ default_in_shape=tuple(size[:n_dim]),
28
+ n_modes=max_n_modes[:n_dim],
29
+ max_n_modes=max_n_modes[:n_dim],
30
+ n_layers=1,
31
+ diff_layers=[True],
32
+ disco_layers=[(n_dim == 2)],
33
+ )
34
+
35
+ assert block.convs[0].n_modes[:-1] == max_n_modes[: n_dim - 1]
36
+ assert block.convs[0].n_modes[-1] == max_n_modes[n_dim - 1] // 2 + 1
37
+
38
+ block.n_modes = n_modes[:n_dim]
39
+ assert block.convs[0].n_modes[:-1] == n_modes[: n_dim - 1]
40
+ assert block.convs[0].n_modes[-1] == n_modes[n_dim - 1] // 2 + 1
41
+
42
+ block.n_modes = max_n_modes[:n_dim]
43
+ assert block.convs[0].n_modes[:-1] == max_n_modes[: n_dim - 1]
44
+ assert block.convs[0].n_modes[-1] == max_n_modes[n_dim - 1] // 2 + 1
45
+
46
+ # Downsample outputs
47
+ block = LocalNOBlocks(
48
+ 3,
49
+ 4,
50
+ n_modes[:n_dim],
51
+ default_in_shape=tuple(size[:n_dim]),
52
+ n_layers=1,
53
+ diff_layers=[True],
54
+ disco_layers=[(n_dim == 2)],
55
+ resolution_scaling_factor=0.5,
56
+ use_channel_mlp=True,
57
+ channel_mlp_dropout=channel_mlp_dropout,
58
+ channel_mlp_expansion=channel_mlp_expansion,
59
+ channel_mlp_skip=channel_mlp_skip,
60
+ )
61
+
62
+ x = torch.randn(2, 3, *size[:n_dim])
63
+ res = block(x)
64
+ assert list(res.shape[2:]) == [m // 2 for m in size[:n_dim]]
65
+
66
+ # Upsample outputs
67
+ block = LocalNOBlocks(
68
+ 3,
69
+ 4,
70
+ n_modes[:n_dim],
71
+ default_in_shape=tuple(size[:n_dim]),
72
+ n_layers=1,
73
+ diff_layers=[True],
74
+ disco_layers=[(n_dim == 2)],
75
+ resolution_scaling_factor=2,
76
+ use_channel_mlp=True,
77
+ channel_mlp_dropout=channel_mlp_dropout,
78
+ channel_mlp_expansion=channel_mlp_expansion,
79
+ channel_mlp_skip=channel_mlp_skip,
80
+ )
81
+
82
+ x = torch.randn(2, 3, *size[:n_dim])
83
+ res = block(x)
84
+ assert res.shape[1] == 4 # Check out channels
85
+ assert list(res.shape[2:]) == [m * 2 for m in size[:n_dim]]
86
+
87
+
88
+ @pytest.mark.parametrize("norm", ["instance_norm", "ada_in", "group_norm"])
89
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
90
+ def test_LocalNOBlock_norm(norm, n_dim):
91
+ """Test LocalNOBlock with normalization"""
92
+ modes = (8, 8, 8)
93
+ size = [10] * 3
94
+ channel_mlp_dropout = 0
95
+ channel_mlp_expansion = 0.5
96
+ channel_mlp_skip = "linear"
97
+ ada_in_features = 4
98
+ block = LocalNOBlocks(
99
+ 3,
100
+ 4,
101
+ modes[:n_dim],
102
+ default_in_shape=tuple(size[:n_dim]),
103
+ n_layers=1,
104
+ diff_layers=[True],
105
+ disco_layers=[(n_dim == 2)],
106
+ use_channel_mlp=True,
107
+ norm=norm,
108
+ ada_in_features=ada_in_features,
109
+ channel_mlp_dropout=channel_mlp_dropout,
110
+ channel_mlp_expansion=channel_mlp_expansion,
111
+ channel_mlp_skip=channel_mlp_skip,
112
+ )
113
+
114
+ if norm == "ada_in":
115
+ embedding = torch.randn(ada_in_features)
116
+ block.set_ada_in_embeddings(embedding)
117
+
118
+ x = torch.randn(2, 3, *size[:n_dim])
119
+ res = block(x)
120
+ assert list(res.shape[2:]) == size[:n_dim]
121
+
122
+
123
+ @pytest.mark.parametrize("local_no_skip", ["linear", None])
124
+ @pytest.mark.parametrize("channel_mlp_skip", ["linear", None])
125
+ def test_LocalNOBlock_skip_connections(local_no_skip, channel_mlp_skip):
126
+ """Test LocalNOBlocks with different skip connection options including None"""
127
+ modes = (8, 8, 8)
128
+ size = [10, 10, 10]
129
+
130
+ # Test with channel MLP enabled
131
+ block = LocalNOBlocks(
132
+ 3,
133
+ 4,
134
+ modes,
135
+ default_in_shape=tuple(size),
136
+ n_layers=2,
137
+ local_no_skip=local_no_skip,
138
+ channel_mlp_skip=channel_mlp_skip,
139
+ use_channel_mlp=True,
140
+ channel_mlp_expansion=0.5,
141
+ channel_mlp_dropout=0.0,
142
+ diff_layers=[True, True],
143
+ disco_layers=[False, False],
144
+ )
145
+
146
+ x = torch.randn(2, 3, *size)
147
+ res = block(x)
148
+
149
+ # Check output shape
150
+ assert res.shape == (2, 4, *size)
151
+
152
+ # Test with channel MLP disabled
153
+ block_no_mlp = LocalNOBlocks(
154
+ 3,
155
+ 4,
156
+ modes,
157
+ default_in_shape=tuple(size),
158
+ n_layers=2,
159
+ local_no_skip=local_no_skip,
160
+ channel_mlp_skip=channel_mlp_skip,
161
+ use_channel_mlp=False,
162
+ diff_layers=[True, True],
163
+ disco_layers=[False, False],
164
+ )
165
+
166
+ res_no_mlp = block_no_mlp(x)
167
+ assert res_no_mlp.shape == (2, 4, *size)
168
+
169
+
170
+ @pytest.mark.parametrize("norm_groups", [1, 2, 4, 8])
171
+ def test_LocalNOBlock_group_norm(norm_groups):
172
+ """Test LocalNOBlocks with group_norm and custom norm_groups"""
173
+ modes = (8, 8)
174
+ hidden_channels = 16
175
+ n_layers = 1
176
+ size = [12] * 2
177
+
178
+ block = LocalNOBlocks(
179
+ in_channels=hidden_channels,
180
+ out_channels=hidden_channels,
181
+ n_modes=modes,
182
+ default_in_shape=tuple(size),
183
+ n_layers=n_layers,
184
+ norm="group_norm",
185
+ norm_groups=norm_groups,
186
+ diff_layers=[True],
187
+ disco_layers=[False],
188
+ )
189
+
190
+ assert block.norm is not None
191
+ for norm_layer in block.norm:
192
+ assert isinstance(norm_layer, torch.nn.GroupNorm)
193
+ assert norm_layer.num_groups == norm_groups
194
+ assert norm_layer.num_channels == hidden_channels
sources/neuraloperator/neuralop/layers/tests/test_neighbor_search.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests fallback neighbor search on a small 2d grid
3
+ that was calculated manually
4
+ """
5
+
6
+ import numpy as np
7
+ import torch
8
+ import pytest
9
+
10
+ from ..neighbor_search import native_neighbor_search
11
+
12
+ # Manually-calculated CSR list of neighbors
13
+ # in a 5x5 grid on [0,1] X [0,1] for radius=0.3
14
+
15
+ indices = [0, 1, 5, 0, 1, 2, 6, 1, 2, 3, 7, 2, 3, 4, 8,
16
+ 3, 4, 9, 0, 5, 6, 10, 1, 5, 6, 7, 11, 2, 6, 7,
17
+ 8, 12, 3, 7, 8, 9, 13, 4, 8, 9, 14, 5, 10, 11,
18
+ 15, 6, 10, 11, 12, 16, 7, 11, 12, 13, 17, 8, 12,
19
+ 13, 14, 18, 9, 13, 14, 19, 10, 15, 16, 20, 11, 15,
20
+ 16, 17, 21, 12, 16, 17, 18, 22, 13, 17, 18, 19, 23,
21
+ 14, 18, 19, 24, 15, 20, 21, 16, 20, 21, 22, 17, 21,
22
+ 22, 23, 18, 22, 23, 24, 19, 23, 24]
23
+
24
+ splits = [0, 3, 7, 11, 15, 18, 22, 27, 32, 37, 41, 45, 50,
25
+ 55, 60, 64, 68, 73, 78, 83, 87, 90, 94, 98, 102, 105]
26
+
27
+ def test_fallback_nb_search():
28
+ mesh_grid = np.stack(
29
+ np.meshgrid(*[np.linspace(0, 1, 5) for _ in range(2)], indexing="ij"), axis=-1
30
+ )
31
+ coords = torch.Tensor(
32
+ mesh_grid.reshape(-1, 2)
33
+ ) # reshape into n**d x d coord points
34
+ return_dict = native_neighbor_search(
35
+ data=coords, queries=coords, radius=0.3, return_norm=True
36
+ )
37
+
38
+ assert return_dict["neighbors_index"].tolist() == indices
39
+ assert return_dict["neighbors_row_splits"].tolist() == splits
40
+ print(f"{return_dict['weights']=}")
41
+
42
+ def compute_norm_separate(nbrs, data, queries):
43
+ return_dict = nbrs
44
+ num_reps = (
45
+ return_dict["neighbors_row_splits"][1:]
46
+ - return_dict["neighbors_row_splits"][:-1]
47
+ )
48
+ rep_queries = torch.repeat_interleave(queries, num_reps, dim=0)
49
+ rep_data = data[return_dict["neighbors_index"]]
50
+ rep_dist = rep_queries - rep_data
51
+ return_dict["squared_norm"] = (rep_dist**2).sum(dim=-1)
52
+ return return_dict
53
+
54
+ return_dict = compute_norm_separate(return_dict, coords, coords)
55
+ print(return_dict["squared_norm"])
sources/neuraloperator/neuralop/layers/tests/test_padding.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ..padding import DomainPadding
3
+ import pytest
4
+
5
+
6
+ def test_DomainPadding():
7
+ data = torch.randn((2, 3, 10, 10))
8
+ padder = DomainPadding(0.2)
9
+ padded = padder.pad(data)
10
+
11
+ # With 0.2 padding and symmetric mode, output size should be 14
12
+ target_shape = list(padded.shape)
13
+ target_shape[-1] = target_shape[-2] = 14
14
+ assert list(padded.shape) == target_shape
15
+
16
+ unpadded = padder.unpad(padded)
17
+ assert unpadded.shape == data.shape
sources/neuraloperator/neuralop/layers/tests/test_resample.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..resample import resample
2
+ import torch
3
+
4
+
5
+ def test_resample():
6
+ a = torch.randn(10, 20, 40, 50)
7
+
8
+ res_scale = [2, 3]
9
+ axis = [-2, -1]
10
+
11
+ b = resample(a, res_scale, axis)
12
+ assert b.shape[-1] == 3 * a.shape[-1] and b.shape[-2] == 2 * a.shape[-2]
13
+
14
+ a = torch.randn((10, 20, 40, 50, 60))
15
+
16
+ res_scale = [0.5, 3, 4]
17
+ axis = [-3, -2, -1]
18
+ b = resample(a, res_scale, axis)
19
+
20
+ assert (
21
+ b.shape[-1] == 4 * a.shape[-1]
22
+ and b.shape[-2] == 3 * a.shape[-2]
23
+ and b.shape[-3] == int(0.5 * a.shape[-3])
24
+ )
sources/neuraloperator/neuralop/layers/tests/test_rno_block.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ..rno_block import RNOBlock
4
+
5
+
6
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
7
+ @pytest.mark.parametrize("complex_data", [False, True])
8
+ def test_RNOBlock_basic(n_dim, complex_data):
9
+ """Test RNOBlock with basic functionality"""
10
+ modes = (8, 8, 8)
11
+ width = 16
12
+ size = [12] * n_dim
13
+ batch_size = 2
14
+ num_timesteps = 3
15
+
16
+ layer = RNOBlock(
17
+ n_modes=modes[:n_dim],
18
+ hidden_channels=width,
19
+ complex_data=complex_data,
20
+ )
21
+
22
+ dtype = torch.cfloat if complex_data else torch.float32
23
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
24
+
25
+ # Test forward pass
26
+ out = layer(x)
27
+ assert out.shape == (batch_size, width, *size)
28
+ assert out.dtype == dtype
29
+
30
+ # Test with custom hidden state
31
+ h_init = torch.randn(batch_size, width, *size, dtype=dtype)
32
+ out_custom = layer(x, h_init)
33
+ assert out_custom.shape == (batch_size, width, *size)
34
+ assert out_custom.dtype == dtype
35
+
36
+
37
+ @pytest.mark.parametrize("return_sequences", [False, True])
38
+ @pytest.mark.parametrize("complex_data", [False, True])
39
+ def test_RNOBlock_return_sequences(return_sequences, complex_data):
40
+ """Test RNOBlock with return_sequences option"""
41
+ modes = (8, 8)
42
+ width = 16
43
+ size = [12, 12]
44
+ batch_size = 2
45
+ num_timesteps = 3
46
+
47
+ layer = RNOBlock(
48
+ n_modes=modes,
49
+ hidden_channels=width,
50
+ return_sequences=return_sequences,
51
+ complex_data=complex_data,
52
+ )
53
+
54
+ dtype = torch.cfloat if complex_data else torch.float32
55
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
56
+
57
+ out = layer(x)
58
+
59
+ if return_sequences:
60
+ assert out.shape == (batch_size, num_timesteps, width, *size)
61
+ else:
62
+ assert out.shape == (batch_size, width, *size)
63
+
64
+ assert out.dtype == dtype
65
+
66
+
67
+ @pytest.mark.parametrize("n_dim", [1, 2, 3])
68
+ @pytest.mark.parametrize("complex_data", [False]) # Skip complex for resolution scaling (interpolation not supported)
69
+ def test_RNOBlock_resolution_scaling(n_dim, complex_data):
70
+ """Test RNOBlock with resolution scaling"""
71
+ modes = (8, 8, 8)
72
+ width = 16
73
+ size = [12] * n_dim
74
+ batch_size = 2
75
+ num_timesteps = 3
76
+
77
+ # Test upsampling
78
+ layer_up = RNOBlock(
79
+ n_modes=modes[:n_dim],
80
+ hidden_channels=width,
81
+ resolution_scaling_factor=2.0,
82
+ complex_data=complex_data,
83
+ )
84
+
85
+ dtype = torch.cfloat if complex_data else torch.float32
86
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
87
+
88
+ out_up = layer_up(x)
89
+ expected_size_up = tuple(s * 2 for s in size)
90
+ assert out_up.shape == (batch_size, width, *expected_size_up)
91
+ assert out_up.dtype == dtype
92
+
93
+ # Test downsampling
94
+ layer_down = RNOBlock(
95
+ n_modes=modes[:n_dim],
96
+ hidden_channels=width,
97
+ resolution_scaling_factor=0.5,
98
+ complex_data=complex_data,
99
+ )
100
+
101
+ out_down = layer_down(x)
102
+ expected_size_down = tuple(s // 2 for s in size)
103
+ assert out_down.shape == (batch_size, width, *expected_size_down)
104
+ assert out_down.dtype == dtype
105
+
106
+
107
+ @pytest.mark.parametrize("norm", [None, "group_norm", "instance_norm"])
108
+ @pytest.mark.parametrize("complex_data", [False, True])
109
+ def test_RNOBlock_norm(norm, complex_data):
110
+ """Test RNOBlock with different normalization options"""
111
+ modes = (8, 8)
112
+ width = 16
113
+ size = [12, 12]
114
+ batch_size = 2
115
+ num_timesteps = 3
116
+
117
+ layer = RNOBlock(
118
+ n_modes=modes,
119
+ hidden_channels=width,
120
+ norm=norm,
121
+ complex_data=complex_data,
122
+ )
123
+
124
+ dtype = torch.cfloat if complex_data else torch.float32
125
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
126
+
127
+ out = layer(x)
128
+ assert out.shape == (batch_size, width, *size)
129
+ assert out.dtype == dtype
130
+
131
+
132
+ @pytest.mark.parametrize("stabilizer", [None, "tanh"])
133
+ @pytest.mark.parametrize("complex_data", [False, True])
134
+ def test_RNOBlock_stabilizer(stabilizer, complex_data):
135
+ """Test RNOBlock with stabilizer options"""
136
+ modes = (8, 8)
137
+ width = 16
138
+ size = [12, 12]
139
+ batch_size = 2
140
+ num_timesteps = 3
141
+
142
+ layer = RNOBlock(
143
+ n_modes=modes,
144
+ hidden_channels=width,
145
+ stabilizer=stabilizer,
146
+ complex_data=complex_data,
147
+ )
148
+
149
+ dtype = torch.cfloat if complex_data else torch.float32
150
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
151
+
152
+ out = layer(x)
153
+ assert out.shape == (batch_size, width, *size)
154
+ assert out.dtype == dtype
155
+
156
+
157
+ @pytest.mark.parametrize("separable", [False, True])
158
+ @pytest.mark.parametrize("complex_data", [False, True])
159
+ def test_RNOBlock_separable(separable, complex_data):
160
+ """Test RNOBlock with separable convolutions"""
161
+ modes = (8, 8)
162
+ width = 16
163
+ size = [12, 12]
164
+ batch_size = 2
165
+ num_timesteps = 3
166
+
167
+ layer = RNOBlock(
168
+ n_modes=modes,
169
+ hidden_channels=width,
170
+ separable=separable,
171
+ complex_data=complex_data,
172
+ )
173
+
174
+ dtype = torch.cfloat if complex_data else torch.float32
175
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
176
+
177
+ out = layer(x)
178
+ assert out.shape == (batch_size, width, *size)
179
+ assert out.dtype == dtype
180
+
181
+
182
+ @pytest.mark.parametrize("preactivation", [False, True])
183
+ @pytest.mark.parametrize("complex_data", [False, True])
184
+ def test_RNOBlock_preactivation(preactivation, complex_data):
185
+ """Test RNOBlock with preactivation"""
186
+ modes = (8, 8)
187
+ width = 16
188
+ size = [12, 12]
189
+ batch_size = 2
190
+ num_timesteps = 3
191
+
192
+ layer = RNOBlock(
193
+ n_modes=modes,
194
+ hidden_channels=width,
195
+ preactivation=preactivation,
196
+ complex_data=complex_data,
197
+ )
198
+
199
+ dtype = torch.cfloat if complex_data else torch.float32
200
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
201
+
202
+ out = layer(x)
203
+ assert out.shape == (batch_size, width, *size)
204
+ assert out.dtype == dtype
205
+
206
+
207
+ @pytest.mark.parametrize("factorization", [None, "Tucker"])
208
+ @pytest.mark.parametrize("complex_data", [False, True])
209
+ def test_RNOBlock_factorization(factorization, complex_data):
210
+ """Test RNOBlock with factorization"""
211
+ modes = (8, 8)
212
+ width = 16
213
+ size = [12, 12]
214
+ batch_size = 2
215
+ num_timesteps = 3
216
+
217
+ layer = RNOBlock(
218
+ n_modes=modes,
219
+ hidden_channels=width,
220
+ factorization=factorization,
221
+ rank=0.5 if factorization else 1.0,
222
+ complex_data=complex_data,
223
+ )
224
+
225
+ dtype = torch.cfloat if complex_data else torch.float32
226
+ x = torch.randn(batch_size, num_timesteps, width, *size, dtype=dtype)
227
+
228
+ out = layer(x)
229
+ assert out.shape == (batch_size, width, *size)
230
+ assert out.dtype == dtype
231
+
232
+
233
+ @pytest.mark.parametrize("norm_groups", [1, 2, 4, 8])
234
+ def test_RNOBlock_group_norm(norm_groups):
235
+ """Test RNOBlock with group_norm and custom norm_groups"""
236
+ modes = (8, 8)
237
+ hidden_channels = 16
238
+
239
+ layer = RNOBlock(
240
+ n_modes=modes,
241
+ hidden_channels=hidden_channels,
242
+ norm="group_norm",
243
+ norm_groups=norm_groups,
244
+ )
245
+
246
+ # RNOBlock contains an RNOCell which contains 6 FNOBlocks (3 input + 3 hidden gates)
247
+ for fno_block in [*layer.cell.input_gates, *layer.cell.hidden_gates]:
248
+ assert fno_block.norm is not None
249
+ for norm_layer in fno_block.norm:
250
+ assert isinstance(norm_layer, torch.nn.GroupNorm)
251
+ assert norm_layer.num_groups == norm_groups
252
+ assert norm_layer.num_channels == hidden_channels
sources/neuraloperator/neuralop/layers/tests/test_segment_csr.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ..segment_csr import segment_csr
3
+
4
+ import pytest
5
+
6
+
7
+ @pytest.mark.parametrize("batch_size", [1, 4])
8
+ def test_native_segcsr_shapes(batch_size):
9
+ n_pts = 25
10
+ n_channels = 5
11
+ max_nbrhd_size = 7 # prevent degenerate cases in testing
12
+
13
+ # tensor to reduce
14
+ src = torch.randn((batch_size, n_pts, n_channels))
15
+
16
+ # randomly generate index pointer tensor for CSR format
17
+ nbrhd_sizes = [torch.tensor([0])]
18
+ while sum(nbrhd_sizes) < n_pts:
19
+ nbrhd_sizes.append(torch.randint(0, max_nbrhd_size + 1, size=(1,)))
20
+ max_nbrhd_size = min(max_nbrhd_size, n_pts - sum(nbrhd_sizes))
21
+ indptr = torch.cumsum(torch.tensor(nbrhd_sizes, dtype=torch.long), dim=0)
22
+ if batch_size > 1:
23
+ indptr = indptr.repeat([batch_size] + [1] * indptr.ndim)
24
+ else:
25
+ src = src.squeeze(0)
26
+ out = segment_csr(src, indptr, reduction="sum", use_scatter=False)
27
+
28
+ if batch_size == 1:
29
+ assert out.shape == (len(indptr) - 1, n_channels)
30
+ else:
31
+ assert out.shape == (batch_size, indptr.shape[1] - 1, n_channels)
32
+
33
+
34
+ def test_native_segcsr_reductions():
35
+ src = torch.ones([10, 3])
36
+ indptr = torch.tensor([0, 3, 8, 10], dtype=torch.long)
37
+
38
+ out_sum = segment_csr(src, indptr, reduction="sum", use_scatter=False)
39
+ assert out_sum.shape == (3, 3)
40
+ diff = out_sum - torch.tensor([[3, 5, 2]]).T * torch.ones([3, 3])
41
+ assert not diff.nonzero().any()
42
+
43
+ out_mean = segment_csr(src, indptr, reduction="mean", use_scatter=False)
44
+ assert out_mean.shape == (3, 3)
45
+ diff = out_mean - torch.ones([3, 3])
46
+ assert not diff.nonzero().any()
sources/neuraloperator/neuralop/layers/tests/test_sin_embeddings.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch.testing import assert_close
5
+ import pytest
6
+
7
+ from ..embeddings import SinusoidalEmbedding
8
+
9
+ # Testing NeRF Embedding: start with a simple range
10
+ # and see that it is embedded properly
11
+
12
+ batch_size = 4
13
+ num_freqs = 3
14
+ in_channels = 3
15
+ n_in = 2
16
+ max_pos = 10000
17
+
18
+ if torch.backends.cuda.is_built():
19
+ device = "cuda"
20
+ else:
21
+ device = "cpu"
22
+
23
+
24
+ def test_NeRFEmbedding():
25
+ nerf_embed = SinusoidalEmbedding(
26
+ in_channels=in_channels, num_frequencies=3, embedding_type="nerf"
27
+ )
28
+ unbatched_inputs = torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])
29
+ embeds = nerf_embed(unbatched_inputs.to(device))
30
+
31
+ true_outputs = torch.zeros(n_in, in_channels * num_freqs * 2).to(device)
32
+
33
+ # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p))
34
+ for channel in range(in_channels):
35
+ for wavenumber in range(num_freqs):
36
+ for i in range(2):
37
+ idx = channel * (num_freqs * 2) + wavenumber * 2 + i
38
+ freqs = 2**wavenumber * math.pi * unbatched_inputs[:, channel]
39
+ if i == 0:
40
+ true_outputs[:, idx] = freqs.sin()
41
+ else:
42
+ true_outputs[:, idx] = freqs.cos()
43
+ assert_close(embeds, true_outputs)
44
+
45
+ batched_inputs = torch.stack(
46
+ [torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])] * batch_size
47
+ )
48
+ embeds = nerf_embed(batched_inputs.to(device))
49
+
50
+ true_outputs = torch.zeros(batch_size, n_in, in_channels * num_freqs * 2).to(device)
51
+
52
+ # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p))
53
+ for channel in range(in_channels):
54
+ for wavenumber in range(num_freqs):
55
+ for i in range(2):
56
+ idx = channel * (num_freqs * 2) + wavenumber * 2 + i
57
+ freqs = 2**wavenumber * math.pi * batched_inputs[:, :, channel]
58
+ if i == 0:
59
+ true_outputs[:, :, idx] = freqs.sin()
60
+ else:
61
+ true_outputs[:, :, idx] = freqs.cos()
62
+ assert_close(embeds, true_outputs)
63
+
64
+
65
+ def test_TransformerEmbedding():
66
+ sin_embed = SinusoidalEmbedding(
67
+ in_channels=in_channels,
68
+ num_frequencies=3,
69
+ embedding_type="transformer",
70
+ max_positions=max_pos,
71
+ )
72
+ unbatched_inputs = torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])
73
+ embeds = sin_embed(unbatched_inputs.to(device))
74
+
75
+ true_outputs = torch.zeros(n_in, in_channels * num_freqs * 2).to(device)
76
+
77
+ # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p))
78
+ for channel in range(in_channels):
79
+ for wavenumber in range(num_freqs):
80
+ for i in range(2):
81
+ idx = channel * (num_freqs * 2) + wavenumber * 2 + i
82
+ freqs = (
83
+ (1 / max_pos) ** (wavenumber / sin_embed.num_frequencies * 2)
84
+ ) * unbatched_inputs[:, channel]
85
+ if i == 0:
86
+ true_outputs[:, idx] = freqs.sin()
87
+ else:
88
+ true_outputs[:, idx] = freqs.cos()
89
+ assert_close(embeds, true_outputs)
90
+
91
+ batched_inputs = torch.stack(
92
+ [torch.arange(in_channels) * torch.tensor([[1.0], [0.5]])] * batch_size
93
+ )
94
+ embeds = sin_embed(batched_inputs.to(device))
95
+
96
+ true_outputs = torch.zeros(batch_size, n_in, in_channels * num_freqs * 2).to(device)
97
+
98
+ # True values are (sin(2^0 * pi * p), cos(2^0 * pi * p), ... cos(2^(L-1) * pi * p))
99
+ for channel in range(in_channels):
100
+ for wavenumber in range(num_freqs):
101
+ for i in range(2):
102
+ idx = channel * (num_freqs * 2) + wavenumber * 2 + i
103
+ freqs = (
104
+ (1 / max_pos) ** (wavenumber / sin_embed.num_frequencies * 2)
105
+ ) * batched_inputs[:, :, channel]
106
+ if i == 0:
107
+ true_outputs[:, :, idx] = freqs.sin()
108
+ else:
109
+ true_outputs[:, :, idx] = freqs.cos()
110
+ assert_close(embeds, true_outputs)
sources/neuraloperator/neuralop/layers/tests/test_spectral_convolution.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from tltorch import FactorizedTensor
4
+ from ..spectral_convolution import SpectralConv
5
+
6
+
7
+ @pytest.mark.parametrize("factorization", ["Dense", "CP", "Tucker", "TT"])
8
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
9
+ @pytest.mark.parametrize("separable", [False, True])
10
+ @pytest.mark.parametrize("dim", [1, 2, 3, 4])
11
+ @pytest.mark.parametrize("complex_data", [False, True])
12
+ def test_SpectralConv(factorization, implementation, separable, dim, complex_data):
13
+ """Test for SpectralConv of any order
14
+
15
+ Compares Factorized and Dense convolution output
16
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
17
+
18
+ Checks the output size
19
+
20
+ Verifies that dynamically changing the number of Fourier modes doesn't break the conv
21
+ """
22
+ modes = (10, 8, 6, 6)
23
+ incremental_modes = (6, 6, 4, 4)
24
+ dtype = torch.cfloat if complex_data else torch.float32
25
+
26
+ # Test for Conv1D to Conv4D
27
+ conv = SpectralConv(
28
+ 3,
29
+ 3,
30
+ modes[:dim],
31
+ bias=False,
32
+ implementation=implementation,
33
+ factorization=factorization,
34
+ complex_data=complex_data,
35
+ separable=separable,
36
+ )
37
+
38
+ conv_dense = SpectralConv(
39
+ 3,
40
+ 3,
41
+ modes[:dim],
42
+ bias=False,
43
+ implementation="reconstructed",
44
+ factorization=None,
45
+ complex_data=complex_data,
46
+ )
47
+
48
+ x = torch.randn(2, 3, *(12,) * dim, dtype=dtype)
49
+
50
+ assert torch.is_complex(conv.weight)
51
+ assert torch.is_complex(conv_dense.weight)
52
+
53
+ # this closeness test only works if the weights in full form have the same shape
54
+ if not separable:
55
+ conv_dense.weight = FactorizedTensor.from_tensor(
56
+ conv.weight.to_tensor(), rank=None, factorization="ComplexDense"
57
+ )
58
+
59
+ res_dense = conv_dense(x)
60
+ res = conv(x)
61
+ res_shape = res.shape
62
+
63
+ # this closeness test only works if the weights in full form have the same shape
64
+ if not separable:
65
+ torch.testing.assert_close(res_dense, res)
66
+
67
+ # Dynamically reduce the number of modes in Fourier space
68
+ conv.n_modes = incremental_modes[:dim]
69
+ res = conv(x)
70
+ assert res_shape == res.shape
71
+
72
+ # Downsample outputs
73
+ block = SpectralConv(3, 4, modes[:dim], resolution_scaling_factor=0.5)
74
+
75
+ x = torch.randn(2, 3, *(12,) * dim)
76
+ res = block(x)
77
+ assert list(res.shape[2:]) == [12 // 2] * dim
78
+
79
+ # Upsample outputs
80
+ block = SpectralConv(3, 4, modes[:dim], resolution_scaling_factor=2)
81
+
82
+ x = torch.randn(2, 3, *(12,) * dim)
83
+ res = block(x)
84
+ assert res.shape[1] == 4 # Check out channels
85
+ assert list(res.shape[2:]) == [12 * 2] * dim
86
+
87
+
88
+ @pytest.mark.parametrize("enforce_hermitian_symmetry", [True, False])
89
+ @pytest.mark.parametrize("dim", [1, 2, 3])
90
+ @pytest.mark.parametrize("spatial_size", [8, 9]) # Even and odd: Nyquist handling differs
91
+ @pytest.mark.parametrize("resolution_scaling_factor", [None, 0.5, 2])
92
+ @pytest.mark.parametrize("modes", [(4, 4, 4), (4, 5, 7)])
93
+ def test_SpectralConv2(enforce_hermitian_symmetry, dim, spatial_size, modes, resolution_scaling_factor):
94
+ modes = modes[:dim]
95
+ size = [spatial_size] * dim
96
+ if resolution_scaling_factor is None:
97
+ out_size = size
98
+ else:
99
+ out_size = [round(s * resolution_scaling_factor) for s in size]
100
+
101
+ # Test with real-valued data
102
+ conv = SpectralConv(
103
+ 3,
104
+ 4,
105
+ modes,
106
+ enforce_hermitian_symmetry=enforce_hermitian_symmetry,
107
+ complex_data=False,
108
+ resolution_scaling_factor=resolution_scaling_factor,
109
+ )
110
+ x = torch.randn(2, 3, *size, dtype=torch.float32)
111
+ res = conv(x)
112
+
113
+ assert res.shape == (2, 4, *out_size)
114
+ assert res.dtype == torch.float32
115
+ assert not torch.is_complex(res)
sources/neuraloperator/neuralop/layers/tests/test_spectral_projection.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytest
3
+ import numpy as np
4
+ from ..spectral_projection import spectral_projection_divergence_free
5
+
6
+ @pytest.mark.parametrize("resolution", [(64, 64), (80, 60), (60, 80)])
7
+ @pytest.mark.parametrize("constraint_modes", [(64, 64), (50, 64), (72, 60)])
8
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64])
9
+ def test_spectral_projection(resolution, constraint_modes, dtype):
10
+ """Test spectral projection functionality with different resolutions, constraint modes and dtypes."""
11
+
12
+ height, width = resolution
13
+ batch_size = 3
14
+ domain_size = 2 * np.pi
15
+
16
+ # Create a simple velocity field with some divergence
17
+ x = torch.linspace(0, domain_size, width)
18
+ y = torch.linspace(0, domain_size, height)
19
+ X, Y = torch.meshgrid(x, y, indexing='ij')
20
+
21
+ # Example u_x = sin(y), u_y = cos(x)
22
+ u_x = torch.sin(Y.T).unsqueeze(0).unsqueeze(0).expand(batch_size, 1, height, width)
23
+ u_y = torch.cos(X.T).unsqueeze(0).unsqueeze(0).expand(batch_size, 1, height, width)
24
+ u = torch.cat([u_x, u_y], dim=1).to(dtype)
25
+
26
+ # Apply spectral projection
27
+ u_projected = spectral_projection_divergence_free(u, domain_size, constraint_modes)
28
+
29
+ # Check output shape and properties
30
+ assert u_projected.shape == u.shape
31
+ assert u_projected.dtype == dtype
32
+ assert u_projected.device == u.device
33
+
34
+ # Check no NaN or inf values
35
+ assert not torch.isnan(u_projected).any()
36
+ assert not torch.isinf(u_projected).any()
sources/neuraloperator/neuralop/layers/tests/test_spherical_convolution.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from tltorch import FactorizedTensor
4
+
5
+ try:
6
+ import torch_harmonics
7
+ except ModuleNotFoundError:
8
+ pytest.skip(
9
+ "Skipping because torch_harmonics is not installed", allow_module_level=True
10
+ )
11
+
12
+ from ..spherical_convolution import SphericalConv
13
+ from ..spherical_convolution import SHT
14
+
15
+
16
+ @pytest.mark.parametrize(
17
+ "factorization", ["ComplexDense", "ComplexCP", "ComplexTucker", "ComplexTT"]
18
+ )
19
+ @pytest.mark.parametrize("implementation", ["factorized", "reconstructed"])
20
+ def test_SphericalConv(factorization, implementation):
21
+ """Test for SphericalConv (2D only)
22
+
23
+ Compares Factorized and Dense convolution output
24
+ Verifies that a dense conv and factorized conv with the same weight produce the same output
25
+
26
+ Checks the output size
27
+
28
+ Verifies that dynamically changing the number of Fourier modes doesn't break the conv
29
+ """
30
+ n_modes = (6, 6)
31
+
32
+ conv = SphericalConv(
33
+ 3,
34
+ 3,
35
+ n_modes,
36
+ bias=False,
37
+ implementation=implementation,
38
+ factorization=factorization,
39
+ )
40
+
41
+ conv_dense = SphericalConv(
42
+ 3, 3, n_modes, bias=False, implementation="reconstructed", factorization=None
43
+ )
44
+
45
+ conv_dense.weight = FactorizedTensor.from_tensor(
46
+ conv.weight.to_tensor(), rank=None, factorization="ComplexDense"
47
+ )
48
+ x = torch.randn(2, 3, *(12, 12))
49
+
50
+ res_dense = conv_dense(x)
51
+ res = conv(x)
52
+
53
+ torch.testing.assert_close(res_dense, res)
54
+
55
+ # Downsample outputs
56
+ block = SphericalConv(3, 4, n_modes, resolution_scaling_factor=0.5)
57
+
58
+ x = torch.randn(2, 3, *(12, 12))
59
+ res = block(x)
60
+ assert list(res.shape[2:]) == [12 // 2, 12 // 2]
61
+
62
+ # Upsample outputs
63
+ block = SphericalConv(3, 4, n_modes, resolution_scaling_factor=2)
64
+
65
+ x = torch.randn(2, 3, *(12, 12))
66
+ res = block(x)
67
+ assert res.shape[1] == 4 # Check out channels
68
+ assert list(res.shape[2:]) == [12 * 2, 12 * 2]
69
+
70
+ # Test change of grid
71
+ block_0 = SphericalConv(4, 4, n_modes, sht_grids=["equiangular", "legendre-gauss"])
72
+
73
+ block_1 = SphericalConv(4, 4, n_modes, sht_grids=["legendre-gauss", "equiangular"])
74
+
75
+ x = torch.randn(2, 4, *(12, 12))
76
+ res = block_0(x)
77
+ res = block_1(res)
78
+ assert res.shape[2:] == x.shape[2:]
79
+
80
+ res = block_0.transform(x)
81
+ res = block_1.transform(res)
82
+ assert res.shape[2:] == x.shape[2:]
83
+
84
+
85
+ @pytest.mark.parametrize("grid", ["equiangular", "legendre-gauss"])
86
+ def test_sht(grid):
87
+ nlat = 16
88
+ nlon = 2 * nlat
89
+ batch_size = 2
90
+ if grid == "equiangular":
91
+ mmax = nlat // 2
92
+ else:
93
+ mmax = nlat
94
+ lmax = mmax
95
+ norm = "ortho"
96
+ dtype = torch.float32
97
+
98
+ sht_handle = SHT(dtype=dtype)
99
+
100
+ # Create input
101
+ coeffs = torch.zeros(batch_size, lmax, mmax, dtype=torch.complex64)
102
+ coeffs[:, :lmax, :mmax] = torch.randn(batch_size, lmax, mmax, dtype=torch.complex64)
103
+
104
+ signal = sht_handle.isht(coeffs, s=(nlat, nlon), grid=grid, norm=norm).to(torch.float32)
105
+
106
+ coeffs = sht_handle.sht(signal, s=(lmax, mmax), grid=grid, norm=norm)
107
+ rec = sht_handle.isht(coeffs, s=(nlat, nlon), grid=grid, norm=norm)
108
+ torch.testing.assert_close(signal, rec, rtol=1e-4, atol=1e-4)
sources/neuraloperator/neuralop/losses/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .data_losses import LpLoss, H1Loss
2
+ from .equation_losses import BurgersEqnLoss, ICLoss
3
+ from .differentiation import FourierDiff, non_uniform_fd, FiniteDiff
4
+ from .meta_losses import (
5
+ WeightedSumLoss,
6
+ FieldwiseAggregatorLoss,
7
+ Aggregator,
8
+ Relobralo,
9
+ SoftAdapt,
10
+ )
sources/neuraloperator/neuralop/losses/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (578 Bytes). View file
 
sources/neuraloperator/neuralop/losses/__pycache__/data_losses.cpython-313.pyc ADDED
Binary file (31.9 kB). View file
 
sources/neuraloperator/neuralop/losses/__pycache__/differentiation.cpython-313.pyc ADDED
Binary file (63.8 kB). View file
 
sources/neuraloperator/neuralop/losses/__pycache__/equation_losses.cpython-313.pyc ADDED
Binary file (13.4 kB). View file
 
sources/neuraloperator/neuralop/losses/__pycache__/meta_losses.cpython-313.pyc ADDED
Binary file (21.9 kB). View file