Time stepping and rollouts

The next state is predicted from the current one and fed back in; errors tend to grow with each step.

Outcome: Roll a next-step model out in time, and explain why its errors grow; train with Δu prediction, an unrolled loss and noise injection in PyTorch; read rollout results: error against time, VRMSE, several seeds.

Builds on Graph networks and MeshGraphNets, Normalising and the training loop, Overfitting and regularisation

Many surrogates predict how a field changes in time: vortex shedding behind a cylinder, a crash, the flow in a combustor. A solver marches in small time steps; a surrogate usually does the same with a larger step.

DefinitionAutoregressive rollout

The sequence of states from a model trained to map the state at time tt to the state at t+Δtt + \Delta t, when each output is fed back as the next input.

In crash the state must also hold what the material remembers, such as plastic strain, not only positions and velocities. The site’s aircraft is steady, so this lesson uses Burgers’ equation, a 1D model of convection and diffusion that forms steep fronts.

Why errors grow

A model trained only to predict one step ahead is never shown its own mistakes. At test time it is fed them, and small errors can compound: a state slightly off becomes the input for a step the model was never trained on, which drifts further. Errors often grow fastest at high frequencies, where a small one-step error is large relative to the signal. Past a certain number of steps the rollout can leave the range of states seen in training altogether.

One remedy is to train on several steps at once. Equation 5-6 unrolls the model for KK steps from a solver state and puts the loss on all of them, so it sees its own errors in training.

u^t=utu^t+j=u^t+j−1+fθ(u^t+j−1)L=1Kn∑j=1K∑i=1n(u^t+j,i−ut+j,i)2\begin{aligned} \hat{u}_t &= u_t \\ \hat{u}_{t+j} &= \hat{u}_{t+j-1} + f_\theta(\hat{u}_{t+j-1}) \\ \mathcal{L} &= \frac{1}{Kn} \sum_{j=1}^{K} \sum_{i=1}^{n} \big(\hat{u}_{t+j,i} - u_{t+j,i}\big)^2 \end{aligned}
(5-6)
utu_t is the solver’s state at saved step tt, with nn grid values; fθf_\theta is the network, which predicts the change; KK is the number of unrolled steps, 1 or 4 in the script. The loss is also averaged over the 64 (run, start time) pairs of each batch. With K=1K = 1 every prediction starts from solver data.
Example 5-8. A convolutional model of Burgers’ equation, trained on one step and on four unrolled steps, then rolled out for 100 steps
import torch
from torch import nn

torch.manual_seed(0)
torch.set_num_threads(1)
n, nu, h = 64, 0.01, 0.002
dx = 1.0 / n

def solver(u, substeps=10):
    # Burgers' equation, explicit, periodic in x.
    # One saved time step = 10 small solver steps.
    for _ in range(substeps):
        up, um = u.roll(-1, -1), u.roll(1, -1)
        ux = (up - um) / (2 * dx)
        uxx = (up - 2 * u + um) / dx**2
        u = u + h * (-u * ux + nu * uxx)1
    return u

def trajectories(m, steps):
    x = torch.arange(n) * dx * 2 * torch.pi
    k = torch.randint(1, 4, (m, 1)).float()
    amp = 0.2 + 0.5 * torch.rand(m, 1)
    u = amp * torch.sin(k * x + 6.28 * torch.rand(m, 1))
    out = [u]
    for _ in range(steps):
        u = solver(u)
        out.append(u)
    # (m, steps + 1, n): one row per saved time step
    return torch.stack(out, 1)

def step(model, u):
    # Predict the change du, not the next state.
    return u + model(u[:, None])[:, 0]2

def train(unroll, iters=1500):
    c = dict(padding=2, padding_mode="circular")
    model = nn.Sequential(
        nn.Conv1d(1, 32, 5, **c), nn.SiLU(),
        nn.Conv1d(32, 32, 5, **c), nn.SiLU(),
        nn.Conv1d(32, 1, 5, **c))
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    T = data.shape[1]
    for _ in range(iters):
        # 64 random (run, start time) pairs
        r = torch.randint(0, len(data), (64,))
        t = torch.randint(0, T - unroll, (64,))3
        u, loss = data[r, t], 0.0
        for j in range(1, unroll + 1):
            # unroll > 1: the model is fed its own output
            u = step(model, u)
            loss = loss + ((u - data[r, t + j]) ** 2).mean()4
        opt.zero_grad()
        (loss / unroll).backward()
        opt.step()
    return model

