Hamiltonian Neural Networks: Physics as Inductive Bias

Build a Hamiltonian Neural Network from scratch in PyTorch: learn a scalar energy, take its symplectic gradient, and conserve energy where a plain MLP drifts.

Cover Image for Hamiltonian Neural Networks: Physics as Inductive Bias

You train a network on the motion of an ideal pendulum to predict how it moves next. The short predictions look plausible, but following them for a long time can produce a swing that fades or grows without a physical reason. Small errors have accumulated in a system whose energy should stay constant. Hamiltonian neural networks give us a way to build that physical structure into the prediction, instead of asking the network to discover it from examples alone.

The HNN predicts through a learned energy function, following Greydanus, Dzamba and Yosinski's 2019 construction. Its continuous flow conserves that function even when it is imperfect. We compare models on identical mass-spring observations. The MLP rollout loses 24.2% energy, while the HNN loses approximately none. Long trajectories test the practical consequence.

This post builds one from scratch in about forty lines of PyTorch. We train it on an ideal mass-spring and a pendulum, compare it against an ordinary MLP given exactly the same data, and watch the MLP's orbit spiral inward as energy drains away while the HNN's orbit closes on itself for eighty laps. By the end you will have used autograd to differentiate through a learned energy, and you will have kept a planet in a stable orbit that the baseline sends crashing into its star.

Let's Build It

An ideal mass on a spring has one number that never changes: its total energy, H(q,p)=12(q2+p2)H(q, p) = \tfrac{1}{2}(q^2 + p^2), where qq is position and pp is momentum. The whole motion follows from that energy through Hamilton's equations, which we will meet properly in a moment. For now, treat the energy as the thing to learn.

Open the notebook and run the full comparison in Colab:

Open In Colab

The animation below is the punchline. Both models were trained on the same orbits and rolled forward from the same starting point. The baseline spirals in; the Hamiltonian network holds its ground.

Two side-by-side phase-space panels animating a rollout from the same start point. In the left panel, labelled Baseline MLP, the trajectory spirals steadily inward and the energy readout falls from 2.64 toward 2.0. In the right panel, labelled Hamiltonian NN, the trajectory retraces the same circle and the energy readout stays pinned near 2.64.

Here is the entire method. The HNN learns a scalar energy and returns its symplectic gradient; the baseline predicts the velocity field directly.

import numpy as np, torch, torch.nn as nn
torch.manual_seed(0)

# Ideal mass-spring. Its conserved energy is H(q, p) = (q^2 + p^2)/2.
def true_field(s):                                  # s = [q, p]
    q, p = s[..., 0], s[..., 1]
    return np.stack([p, -q], axis=-1)               # (dq/dt, dp/dt)

def energy(s):
    return 0.5 * (s[..., 0] ** 2 + s[..., 1] ** 2)

def rk4(f, s, dt):                                  # one integrator step
    k1 = f(s); k2 = f(s + .5*dt*k1); k3 = f(s + .5*dt*k2); k4 = f(s + dt*k3)
    return s + dt/6 * (k1 + 2*k2 + 2*k3 + k4)

def trajectory(f, s0, dt, n):
    out = np.zeros((n, 2)); s = s0.astype(float)
    for i in range(n):
        out[i] = s; s = rk4(f, s, dt)
    return out

# Training data: 40 short orbits at random radii, and their velocities.
rng = np.random.default_rng(1)
orbits = [trajectory(true_field,
                     np.array([r*np.cos(a), r*np.sin(a)]), 0.1, 50)
          for r, a in zip(rng.uniform(1.0, 2.5, 40), rng.uniform(0, 2*np.pi, 40))]
X = np.concatenate(orbits).astype(np.float32)
Y = (true_field(X) + rng.normal(scale=0.01, size=X.shape)).astype(np.float32)

# Baseline: predict the velocity field directly.
def baseline(h=200):
    return nn.Sequential(nn.Linear(2, h), nn.Tanh(),
                         nn.Linear(h, h), nn.Tanh(), nn.Linear(h, 2))

# HNN: learn a scalar H, differentiate it, rotate the gradient 90 degrees.
class HNN(nn.Module):
    def __init__(self, h=200):
        super().__init__()
        self.H = nn.Sequential(nn.Linear(2, h), nn.Tanh(),
                               nn.Linear(h, h), nn.Tanh(), nn.Linear(h, 1))
    def forward(self, x):
        x = x.requires_grad_(True)
        dH = torch.autograd.grad(self.H(x).sum(), x, create_graph=True)[0]
        return torch.stack([dH[:, 1], -dH[:, 0]], dim=1)   # (dH/dp, -dH/dq)

