Skip to content
VLASIFY™
TutorialScientific AI & machine learning

DeepONet tutorial: learning the antiderivative operator in PyTorch

Updated · Scientifically reviewed by Dinkar Mishra, PhD on

Short answer

DeepONet approximates an operator G that maps an input function u to an output function G(u)(y). A branch network takes u sampled at fixed sensor points and returns p coefficients; a trunk network takes the query location y and returns p basis functions; their dot product is the prediction. This tutorial trains a DeepONet on the antiderivative operator, whose exact answer is known, and verifies it on unseen functions.

Who this is for

Researchers exploring operator learning who want a clear, verifiable DeepONet implementation to build on.

Software

Python ≥ 3.9PyTorch ≥ 2.0

Prerequisites

Step 1: the operator

The antiderivative operator maps uu to G(u)(y)=∫0yu(x) dxG(u)(y) = \int_0^y u(x)\,dx on [0,1][0, 1]. Using input functions u(x)=∑j=15ajsin⁡(jπx)u(x) = \sum_{j=1}^{5} a_j \sin(j\pi x) with random aja_j, the exact output is

G(u)(y)=∑j=15aj 1−cos⁡(jπy)jπ,G(u)(y) = \sum_{j=1}^{5} a_j\,\frac{1 - \cos(j\pi y)}{j\pi},

so every prediction can be checked exactly.

Step 2: the code

import math
import torch
import torch.nn as nn

torch.manual_seed(0)
m, p = 50, 64                                   # sensors, latent dimension
sensors = torch.linspace(0, 1, m)
j = torch.arange(1, 6, dtype=torch.float32)


def sample(n_funcs, n_points):
    a = torch.randn(n_funcs, 5)
    u_sensors = a @ torch.sin(math.pi * j[:, None] * sensors[None, :])          # (n_funcs, m)
    y = torch.rand(n_funcs, n_points, 1)
    G = (a[:, None, :] * (1 - torch.cos(math.pi * j * y)) / (math.pi * j)).sum(-1)  # (n_funcs, n_points)
    return u_sensors, y, G


def mlp(sizes):
    layers = []
    for a, b in zip(sizes[:-1], sizes[1:]):
        layers += [nn.Linear(a, b), nn.Tanh()]
    return nn.Sequential(*layers[:-1])          # no activation after the last layer


class DeepONet(nn.Module):
    def __init__(self):
        super().__init__()
        self.branch = mlp([m, 128, 128, p])
        self.trunk = mlp([1, 128, 128, p])
        self.bias = nn.Parameter(torch.zeros(1))

    def forward(self, u_sensors, y):
        b = self.branch(u_sensors)              # (n_funcs, p)
        t = self.trunk(y)                       # (n_funcs, n_points, p)
        return torch.einsum("np,nkp->nk", b, t) + self.bias


model = DeepONet()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for step in range(5000):
    u_s, y, G = sample(64, 100)
    loss = ((model(u_s, y) - G) ** 2).mean()
    opt.zero_grad()
    loss.backward()
    opt.step()

u_s, y, G = sample(500, 100)                    # unseen functions and points
with torch.no_grad():
    rel = ((model(u_s, y) - G).norm(dim=1) / G.norm(dim=1)).mean().item()
print(f"mean relative L2 error on 500 unseen functions: {rel:.3e}")

Step 3: what each part does

  • Branch network: sees the whole input function through its values at 50 fixed sensors, and encodes which function it is.
  • Trunk network: sees only the query point yy and learns pp basis functions of yy.
  • Dot product: combines them, G(u)(y)≈∑kbk(u) tk(y)+b0G(u)(y) \approx \sum_k b_k(u)\,t_k(y) + b_0, which is a learned, function-dependent expansion.

Applying DeepONet to physics problems

For a real PDE, the branch input is the function you vary, such as an initial profile, a source term or boundary data sampled at sensors. The trunk input is the space-time point where you want the solution, for example (x,t)(x, t). Training data come from a verified solver run on many sampled input functions. Because the trunk can be queried anywhere, DeepONet is convenient when you need outputs at scattered locations such as diagnostic positions.

Verify

Running the script prints the mean relative error on 500 functions not seen during training. Because the exact operator is known, the error is a true generalisation error. Further checks:

  1. Test inputs with larger amplitudes than in training (scale a by 3). The error grows, showing the input-distribution limit.
  2. Evaluate on a fine, regular grid of yy and plot the prediction against the exact antiderivative for a few functions.
  3. Vary p and the network width, and record the accuracy trend.

Troubleshooting

  • Error plateaus: increase p, network width or training steps, or use a learning-rate decay.
  • Good on training functions, poor on new ones: sample more diverse input functions in training. DeepONet only learns what the input distribution covers.
  • Sensor mismatch at inference: input functions must be sampled at exactly the same sensor locations used in training.

Assumptions and limitations

  • A linear operator with an exact solution, chosen for verifiability. Non-linear PDE operators need far more data and capacity.
  • Results vary with seeds and versions, so the script reports the error instead of us quoting a fixed value.
  • For production work, libraries such as DeepXDE implement DeepONet variants with tested utilities.

Frequently asked questions

How many sensor points does the branch network need?+

Enough to resolve the input functions you will use; the theory requires that the input can be recovered from its sensor values to the needed accuracy. For smooth inputs, tens to a hundred points in 1D are typical.

What does the output dimension p control?+

p is the number of learned basis functions. Larger p increases expressiveness and cost. If the error plateaus, increasing p (and network width) is one of the first things to try.

DeepONet or FNO?+

FNO is efficient on regular grids and often very accurate for smooth problems. DeepONet can be queried at arbitrary points and handles scattered outputs naturally. Many studies compare both on their problem.

Can I add physics to DeepONet?+

Yes. Physics-informed DeepONets add PDE-residual terms to the loss, computed with automatic differentiation with respect to the trunk input, which can reduce the amount of training data needed.

References

  1. Lu et al., Learning nonlinear operators via DeepONet based on the universal approximation theorem of operators, Nat. Mach. Intell. 3, 218 (2021) · Peer-reviewed article
  2. Chen & Chen, Universal approximation to nonlinear operators by neural networks, IEEE Trans. Neural Netw. 6, 911 (1995) · Peer-reviewed article
  3. DeepXDE documentation · DeepXDE 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