Skip to content
VLASIFY™
TutorialScientific AI & machine learning

Fourier neural operator example in PyTorch (1D, from scratch)

Updated · Scientifically reviewed by Dinkar Mishra, PhD on

Short answer

A Fourier neural operator lifts the input function to several channels, applies layers that take an FFT, multiply the lowest Fourier modes by learned complex weights, transform back and add a pointwise linear map, and finally projects to the output function. The ~70-line PyTorch script below trains a 1D FNO to map a random forcing f to the solution u of −u″ + u = f on a periodic domain, and verifies it on 200 unseen test cases.

Who this is for

ML practitioners and computational scientists who want to understand FNOs by building one, before using libraries on larger problems.

Software

Python ≥ 3.9PyTorch ≥ 2.0 (complex parameters supported by Adam)

Prerequisites

  • Python 3.9+ and PyTorch 2.x. A CPU finishes this example in a few minutes.
  • The concepts from our neural operator tutorial.

Step 1: the learning problem

On the periodic domain [0,2π)[0, 2\pi), the operator maps a forcing ff to the solution uu of

−u′′+u=f⟺u^k=f^k1+k2.-u'' + u = f \quad\Longleftrightarrow\quad \hat u_k = \frac{\hat f_k}{1 + k^2}.

The exact Fourier-space solution lets us generate unlimited exact training data and test the FNO precisely.

Step 2: the code

import math
import torch
import torch.nn as nn

torch.manual_seed(0)
n, n_train, n_test = 128, 800, 200
x = torch.linspace(0, 2 * math.pi, n + 1)[:-1]
k = torch.fft.rfftfreq(n, d=1.0 / n)              # integer wavenumbers 0..n/2


