Physics in the loss and in the model

Physics as a penalty in the loss, or built into the model so that it holds by construction.

Outcome: Tell soft constraints (penalties) from hard constraints (built into the output); add a PDE residual to a loss and build a divergence-free velocity from a stream function; check physical consistency, not only field error; tell when a symmetry holds for the whole posed problem, and choose between building it in, augmenting and canonicalising.

Builds on Loss, gradients and autograd, Decoders and volume fields

A surrogate trained only on data learns physics approximately at best: mass and forces need not balance exactly, and a field error says little about the force error (outside the box, the project’s two models had similar field errors and lift errors far apart, Table 4-2; measuring error). There are two ways to do better: a soft or a hard constraint.

DefinitionSoft and hard constraints

A soft constraint adds a penalty to the loss when a law is broken; the network is encouraged, not forced. A hard constraint builds the law into the model's output, so it holds for any weights.

Soft: a PDE residual in the loss

The network's output is a function of its input coordinates, and autograd (backpropagation) gives its derivatives with respect to them. With those derivatives in the governing equation, its residual (how far the equation is from being satisfied) can be added to the loss at a set of points in the domain, with no data needed there. For steady conduction with constant conductivity and no heat source, ∇2T=0\nabla^2 T = 0:

L=mean⁡ (T^−T)2+λ mean⁡(∂2T^∂x2+∂2T^∂y2)2\begin{aligned} \mathcal{L} &= \operatorname{mean}\,(\hat{T} - T)^2 \\ &\quad + \lambda\,\operatorname{mean}\left(\frac{\partial^2 \hat{T}}{\partial x^2} + \frac{\partial^2 \hat{T}}{\partial y^2}\right)^2 \end{aligned}
(7-3)
T^\hat{T} is the network’s temperature and TT the solver’s. The first mean runs over the points with data, the second over the points in the domain where the residual is evaluated. λ\lambda balances fitting the data against satisfying the equation.

This is the idea of physics-informed neural networks (PINNs; Raissi et al. 2019). It tends to help most when data is scarce and the equation is known exactly. It has costs: second derivatives slow each step, λ\lambda needs tuning, training can fail even on simple equations (Krishnapriyan et al. 2021), and for turbulent flows the averaged equations a surrogate would need depend on a turbulence model, which is approximate.

Example 7-3 applies Equation 7-3 to the unit square. The data are 20 values on the boundary, taken from the exact solution T=sinh⁡(πy)sin⁡(πx)/sinh⁡πT = \sinh(\pi y) \sin(\pi x) / \sinh \pi, which is 1 at the middle of the top edge and 0 on the other three; inside, only the equation is enforced.

Example 7-3. A physics-informed loss for steady conduction, with PyTorch
import torch
from torch import nn

def T_exact(xy):                  # solves the Laplace equation
    x, y = xy[:, :1], xy[:, 1:]
    return (torch.sinh(torch.pi * y) * torch.sin(torch.pi * x)
            / torch.sinh(torch.tensor(torch.pi)))

# Data: 20 points around the boundary of the unit square.
s = torch.linspace(0, 1, 6)[:-1, None]
o, z = torch.ones_like(s), torch.zeros_like(s)
xy_b = torch.cat([torch.cat(p, 1) for p in
                  [(s, z), (o, s), (1 - s, o), (z, 1 - s)]])
T_b = T_exact(xy_b)

torch.manual_seed(0)
net = nn.Sequential(nn.Linear(2, 32), nn.Tanh(),
                    nn.Linear(32, 32), nn.Tanh(),
                    nn.Linear(32, 1))
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
grad = torch.autograd.grad
lam = 1.01
for step in range(5000):
    # Fresh collocation points inside the square, no data.
    xy = torch.rand(256, 2, requires_grad=True)2
    dT = grad(net(xy).sum(), xy, create_graph=True)[0]3
    T_xx = grad(dT[:, 0].sum(), xy, create_graph=True)[0][:, 0]
    T_yy = grad(dT[:, 1].sum(), xy, create_graph=True)[0][:, 1]
    # Data on the boundary, residual inside.
    loss = (((net(xy_b) - T_b) ** 2).mean()
            + lam * ((T_xx + T_yy) ** 2).mean())4
    opt.zero_grad()
    loss.backward()
    opt.step()

# The largest error over 10,000 random points.
xy = torch.rand(10_000, 2)
with torch.no_grad():
    err = (net(xy) - T_exact(xy)).abs().max().item()
print(f"{err:.3f}")
  1. λ\lambda of Equation 7-3, here 1.
  2. The collocation points: 256 fresh random points inside the square at every step, where only the residual is evaluated.
  3. create_graph=True keeps the first derivatives differentiable, so they can be differentiated again for ∂2T^/∂x2\partial^2 \hat{T}/\partial x^2 and ∂2T^/∂y2\partial^2 \hat{T}/\partial y^2, and the loss can be backpropagated through them.
  4. The two means of Equation 7-3: the data term on the 20 boundary points, then the residual at the collocation points.