def rollout_error(model, runs, steps=100):
    u, errs = runs[:, 0], []
    with torch.no_grad():
        for t in range(1, steps + 1):
            u = step(model, u)
            e = (u - runs[:, t]).norm(dim=1)
            rel = e / runs[:, t].norm(dim=1)5
            errs.append(rel.mean().item())
    return errs

data = trajectories(64, 60)
test = trajectories(16, 100)
for unroll in (1, 4):
    errs = rollout_error(train(unroll), test)
    # relative L2 error after 1, 10, 30, 60, 100 steps
    print(unroll, [round(errs[t - 1], 3)
                   for t in (1, 10, 30, 60, 100)])
  1. One explicit Euler step of ∂tu=−u ∂xu+ν ∂x2u\partial_t u = -u\,\partial_x u + \nu\,\partial_x^2 u, with central differences in xx.
  2. [:, None] adds the channel axis that Conv1d expects, and [:, 0] removes it: fθf_\theta in Equation 5-6.
  3. Start times stop unroll steps before the end, so every target t + j exists.
  4. One term of the sum in Equation 5-6, averaged over the batch and the grid.
  5. The relative L2 error of each test run at step t, then its mean over the 16 runs. The script runs in a minute or two on a recent laptop CPU.
1 [0.004, 0.011, 0.027, 0.212, 7.095]
4 [0.006, 0.013, 0.042, 0.17, 4.82]

Example 5-8 prints each model’s relative L2 error after 1, 10, 30, 60 and 100 steps. Trained on one step, the model’s error goes from 0.4 % after one step to 21 % after 60 and about 710 % after 100. Trained on four unrolled steps, the same seed ends at 17 % and about 480 %.

relative L2 errorrollout step0.1%1%10%100%1000%beyondtraining data120406080100
Figure 5-6. Relative L2 error of the lesson’s one-step Burgers model over 100 rollout steps, log scale, for six random seeds (thick line: the run in the text). The shaded steps lie beyond step 60, where the training trajectories end.

That gain does not hold: with seeds 1, 2 and 3 of the same script the four-step model was worse at both horizons, for example 117 % against 18 % at step 60 on seed 2. The thin lines of Figure 5-6 show how much one training run differs from the next.

The standard remedies

  • Predict the change. The network predicts Δu=u(t+Δt)−u(t)\Delta u = u(t + \Delta t) - u(t), which is added to the current state. Over a short step the change is small, and the network does not have to copy the state through.
  • Condition on a short history. The model receives the last two to four states, so it can estimate rates of change, as a multistep time integrator does.
  • Noise injection. A little random noise is added to the input states during training, as MeshGraphNets and the Graph Network Simulator (GNS) do. The aim is that the model learns to pull a slightly wrong state back towards the right one.
  • Unrolled training. The model is rolled out for a few steps during training, with the loss on all of them, so it sees its own errors. Backpropagating through every step is expensive; the pushforward trick of Brandstetter, Worrall and Welling (2022) (section 3.1) unrolls two steps but backpropagates only through the last.
  • Refinement and generative models. PDE-Refiner (Lippe et al. 2023) refines each step over several denoising passes so that low-amplitude components, often at high frequency, are not lost; diffusion surrogates sample each step from noise (generative surrogates). The price is several network evaluations per step.

These are widely used and none is guaranteed, so each needs tuning and testing over several seeds.

Reporting rollout error

The informative report is the error as a function of rollout time, over several seeds; one seed and one horizon show little. Common forms are the relative L2 error at several horizons, the VRMSE of The Well (see measuring error: 1.0 means no better than predicting the mean), and the time until the correlation between prediction and truth drops below a threshold (as in Kochkov et al. 2021). For chaotic flows a pointwise error must grow eventually, since nearby states separate exponentially (Lorenz 1963); there, statistics such as spectra or mean fields are compared instead.