def make_data(m):
    """Random smooth forcings f and exact periodic solutions of -u'' + u = f."""
    f_hat = torch.zeros(m, n // 2 + 1, dtype=torch.cfloat)
    f_hat[:, 1:9] = torch.randn(m, 8, dtype=torch.cfloat) / (1 + torch.arange(8)) ** 2
    f = torch.fft.irfft(f_hat, n=n) * n
    u = torch.fft.irfft(f_hat / (1 + k**2), n=n) * n
    return f.unsqueeze(1), u.unsqueeze(1)


class SpectralConv1d(nn.Module):
    def __init__(self, channels, modes):
        super().__init__()
        self.modes = modes
        self.w = nn.Parameter(torch.randn(channels, channels, modes, dtype=torch.cfloat) / channels)

    def forward(self, v):
        v_hat = torch.fft.rfft(v)
        out = torch.zeros_like(v_hat)
        out[:, :, : self.modes] = torch.einsum("bim,iom->bom", v_hat[:, :, : self.modes], self.w)
        return torch.fft.irfft(out, n=v.shape[-1])


class FNO1d(nn.Module):
    def __init__(self, width=32, modes=16, layers=4):
        super().__init__()
        self.lift = nn.Conv1d(2, width, 1)          # input channels: f(x) and x
        self.spectral = nn.ModuleList(SpectralConv1d(width, modes) for _ in range(layers))
        self.local = nn.ModuleList(nn.Conv1d(width, width, 1) for _ in range(layers))
        self.project = nn.Sequential(nn.Conv1d(width, 64, 1), nn.GELU(), nn.Conv1d(64, 1, 1))

    def forward(self, f):
        grid = x.expand(f.shape[0], 1, -1)
        v = self.lift(torch.cat([f, grid], dim=1))
        for spec, loc in zip(self.spectral, self.local):
            v = nn.functional.gelu(spec(v) + loc(v))
        return self.project(v)


f_tr, u_tr = make_data(n_train)
f_te, u_te = make_data(n_test)
model = FNO1d()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(200):
    perm = torch.randperm(n_train)
    for i in range(0, n_train, 32):
        idx = perm[i : i + 32]
        opt.zero_grad()
        loss = ((model(f_tr[idx]) - u_tr[idx]) ** 2).mean()
        loss.backward()
        opt.step()

with torch.no_grad():
    rel = ((model(f_te) - u_te).norm(dim=-1) / u_te.norm(dim=-1)).squeeze()
print(f"mean relative L2 test error = {rel.mean().item():.3e}, worst = {rel.max().item():.3e}")

Step 3: how the spectral layer works

SpectralConv1d performs a global convolution efficiently. The FFT turns convolution into multiplication, so the layer multiplies the first modes Fourier coefficients of each channel by a learned complex matrix (mixing channels) and discards higher modes. The parallel 1×1 convolution (local) restores pointwise detail, and GELU adds nonlinearity, which matters for non-linear PDEs even though this example is linear.

Scaling up to real problems

Real applications differ from this example in three ways. Dimensions: 2D and 3D FNOs use rfft2/rfftn and keep modes in each direction, so memory grows quickly. Data: training pairs come from your verified solver, with inputs drawn from the range you will query. Normalisation: inputs and outputs are scaled to order one, and the relative L2L^2 loss is often preferred over the mean-squared error. Libraries such as neuraloperator implement these details.

Verify

Run python fno1d.py. The script reports the mean and worst relative L2L^2 error on 200 test cases the model never saw. For this smooth linear problem, both should be small. Then:

  1. Halve n_train to see how accuracy depends on data.
  2. Reduce modes to 4. Accuracy should drop, because the forcing contains wavenumbers up to 8.
  3. Change the data distribution (for example wavenumbers up to 12) only in the test set. The error grows, a direct demonstration of out-of-distribution risk.

Troubleshooting

  • Error does not decrease: check that the data are not all near zero (normalise if you change the scaling), and lower the learning rate.
  • Complex-parameter errors from the optimiser: use a recent PyTorch 2.x. Older versions had limited complex support. Alternatively store real and imaginary parts as two real parameters.
  • Slow training: move the model and tensors to a GPU (.cuda()), or reduce width.

Assumptions and limitations

  • A linear, periodic, 1D problem chosen so that exact solutions exist. Non-linear and higher-dimensional PDEs need more data, model capacity and care.
  • Error values depend on random seeds and library versions. The script prints them rather than us quoting fixed numbers.
  • For production, use a maintained library and validate against your own solver; see machine learning surrogate models.

Frequently asked questions

Why truncate to the lowest Fourier modes?+

Solutions of many PDEs are dominated by low wavenumbers, and keeping a fixed number of modes makes the learned weights independent of the grid resolution. The trade-off is that features finer than the retained modes must be represented by the pointwise layers and nonlinearities.

Why concatenate the coordinate x to the input?+

Giving the network its position helps it represent non-translation-invariant problems. For a strictly periodic, translation-invariant problem like this one it is not essential, but it is standard practice in FNO implementations.

Can I evaluate the trained FNO on a finer grid?+

Yes in principle: the spectral weights act on Fourier modes, not grid points. Evaluate with the input sampled on the new grid (and the new coordinate array) and check the error, because accuracy at different resolutions is not guaranteed.

Should I use a library instead?+

For real projects, yes. The neuraloperator library provides tested FNO variants, 2D and 3D layers, and training utilities. Writing a minimal version once is the best way to understand what the library does.

References

  1. Li et al., Fourier neural operator for parametric partial differential equations (ICLR 2021) · Conference paper (arXiv)
  2. Kovachki et al., Neural operator: learning maps between function spaces, J. Mach. Learn. Res. 24(89), 1 (2023) · Peer-reviewed article
  3. torch.fft documentation · PyTorch
  4. neuraloperator library · neuraloperator project

Want this set up and verified for you?

We install, configure and validate scientific software on your workstation, cluster or cloud, and train your team to run it.

Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.

Spotted an error or an outdated command? Tell us. We correct verified issues promptly.

Related guides

How Vlasify can help

Get a Quote