def train(model, steps=3000):
    Xt, Yt = torch.tensor(X), torch.tensor(Y)
    opt = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-6)
    sched = torch.optim.lr_scheduler.StepLR(opt, step_size=1000, gamma=0.3)
    for _ in range(steps):
        opt.zero_grad()
        loss = ((model(Xt) - Yt) ** 2).mean()
        loss.backward(); opt.step(); sched.step()
    return model

def learned_field(model):
    def f(s):
        d = model(torch.tensor(np.atleast_2d(s), dtype=torch.float32))
        return d.detach().numpy().reshape(np.shape(s))
    return f

hnn, mlp = train(HNN()), train(baseline())
s0 = np.array([2.3, 0.0])                            # start on a circle of radius 2.3
for name, model in [("MLP", mlp), ("HNN", hnn)]:
    roll = trajectory(learned_field(model), s0, 0.1, 5000)   # 80 orbits
    e = energy(roll)
    print(f"{name}: energy drift over 80 orbits = {100*(e[-1]-e[0])/e[0]:+.1f}%")
# MLP: energy drift over 80 orbits = -24.2%
# HNN: energy drift over 80 orbits = -0.0%

Both models saw identical data and both fit it well. Roll them forward and one obeys a conservation law it was never told about; the other does not.

Two phase-space panels for the mass-spring, each showing the learned rollout coloured by time from dark (early) to yellow (late) against the true orbit as a grey dashed circle. The left panel, Baseline MLP, shows the trajectory spiralling visibly inward with an energy drift of -24.2 percent over 80 orbits. The right panel, Hamiltonian NN, shows the trajectory staying locked on the true circle with a drift of -0.0 percent.

The left panel bleeds energy; over eighty orbits the radius shrinks by an eighth. The right panel is a clean annulus one line wide. Same optimiser, same integrator, same data. The only thing that changed is what the network was asked to output.

What Just Happened?

Learning a vector field

Both models solve the same supervised problem. The input is a state (q,p)(q, p), a point in phase space (position on one axis, momentum on the other). The target is the state's velocity (q˙,p˙)(\dot q, \dot p), the little arrow that says where the system moves next. Collect enough (state, velocity) pairs and you can fit the whole flow field, then integrate it forward to predict trajectories.

A phase-space plot for the mass-spring. Teal dots mark the training states, which fall on several concentric rings because the data comes from circular orbits at different radii. Faint grey arrows form a rotational vector field circulating clockwise around the origin, showing the velocity attached to each point in the plane.

The training data is nothing more than dots (states) with arrows (velocities). A mass-spring traces circles in phase space, so the samples sit on concentric rings, and the arrows circulate around the origin. Give the network a point and it must predict the arrow. That is a plain regression problem, and both models learn it.

The symplectic gradient

The baseline maps a two-dimensional state to a two-dimensional velocity with a standard MLP. Nothing about that mapping knows the arrows should preserve anything.

The HNN takes a detour. It maps the state to a single number, an estimate of the energy H(q,p)H(q, p), then produces the velocity by differentiating that scalar and rotating the gradient ninety degrees:

q˙=∂H∂p,p˙=−∂H∂q\dot q = \frac{\partial H}{\partial p}, \qquad \dot p = -\frac{\partial H}{\partial q}

Those are Hamilton's equations, the two-hundred-year-old rewrite of Newton's laws in terms of position, momentum, and energy. The right-hand sides are the partial derivatives of HH, with a sign flip and a swap. In code, torch.autograd.grad computes both derivatives of the network's scalar output in one call, and the torch.stack([dH[:, 1], -dH[:, 0]]) line applies the swap-and-flip. Because we pass create_graph=True, the gradient itself stays differentiable, so backpropagation can train the weights through it.

The velocity field the HNN produces is therefore not an arbitrary function. It is the symplectic gradient of a scalar: a vector field that circulates around the level sets of HH instead of pointing across them. Rotating a gradient by ninety degrees turns "uphill" into "around the hill", and going around a hill keeps your height constant. Height, here, is energy.

Conservation by construction

Both models drove their training loss down to about 10−410^{-4}, and the curves are nearly on top of each other. Fit quality is not the difference between them.

