Learned physical simulators: GNS, MeshGraphNets and GraphCast
Build graph-based learned simulators, compare one-step and rollout error, and analyze contact, conservation and multiscale communication.
After this lesson you can
- Explain encode-process-decode particle simulation and integration conventions.
- Derive rollout error bounds and evaluate stability over horizons.
- Distinguish material mesh edges from dynamic contact edges.
- Analyze symmetry and momentum conservation under internal and external forces.
- Compare multimesh communication and measured simulation costs.
Before you start
- 25Message passing neural network frameworkGeometric graphsE(n)-equivariant graph neural networkForces as gradients of an invariant energyTriangle mesh geometryOversquashingNeighborhood explosion
- 09Explicit and implicit Euler methodsSymplectic integrators
- 24Simulation timestep, integrators and stability
- 29Finite difference stencils for PDEsFourier neural operatorDeepONetPredictability horizon
- 22Compounding model error
Simulation feeds its own result back
Predicting the next frame of cloth differs from simulating it for hundreds of steps. In the first task the model receives a correct state at each evaluation. In the second it receives its own predictions, gradually moving away from states observed during training. Small one-step loss does not guarantee a stable rollout.
A graph network naturally represents interactions: nodes are particles or vertices and edges connect influencing objects. Message passing shares a rule across neighbors, but edge choice, variables, integrator and evaluation determine what physics can be learned.
Encode, process and decode
The encode-process-decode scheme first transforms node and edge properties into latent vectors. It then applies several message and update blocks; finally a decoder predicts a physical quantity, such as acceleration. The same edge network is reused across pairs, while aggregation must be neighbor-order invariant. Latent residuals help train deep blocks but do not turn learned dynamics into a conservation law.
In learned particle simulators, a radius graph connects and if . A useful edge input is relative displacement and its norm, not necessarily global position. Velocities are also invariant to a fixed coordinate-system translation. Boundary distance must change with it: translating particles and obstacle together preserves distances; translating only particles relative to the obstacle describes another physical problem.
If the network predicts , semi-implicit Euler updates velocity first and then position:
Acceleration targets derived from data must use the same difference convention and units as the integrator. Normalizing each component using training-set statistics helps balance magnitudes but does not authorize test information. Sanchez-Gonzalez et al. describe GNS with particles, messages and training noise; their generalization results are not a guarantee for every small model.
With equally spaced position samples, model input velocity can be obtained by a backward difference and target acceleration by the difference between successive velocities. If the target is reconstructed this way, changing without recomputing it changes units and meaning. A model trained at one step does not automatically become an integrator at another. If another frequency is needed, include and evaluate that condition or use an appropriate continuous rule.
Radius also sets physical scale. Too small a radius can disconnect the graph; a large one increases neighbor construction and processing cost and each layer mixes more distant interactions. In a fluid neighbor count can vary with density: sum retains information about how many contributions arrive, while mean reduces direct degree dependence. Neither is universal; compare them under changing density and resolution, and decide whether container boundaries and distances should be explicit inputs.
From one step to a horizon
Rollout stability depends on how errors propagate through dynamics. If in a region the true map is Lipschitz with constant and model local error is bounded by , then . From one obtains
This is a bound, not an exact prediction: assumptions must hold along trajectories and it may be very conservative. For and the factor is approximately ; with it is . Contractive dynamics limit accumulation under those assumptions, but an oscillatory or chaotic physical system need not be contractive in the chosen norm.
Perturbing training states exposes the model to deviated inputs. The target must account for how noise is added; otherwise incompatible dynamics are taught. Multi-step loss runs the model in the loop and penalizes trajectory at greater memory and compute cost. No technique guarantees universal stability: measure position error by horizon, energy or momentum where appropriate, and failure rate on initial conditions not used for training.
Two evaluations complement each other. Evaluation with true state at each step, sometimes called teacher forcing, asks whether the model interpolates received states well. Free rollout asks what happens when its errors change future inputs. The difference can appear even with small local errors: in contact, deviation changes collision timing and trajectories then receive different impulses. Plot error distributions and failures by horizon, not only a final mean.
A longer training horizon penalizes consequences invisible at one step, but propagating gradients over many steps can exhaust memory and produce ill-conditioned gradients. A compromise is starting with short windows, increasing length and recording each configuration’s cost. If used for planning, also measure what happens when actions are chosen using the simulator itself: a planner can exploit systematic model errors even when random trajectories appear accurate.
The sandbox is a toy 2D fluid: particles repel within a radius, gravity, damping and inelastic collisions with walls and segments. Reference uses explicit law ; a small network learns its intensity from sampled distances, with or without input perturbation. To speed the browser, its output is linearly interpolated in a table of 2049 distances. The model preserves radial direction and antisymmetry, but does not learn walls or every GNS variable. Network and solver use the same semi-implicit integrator and collision; they can diverge when local error changes collisions. The pour button changes initial state and resets both trajectories, not adds particles mid-trajectory. This experiment neither certifies stability nor ensures noise improves every scene. You can regenerate weights with fluid_train.py and PyTorch.
For the initial 20-particle scene, per-coordinate RMSE measured at steps 50, 200 and 400 was 0.0049, 0.1513 and 0.2188 for the no-noise model and 0.0101, 0.1954 and 0.2479 for the noise model. Both diverge on this trajectory and noise does not help; collisions can amplify small differences. Losses on sampled clean training distances were and respectively: training, not validation losses. The noise form and distance set differ from GNS training in the paper.
Material mesh and world proximity
In MeshGraphNets, mesh edges reflect material or discretization neighborhood. Folded cloth can place two regions close in space that are not mesh neighbors: proximity-based world edges can represent contact. The world graph may change each step while material connectivity can stay fixed or adapt via remeshing. Pfaff et al. study mesh simulation and resolution adaptation.
A proximity edge alone does not impose impenetrability or conservation. Remeshing also requires transferring state and supervision, and separating interpolation from dynamics error. A radius graph needs a convention for ties, duplicates and already-connected pairs. Representation must avoid accidentally including the same interaction twice.
Contact introduces a temporal detail: two distant vertices may approach during the next step, so constructing the graph only once at the start does not describe folding cloth. Rebuilding neighbors every step represents changing contact topology but makes cost and inclusion discontinuities depend on radius. A smooth barrier can reduce message jumps near the threshold; it still does not replace continuous collision detection when a particle crosses an obstacle between states.
In the cloth lab, two fixed vertices and the sphere supply external forces. Therefore total cloth momentum need not remain constant. Ablating world edges at inference measures what happens when the trained model loses contact information; attributing a difference to training design would require training a second model from scratch without those edges, with comparable seeds and budgets.
Symmetry and conservation are different conditions
Symmetries and conservation laws are related but not interchangeable. Relative displacements ensure input translation invariance when boundaries are translated too. An architecture using relative vectors and invariant scalars can be designed so vector outputs rotate with the scene; an arbitrary coordinate MLP is not automatically rotation equivariant.
For pairwise internal forces , constant masses and no external forces, the semi-implicit update satisfies
Each pair cancels. With gravity or external contact, particle momentum changes by external impulse: constancy should not be demanded. Antisymmetry does not guarantee energy or angular momentum conservation either; the latter needs additional conditions on force directions.
From local mesh to planet
Multimesh weather models connect scales so messages travel large distances without stacking as many layers on a fine mesh. A coarse edge can cover many fine-edge steps. This reduces graph distance but does not automatically eliminate information compression or justify out-of-distribution forecasts.
GraphCast learns from reanalysis and publishes deterministic forecasts up to ten days with a graph architecture. GenCast uses diffusion to generate a probabilistic ensemble of trajectories; ensemble spread is part of the product, not simply several copies of a deterministic forecast. Figures and comparisons in those works correspond to their data, metrics, baselines and hardware, not this lesson’s run.
A neural operator such as the FNO also learns a map between fields, but its spectral communication and discretization assumptions differ from a local-message graph. Fair comparison fixes domain, initial and boundary conditions, resolution, error, preparation and inference cost. Speed without comparable accuracy does not show a surrogate is better; nor is it fair to charge one-time training cost to every simulation without declaring how many queries amortize it.
To compare full cost separate data generation, training and execution. If is initial cost and cost per query, amortized cost of queries is . Comparison only makes sense if reference generation cost is added and both methods achieve useful accuracy on the same task. Measured time includes transfers, compilation and graph construction when needed in production; also report peak memory and variation across runs.
Lab: particles and one message per pair
Construct our own data for four particles with central springs between every pair and uniform gravity. This is toy dynamics, not a fluid; it checks training and integration structure without attributing full GNS capability. Use a complete graph, equivalent to a sufficiently large radius in this example, and unit masses. Ordered pair generates a force on and its opposite on .
import numpy as np
rng = np.random.default_rng(7)
n, dt, spring, rest = 4, 0.05, 0.7, 0.8
gravity = np.array([0.0, -0.15])
pairs = np.array([(i, j) for i in range(n) for j in range(i+1,n)])
inc = np.zeros((len(pairs), n))
inc[np.arange(len(pairs)), pairs[:,0]] = 1
inc[np.arange(len(pairs)), pairs[:,1]] = -1
def accel_true(x):
rel = x[..., pairs[:,1], :] - x[..., pairs[:,0], :]
length = np.maximum(np.linalg.norm(rel, axis=-1), 1e-8)
force = spring * (length-rest)[...,None] * rel / length[...,None]
return np.einsum('pn,...pd->...nd', inc, force) + gravity
def advance(x, v, acceleration):
v = v + dt * acceleration
return x + dt*v, v
def make_data(count, steps):
x = rng.normal(0, 0.5, (count,n,2))
v = rng.normal(0, 0.15, (count,n,2))
xs, accs = [], []
for _ in range(steps):
a = accel_true(x)
xs.append(x.copy()); accs.append(a.copy())
x, v = advance(x, v, a)
return np.concatenate(xs), np.concatenate(accs)
train_x, train_a = make_data(60, 40)
test_x, test_a = make_data(12, 40)
print('formas entrenamiento y prueba:', train_x.shape, test_x.shape)Each message is a one-hidden-layer network applied to distance. Scalar output multiplies relative displacement, making it rotation equivariant and forces antisymmetric by construction. Gravity is added separately. We learn from scratch with gradient descent. Both models start from the same weights; the second sees Gaussian-noised positions but retains clean acceleration as target. This is one specific state-denoising comparison, distinct from original GNS noise correction.
def init_model(seed=2):
r = np.random.default_rng(seed)
return [r.normal(0, 0.2, 12), np.zeros(12), r.normal(0, 0.2, 12), np.array(0.0)]
def predict(model, x, derivatives=False):
w1, b1, w2, b2 = model
rel = x[:,pairs[:,1],:] - x[:,pairs[:,0],:]
length = np.linalg.norm(rel, axis=-1)
h = np.tanh(length[...,None]*w1 + b1)
scalar = h @ w2 + b2
force = scalar[...,None] * rel
a = np.einsum('pn,bpd->bnd', inc, force) + gravity
return (a, rel, length, h) if derivatives else a
def train_steps(model, noise, steps, seed):
r = np.random.default_rng(seed)
for _ in range(steps):
idx = r.integers(0, len(train_x), size=128)
x = train_x[idx] + r.normal(0, noise, train_x[idx].shape)
a, rel, length, h = predict(model, x, True)
da = 2*(a-train_a[idx])/a.size
df = np.einsum('pn,bnd->bpd', inc, da)
ds = np.sum(df*rel, axis=-1)
dz = ds[...,None]*model[2]*(1-h*h)
grads = [np.sum(dz*length[...,None], axis=(0,1)), np.sum(dz, axis=(0,1)),
np.sum(ds[...,None]*h, axis=(0,1)), np.sum(ds)]
for param, grad in zip(model, grads):
param -= 0.03*grad
return model
clean, noisy = init_model(), init_model()
print('pérdida inicial:', np.mean((predict(clean, test_x)-test_a)**2))Splitting training into cells keeps each browser execution bounded. Each segment’s seeds are distinct and reproducible. Compare loss on clean and perturbed states; improvement in one metric does not necessarily mean better rollout.
train_steps(clean, 0.0, 180, 10)
train_steps(noisy, 0.03, 180, 11)
print('pérdidas intermedias:', np.mean((predict(clean,test_x)-test_a)**2), np.mean((predict(noisy,test_x)-test_a)**2))train_steps(clean, 0.0, 180, 12)
train_steps(noisy, 0.03, 180, 13)
print('pérdidas finales:', np.mean((predict(clean,test_x)-test_a)**2), np.mean((predict(noisy,test_x)-test_a)**2))The next experiment reserves a new initial state. It compares trajectories at 50, 200 and 1000 steps; it records position error and the difference between total momentum change and gravity impulse. The second readout checks antisymmetry, not energy or trajectory fidelity.
initial_x = rng.normal(0, 0.5, (1,n,2))
initial_v = rng.normal(0, 0.15, (1,n,2))
def rollout(model, horizon=1000):
xt, vt = initial_x.copy(), initial_v.copy()
xp, vp = xt.copy(), vt.copy()
p0 = vp.sum(axis=1)[0].copy()
report = []
for step in range(1, horizon+1):
xt, vt = advance(xt, vt, accel_true(xt))
xp, vp = advance(xp, vp, predict(model, xp))
if step in (50, 200, 1000):
error = np.sqrt(np.mean((xp-xt)**2))
balance = np.linalg.norm(vp.sum(axis=1)[0] - p0 - step*dt*n*gravity)
report.append((step, float(error), float(balance)))
return report
print('sin ruido:', rollout(clean))
print('con ruido:', rollout(noisy))One trajectory does not estimate the error distribution. Change initial-condition seed, repeat multiple training runs and report dispersion, failure cases and data-generation cost. Here the network uses the known force form, so comparison tests noise within a restricted family; it does not reproduce the full paper experiment or show noise always helps.
Cloth in PyTorch: mesh and contact messages
The second lab is cloth_lab.py. It generates cloth trajectories with vertices, springs, gravity and sphere collision through penalty, and reserves distinct test seeds. The graph has bidirectional material edges and world edges from sphere center to nearby vertices. Two blocks update latent vectors and the decoder predicts acceleration. This reduced implementation illustrates the design; it does not replicate every MeshGraphNets decision.
Training unrolls three steps and compares predicted and reference velocities, scaled by so the signal is not multiplied by . Evaluation applies 180 steps without correcting state and reports RMSE at intermediate horizons. It repeats evaluation suppressing contact messages, an inference ablation: not a comparison with a second model trained without world edges. Printed peak CUDA memory belongs to that execution and must be measured on available hardware, not assumed from GPU name.
Download the file and run it in an environment with NumPy and PyTorch. It uses CUDA if available; CPU performs the same calculations at different cost. Parameters, seeds, split and precision are in the file. Data are generated locally, so no prior checkpoint or production repository path is needed.
python cloth_lab.py
In a CUDA run with file seeds, test RMSE with contact was approximately 0.0045, 0.0280, 0.0891 and 0.2671 at steps 20, 60, 120 and 180. Suppressing contact messages only at inference gave 0.0045, 0.0280, 0.0891 and 0.2734. The small final difference does not demonstrate general advantage: this dataset is small, initial conditions are similar and the no-contact model is not retrained. Peak recorded training use was about 45.7 MiB PyTorch-allocated CUDA memory, not total GPU memory budget or a speed measurement.
Exercises
Step 1 of 3. How does particle i momentum change?
build_world_edges(pos, mesh_edges, radius). Return a sorted list of undirected pairs (i, j), with i < j, whose distance is strictly less than radius and which are not mesh edges. Accept mesh edges in either orientation and remove duplicates.import numpy as np
def build_world_edges(pos, mesh_edges, radius):
pass