Example 7-3 prints 0.049: the largest error over the square, for a temperature that peaks at 1, from 20 boundary values and the equation alone. It takes about five seconds on one laptop CPU, with three extra differentiations of the network at every step.

Hard: a divergence-free velocity

In incompressible flow, mass conservation says the divergence of the velocity (u,v)(u, v), ∂u/∂x+∂v/∂y\partial u/\partial x + \partial v/\partial y, is zero: whatever flows into a duct must flow out, so where the section narrows the flow speeds up. Instead of uu and vv, the network predicts a stream function ψ\psi, with u=∂ψ/∂yu = \partial \psi/\partial y and v=−∂ψ/∂xv = -\partial \psi/\partial x. Then the divergence is

∂u∂x+∂v∂y=∂2ψ∂x ∂y−∂2ψ∂y ∂x=0\frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} = \frac{\partial^2 \psi}{\partial x\,\partial y} - \frac{\partial^2 \psi}{\partial y\,\partial x} = 0
(7-4)
The mixed derivatives are equal for any twice continuously differentiable ψ\psi, so the sum is zero whatever the network does.

In 3D the same construction uses a vector potential: the velocity is the curl of a predicted field, u=∇×A\mathbf{u} = \nabla \times \mathbf{A}, and the divergence of a curl is zero. In one experiment AB-UPT uses this identity: it defines vorticity as the curl of its predicted velocity, so the vorticity is divergence-free by construction, at the cost of six extra forward passes for central differences.

Example 7-4. A divergence-free velocity field, with PyTorch
import torch
from torch import nn

torch.manual_seed(0)
psi = nn.Sequential(nn.Linear(2, 64), nn.Tanh(),
                    nn.Linear(64, 64), nn.Tanh(),
                    nn.Linear(64, 1))

xy = torch.rand(1000, 2, requires_grad=True)
grad = torch.autograd.grad
dpsi = grad(psi(xy).sum(), xy, create_graph=True)[0]1
# u = d psi / dy,  v = - d psi / dx
u, v = dpsi[:, 1], -dpsi[:, 0]2

# Divergence du/dx + dv/dy: zero for any weights.
du = grad(u.sum(), xy, create_graph=True)[0]
dv = grad(v.sum(), xy, create_graph=True)[0]
div = du[:, 0] + dv[:, 1]3
# Below 1e-6: float32 round-off only.
print(div.abs().max().item())
  1. Each output row depends only on its own input row, so the gradient of the sum gives every point its own (∂ψ/∂x,∂ψ/∂y)(\partial \psi/\partial x, \partial \psi/\partial y). create_graph=True keeps that result differentiable, for the second derivatives below.
  2. Column 1 of dpsi is ∂ψ/∂y\partial \psi/\partial y and column 0 is ∂ψ/∂x\partial \psi/\partial x: the definitions given just before Equation 7-4.
  3. Column 0 of du is ∂u/∂x\partial u/\partial x and column 1 of dv is ∂v/∂y\partial v/\partial y.

Example 7-4 prints 5.960464477539063e-08, the largest divergence over the 1,000 points: round-off, from weights that were never trained.

Symmetries

Symmetries are hard constraints too. Feeding only relative positions, as in graph networks, makes a model translation-invariant: moving the part changes nothing. Rotation needs more: only inputs that do not change under rotation, such as distances and angles, or an equivariant network, whose output vectors rotate with its input (for example the E(n)-equivariant graph networks of Satorras et al. 2021). A model with a symmetry built in cannot violate it and, when the physics has that symmetry, often needs less data (Elesedy and Zaidi 2021; Batzner et al. 2022, on interatomic potentials).

A symmetry belongs to the whole posed problem, not to the geometry alone (from runs to arrays). The Navier–Stokes equations take the same form in any frame obtained by a rotation, reflection or translation. So if a posed problem has one solution, moving everything that poses it (the body, the boundary conditions with their prescribed vectors, the free stream, gravity, the ground) gives the same flow seen from the new frame: velocities turned with it, pressures unchanged at the corresponding points. A car rotated together with its free stream and its ground is the same problem; a car rotated under a free stream that stays fixed is a different one.

There are three standard routes to a symmetry (Bronstein et al., Geometric Deep Learning). Build it in: feed only invariant quantities and assemble vector or tensor outputs from invariant coefficients times vectors or tensors the model was given, as TBNN does for the Reynolds stress, or make every layer equivariant, as SEGNN and GATr do. Augment: train on randomly transformed copies, so that the model learns the symmetry approximately. Canonicalise: move each case to a frame of its own, such as its principal axes, before the model sees it. A model that has the symmetry by none of these routes must learn it from the data, and data in one pose do not show it. ISLA (Sharpe, 2026) is an example of the first route in a transformer: no learned operation receives a coordinate, and positions enter only as distances and relative angles.