A training-loss plot on a log scale, showing vector-field mean-squared error against training step for both models. The baseline MLP in red and the Hamiltonian NN in teal both fall steeply from about 1 to roughly 1e-4 within the first thousand steps, then plateau together near 1e-4 with no spikes.

The difference appears only when you integrate. Track the total energy along each rollout and the story is stark: the true energy is flat, the HNN sits on top of it, and the baseline slides downhill without stopping.

A plot of total energy against time for an 80-orbit mass-spring rollout. The true energy and the Hamiltonian NN both hold a flat line at about 2.65 and are indistinguishable. The baseline MLP declines almost linearly from 2.65 at the start to about 2.0 at time 500.

Here is why the HNN cannot drift. Ask how fast its own learned energy changes as the system moves along the HNN's own predicted velocity. By the chain rule that rate is the gradient of HH dotted with the velocity, and the velocity is the symplectic gradient of the same HH:

dHdt=∂H∂qq˙+∂H∂pp˙=∂H∂q∂H∂p−∂H∂p∂H∂q=0\frac{dH}{dt} = \frac{\partial H}{\partial q}\dot q + \frac{\partial H}{\partial p}\dot p = \frac{\partial H}{\partial q}\frac{\partial H}{\partial p} - \frac{\partial H}{\partial p}\frac{\partial H}{\partial q} = 0

The two terms cancel exactly, for any HH whatsoever, even a half-trained one. The learned energy is conserved along the learned flow as a matter of algebra, not accuracy. The baseline has no such identity. Its velocity field is a free function, so dH/dtdH/dt is whatever the fit happens to produce, and small errors in different directions never cancel. They accumulate, and the orbit spirals.

Going Deeper

Hamilton's equations

The setup borrows the language of classical mechanics. A system is described by generalised coordinates qq (positions) and their conjugate momenta pp. The Hamiltonian H(q,p)H(q, p) is the total energy written as a function of those two. For the mass-spring, H=12p2+12q2H = \tfrac{1}{2}p^2 + \tfrac{1}{2}q^2 is kinetic plus potential energy. For a pendulum of unit mass and length, H=12p2+(1−cos⁡q)H = \tfrac{1}{2}p^2 + (1 - \cos q). Hamilton's equations then say the state flows so that qq climbs the momentum-gradient of the energy while pp descends the position-gradient.

The geometry matters more than the vocabulary. In phase space the level sets of HH are closed curves (circles for the mass-spring, eye-shaped loops for the pendulum), and Hamilton's equations send the state around those curves, never across them. Energy conservation is exactly the statement that trajectories stay on a single level set. Baking Hamilton's equations into the network is what forces its trajectories onto level sets too.

The learned energy surface

The HNN was trained only on velocities. It never saw an energy value. Yet because its output is the gradient of a scalar, that scalar has to exist, and we can plot it by evaluating the self.H sub-network on a grid.

Two filled contour plots side by side over the position-momentum plane. The left panel shows the true Hamiltonian, a bowl of concentric circular contours centred at the origin. The right panel shows the HNN's learned Hamiltonian, a near-identical bowl of concentric circles, matching the true energy surface up to an overall constant.

The learned surface is the true energy bowl, recovered up to an additive constant (the network has no way to know the zero point, and it does not matter because only the gradient enters the dynamics). The HNN reconstructed the conserved quantity of the system from nothing but snapshots of motion. That is the payoff of the inductive bias: structure you did not supply falls out because the architecture assumed it.

The pendulum: a nonlinear test

The mass-spring is linear, so a skeptic might suspect the HNN only wins on a toy. Swap in the pendulum, whose sin⁡q\sin q restoring force makes the dynamics nonlinear, and retrain both models unchanged.

Two panels for the pendulum. The left panel shows phase space with the true orbit as a grey dashed eye-shaped loop; the Hamiltonian NN traces it exactly while the baseline MLP forms a thick red band that has spiralled inward off the true loop. The right panel plots total energy against time: the HNN holds a nearly flat line around 1.505 while the baseline falls steadily from 1.505 to about 1.05.

The contrast survives the nonlinearity. The HNN's energy stays inside a band a fraction of a percent wide and holds there; the baseline sheds about thirty percent of its energy over the same window and keeps going. The HNN's tiny wobble is honest: its learned energy is not perfect, so the level set it rides is slightly wrong, but it is still a closed level set, so the orbit stays bound. The baseline has no level set to ride.

Where the inductive bias breaks

