Graph networks and MeshGraphNets
Every mesh node updates from its neighbours, layer after layer.
Outcome: Describe a mesh as nodes and edges carrying features; write one message-passing layer with PyTorch Geometric; explain encode–process–decode and why K layers reach K hops.
Builds on Grids, meshes and point clouds, Neurons, layers and MLPs
A CFD or FE mesh is already a graph: nodes (mesh points) joined by edges (mesh connections). A graph network keeps it as it is, with no grid and no resampling, and lets every node exchange information with the nodes it is connected to.
Features on nodes and edges
Each node carries node features: a flag saying wall, inlet or fluid, the flow condition, and for time-dependent problems the current field values, but not its absolute position. Each edge carries edge features: the relative position of its two nodes and their distance. Because position enters only through these differences, the model gives the same answer wherever the part sits in space (translation invariance). Rotating the part is another matter, taken up in physics in the loss and in the model.
One round of message passing
DefinitionMessage passing
The update is residual: the layer computes a correction and adds it to what the node already had, which helps deep stacks train (He et al. 2016).
Encode, process, decode
MeshGraphNets (Pfaff et al. 2021) made this recipe common for mesh-based simulation. An encoder MLP lifts the raw node and edge features to 128 numbers each (section 3.1 of the paper). A processor of message-passing blocks does the work; the paper found 15 a good trade-off between accuracy and cost for all its systems (section 5). A decoder MLP turns each node's final features into the output field. Every block lets information travel one edge further, so after blocks a node has heard from its -hop neighbourhood, and from nothing beyond it.
With the source where it starts, how many blocks K does it take before every node in this patch has heard from it?
Put the source in a corner of Figure 5-4 and find the smallest that reaches the opposite corner. On a mesh hundreds of nodes across, that would be in the hundreds, and on a fine mesh 15 hops may span a few per cent of the domain’s width: too little to connect a wing tip to its root. Remedies are more blocks, or multiscale graphs that add coarser levels with long edges, the graph counterpart of a U-Net's pooling (Lino et al. 2021 is one example).
For moving structures such as cloth, the paper adds a second set of edges between nodes close in space but not connected in the mesh (world-space edges, for contact), and it can refine the mesh as it goes.
Example 5-4 builds the graph of Example 5-1 on the aircraft, stores each edge both ways, and runs an untrained model on it. Each node carries its normal and the design; each edge, the relative position of its two points and their distance.
Example 5-4. A message-passing block and an encode–process–decode model in PyTorch Geometric
import numpy as np
import torch
from torch import nn
from scipy.spatial import KDTree
from torch_geometric.nn import MessagePassing
from aircraft import load_runs
# On recent PyTorch, importing PyG may print a FutureWarning
# about torch.jit.script. It is harmless.
def mlp(i, o, h=64):
return nn.Sequential(nn.Linear(i, h), nn.SiLU(),
nn.Linear(h, o))
class Block(MessagePassing):
def __init__(self, d):
# Sum the messages arriving at each node.
super().__init__(aggr="sum")1
self.msg = mlp(3 * d, d) # from (h_i, h_j, e_ij)
self.upd = mlp(2 * d, d) # from (h_i, sum of msgs)
def forward(self, h, edge_index, e):
# propagate() calls message(), then sums per node.
m = self.propagate(edge_index, h=h, e=e)
# Residual: add a correction to h.
return h + self.upd(torch.cat([h, m], dim=-1))2
def message(self, h_i, h_j, e):3
# h_i: the receiving node, h_j: the sender
return self.msg(torch.cat([h_i, h_j, e], dim=-1))
class MeshGNN(nn.Module):
# Encode, process (K blocks), decode.
def __init__(self, node_in, edge_in, out, d=64, K=8):
super().__init__()
self.enc_n = mlp(node_in, d)
self.enc_e = mlp(edge_in, d)
self.blocks = nn.ModuleList(
Block(d) for _ in range(K))
self.dec = mlp(d, out)
def forward(self, x, edge_index, edge_attr):
h, e = self.enc_n(x), self.enc_e(edge_attr)
for blk in self.blocks:
h = blk(h, edge_index, e)
return self.dec(h)
# Run 0 of the aircraft: 2,000 surface points, no mesh
# edges in the file, so 8 nearest neighbours, both ways.
d = load_runs()
pos = torch.tensor(d["xyz"][0])
_, nbr = KDTree(d["xyz"][0]).query(d["xyz"][0], k=9)
pairs = np.stack([nbr[:, 1:].reshape(-1),
np.repeat(np.arange(2000), 8)])
pairs = np.unique(np.hstack([pairs, pairs[::-1]]), axis=1)
edge_index = torch.tensor(pairs)
# Edges carry relative position and distance.
rel = pos[edge_index[1]] - pos[edge_index[0]]4
edge_attr = torch.cat(
[rel, rel.norm(dim=-1, keepdim=True)], dim=-1)
# Nodes carry the normal and the design (the min-max
# scaling of 4.3), not their absolute position.
a, s = d["alpha"][0], d["sweep"][0]
design = torch.tensor([(a - 3) / 5, (s - 28) / 8])
x = torch.cat([torch.tensor(d["normal"][0]),
design.expand(2000, 2)], dim=-1)
torch.manual_seed(0)
model = MeshGNN(node_in=5, edge_in=4, out=1)
print(edge_index.shape, model(x, edge_index, edge_attr).shape)
- The residual update of Equation 5-2: the second MLP’s correction is added to the node’s features.
- PyG fills arguments ending in
_ifrom the receiver, row 1 ofedge_index, and those ending in_jfrom the sender, row 0.ealready has one row per edge. - Position of the receiver minus that of the sender: moving the whole mesh leaves it unchanged, which is what makes the model translation invariant.
Example 5-4 prints torch.Size([2, 19014]) torch.Size([2000, 1]): 19,014 one-way edges, fewer than twice 16,000 because many neighbour pairs already appear in both directions, and one value per node.
A graph network suits problems where the physics is local and the mesh itself changes, which is why MeshGraphNets is a common baseline for structures and crash; one body-in-white study compares it with Transolver on 150 LS-DYNA runs. Its cost grows with the number of edges, and on very large 3D meshes the graph may not fit in memory without partitioning. Attention, in the next unit, reaches everywhere in one layer, at a different price.
For transient problems (vortex shedding, a flag in the wind), a MeshGraphNets model predicts the next time step and is fed its own predictions to go further; time stepping and rollouts shows ways to slow those errors down.