A conservation prior helps only when the thing is conserved. Hamilton's equations describe conservative systems, the frictionless idealisations. Add a damper to the spring or air resistance to the pendulum and energy does decrease; forcing dH/dt=0dH/dt = 0 then fights the physics and the HNN fits worse than a plain MLP, which is free to represent the decay. The clean version of the fix is to let the network output a Hamiltonian part plus a separate dissipative part, which is what dissipative and port-Hamiltonian variants do. The lesson generalises past physics: an inductive bias is leverage when the assumption holds and a straitjacket when it does not. Before reaching for an HNN, ask whether your system conserves something.

Hyperparameters and training

There is little to tune, and the defaults follow the original paper. The energy network is a small MLP: two hidden layers of two hundred units with tanh⁡\tanh activations. The tanh matters more than it looks, because the dynamics need a smooth second derivative and ReLU's kink makes the gradient field piecewise-constant. Training is plain Adam at a learning rate of 10−310^{-3} with light weight decay, and a step schedule that decays the rate keeps the loss from rattling around the flat minimum. The only real modelling choice is the coordinates: the method assumes you feed it canonical (q,p)(q, p) pairs. When you have those, an HNN is close to free to add on top of whatever network you were already using.

Where This Comes From

Hamiltonian Neural Networks were introduced by Sam Greydanus, Misko Dzamba and Jason Yosinski in "Hamiltonian Neural Networks" (NeurIPS 2019). Their framing is the one we implemented: parametrise the Hamiltonian with a neural network, obtain the dynamics as its symplectic gradient, and train by matching the predicted (q˙,p˙)(\dot q, \dot p) to observed time-derivatives.

"Rather than crafting Hamiltonians by hand, we propose to parameterize them with differentiable models and then learn them directly from data. [...] In doing so, we end up with models that respect exact conservation laws." (Greydanus, Dzamba & Yosinski, 2019)

Their loss is the objective in our train function, written for coordinates qq and momenta pp:

LHNN=∥∂Hθ∂p−dqdt∥2+∥∂Hθ∂q+dpdt∥2L_{\text{HNN}} = \left\lVert \frac{\partial H_\theta}{\partial p} - \frac{dq}{dt} \right\rVert^2 + \left\lVert \frac{\partial H_\theta}{\partial q} + \frac{dp}{dt} \right\rVert^2

The paper's most memorable experiment is orbital. Two bodies attract each other under gravity, a conservative system whose energy and momentum are fixed for all time. A baseline learns the orbit locally then lets it decay or fly apart; the HNN holds it. Reproducing that experiment as a planet around a fixed star shows the same split we saw on the spring, only more dramatic, because an unstable orbit does not just blur, it falls apart.

Two panels titled a planet orbiting a star, each plotting the orbit in the x-y plane with a gold star at the origin and the true orbit as a grey dashed circle. The left panel, Baseline MLP, is labelled the orbit spirals off: the path precesses into a rosette and then flings outward off the plot. The right panel, Hamiltonian NN, is labelled stable bound orbit with energy drift plus zero percent: the path stays a tight annulus hugging the true orbit for the whole rollout.

The baseline planet precesses, then its orbit destabilises and it is thrown off entirely. The HNN planet keeps a bound orbit for the full rollout, energy conserved to within one percent, exactly as a real planet would. Nothing in either model was told about gravity or angular momentum; the difference is the symplectic gradient.

The idea spread quickly. Cranmer and colleagues' "Lagrangian Neural Networks" (2020) lift the requirement for canonical momenta, learning a Lagrangian instead so the method works in arbitrary coordinates. The rollout connects to Chen and colleagues' "Neural Ordinary Differential Equations" (2018), which treats a network as the right-hand side of an ODE and integrates it with a solver. Sanchez-Gonzalez and colleagues' "Hamiltonian Graph Networks with ODE Integrators" (2019) scale the trick to many-body systems by making the Hamiltonian a graph network.

Further Reading

Interactive Tools

  • GP Regression Playground: Another way to bake an assumption into a model: a Gaussian process encodes smoothness through its kernel the way an HNN encodes conservation through its architecture. Change the kernel and watch the prior change.
  • Eigenvalue & SVD Visualizer: The mass-spring's linear flow is a pure rotation, whose matrix has eigenvalues on the imaginary axis. Nudge them off-axis and the closed orbit becomes a spiral, exactly the failure mode the baseline falls into.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions