Part of World Models Handbook
Embed physics into world models using Lagrangian and Hamiltonian architectures, contact and friction constraints, conservation laws.
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Physical Dynamics and Constraints
Imagine a robot arm that sweeps a cup off a table. A learned world model trained only on one-step prediction error can look convincing for a few frames and then produce an impossible rollout: the cup passes through the table, accelerates without a modeled force, or fails to slow when dissipation should matter. The loss did not explicitly require nonpenetration, force balance, or friction. These symptoms are useful diagnostic clues, but they are not one-to-one proofs of a missing concept. Penetration can also come from collision detection or integration error, for example. The practical question is which mechanical assumptions the model should enforce and which effects it should learn from data.
This chapter is about putting mechanics inside world models. We will work through rigid-body motion, deformable media, contact and friction, and conservation laws associated with symmetry. We will then study soft penalties, hard projections, and Hamiltonian architectures. A soft penalty discourages its encoded violation; a hard parameterization or verified projection can rule it out under stated solver assumptions. Exposed physical variables can also aid diagnosis when they are observable and identifiable. None of these choices guarantees accurate extrapolation: parameters, unmodeled forces, observations, and numerical integration can still be wrong.
As in Part I: The World-Model Idea, we keep a sharp line between what a model predicts and how an agent uses those predictions. Here we focus on the prediction side: making the dynamics model itself physically coherent. The decision-making machinery that consumes these predictions comes later, in Part VII: Planning and Agency. That separation is worth holding onto now, because it lets us evaluate a dynamics model on its own terms: as a predictor of what the world does, independent of any particular policy that might act on it.
Why Physics Belongs Inside the Model
In Part II, Chapter 6 we treated the transition model as a black box to be learned from data. That approach can work when the evaluation states resemble the training data and rollouts are short. Longer physical rollouts expose compounding rollout error: the model feeds its predictions back as inputs, so a small one-step bias can move the next state into a less-covered region and compound. Valid physical structure can rule out some impossible behavior in those regions, but it does not make the remaining predictions correct.
Physical structure attacks this problem from three directions:
- Inductive bias: Conservation laws and geometric structure restrict the hypothesis space. A hard parameterization or projection can remove entire classes of violating functions; a soft penalty merely makes them more costly during training.
- Extrapolation: Physical laws apply beyond the sampled states. Encoding a valid law can improve extrapolation and rule out some impossible predictions, but parameters and unmodeled effects still determine accuracy. A pendulum obeys the same nonlinear equation at every amplitude; representing that equation offers a better basis for extrapolation than memorizing observed amplitudes.
- Interpretability and debugging: An architecture that exposes energy, friction, or contact variables lets you compare them with measurements and constraints. This can narrow a diagnosis when the variables are observable and identifiable, though coupled mechanisms and numerical error may still produce the same symptom. Black-box models can be probed post hoc; structured models supply some diagnostics directly.
There is a tension to keep in view throughout. A fixed classical simulator enforces its encoded approximations but retains discretization error and model mismatch; calibration or learned components can improve it from data. A generic learned model can adapt to data without an explicit physical guarantee. Hybrid methods occupy the space between those endpoints, letting you decide which assumptions to enforce, which parameters to estimate, and which effects to leave flexible.
Rigid-Body Dynamics
Rigid-body dynamics describes objects whose shape does not change, so their configuration reduces to a finite set of coordinates. It is the workhorse of robotics and game physics, and it is the cleanest setting in which to see what "structure" means for a learned model. Most of the ideas in this chapter, energy functions, generalized coordinates, constraints, symplectic updates, are easiest to state for rigid bodies and then generalize, so we will spend some care here.
Generalized Coordinates and the Lagrangian
Recall from Part I, Chapter 6 that we described general dynamical systems as state-space models . For rigid bodies, the art is choosing the state. Here, generalized coordinates mean an independent local set of numbers that pins down the configuration. For an ideal open-chain arm, independent joint angles within a valid chart remove the link-length constraints that Cartesian joint positions would require. Closed kinematic loops and global orientation descriptions can still require constraints or multiple coordinate charts.
Given coordinates and velocities , a regular conservative mechanical system can encode its mechanical core in a single scalar function, the Lagrangian:
where:
- : the kinetic energy, the energy of motion
- : the potential energy, the energy stored in the configuration by gravity, springs, and other conservative fields
- : the Lagrangian, here kinetic energy minus potential energy; nonconservative forces, impacts, and active constraints require additional terms or equations
For a regular conservative Lagrangian system, masses, lengths, and conservative couplings enter through and . Actuation, dissipation, impacts, and time-dependent constraints require additional generalized forces or equations. The equations of motion follow from the Euler–Lagrange equation:
where:
- , : the -th generalized coordinate and its velocity
- : the conjugate momentum for coordinate , how the Lagrangian responds to velocity
- : the rate of change of that momentum along the trajectory
- : the position derivative of the Lagrangian, which contributes to the generalized-force balance
- : the generalized force or torque applied externally at coordinate
In words, the equation balances the change in conjugate momentum against the Lagrangian's position dependence and the applied generalized force. When , it gives ; is conserved only when is a cyclic coordinate, or more generally when the corresponding continuous symmetry holds. A regular learned Lagrangian, whose velocity Hessian is nonsingular, induces a structured vector field through differentiation. That reduces the learned output from a -component vector field to one scalar, but nonconservative forces and constraints remain separate modeling choices.
For a regular Lagrangian, define the conjugate momenta and the Hamiltonian . For the autonomous natural systems used here, it equals total mechanical energy; that identification is not universal. The dynamics become first-order and symmetric:
where collects externally applied generalized forces and torques. When , the canonical Hamiltonian flow preserves phase-space volume. Hamiltonian neural architectures build directly on this antisymmetric form. Position changes along the momentum gradient and momentum changes against the position gradient, making for an autonomous unforced system. Arbitrary dissipative or state-dependent forcing can break both energy conservation and volume preservation.
Why does this matter for world models? Suppose you train an autonomous neural scalar from observed trajectories. Computing and with autodiff gives a conservative Hamiltonian vector field for every setting of the weights. Its exact continuous flow conserves the learned scalar . Whether that scalar matches physical energy, and whether a discrete numerical rollout preserves it accurately, remain empirical questions. This is the idea behind Hamiltonian Neural Networks (Greydanus, Dzamba, and Yosinski, 2019) and Lagrangian Neural Networks (Cranmer et al., 2020), and we will implement a Hamiltonian model in the worked example. A regular autonomous Lagrangian network has an analogous learned energy conservation law. The Lagrangian variant is useful when you observe positions and velocities but not momenta, since it fits directly and avoids the change of variables.
Newton–Euler and Multibody Systems
The Lagrangian view is elegant but not the only one. The Newton–Euler formulation works directly with forces and torques on each body: for translation and, in a body-fixed frame about the center of mass, for rotation. Here is the constant body-frame inertia tensor and is angular velocity. The cross-product term produces gyroscopic effects such as precession. Chaining bodies together with joints yields the recursive algorithms used in real-time robot dynamics. Given the robot's masses, link lengths, and inertias, the multibody equations take the form
where:
- : the symmetric positive-definite mass matrix, which maps generalized accelerations to the forces they require
- : the vector of generalized accelerations
- : the Coriolis and centrifugal forces, the velocity-dependent terms that arise as parts of the body rotate
- : the generalized gravity torques, the joint forces gravity induces at configuration
- : the vector of applied joint forces or torques
Each term has a clean physical identity, and that identity is exploitable. For independent coordinates in a regular mechanical system, is symmetric positive-definite because kinetic energy is . The gravity term is the gradient of a potential, . These are checkable properties: losing positive definiteness makes the kinetic-energy model nonphysical and can make the acceleration solve ill-posed or unstable.
This is a classical system-identification target from Part II, Chapter 3: within a correctly specified, identifiable rigid-body model, estimating the inertial parameters determines its dynamics. Friction, compliance, actuator dynamics, and other mismatch remain outside that parameter set. The structured form therefore tells you which parameters to estimate and where a residual model may be needed. Inertial parameters enter linearly in common inverse-dynamics regressions, which can make that part of identification a convex least-squares problem.
What the Model Predicts Versus What the Agent Does
It is easy to conflate two different uses of a dynamics model. The model predicts states; the agent uses predictions to choose actions. Rigid-body structure serves both, but differently:
- For prediction, valid structure can improve long-horizon fidelity. Under the regularity and step-size conditions described below, symplectic integration can keep energy error bounded over many steps even while phase error accumulates.
- For control, selected structure can improve tractability. The control-affine multibody form supports inverse dynamics and computed-torque control; model predictive control can use quadratic programs after suitable linearization or convexification.
The distinction matters because a model can be good at one use and poor at the other. A model with excellent prediction but no convenient control structure may be harder to optimize inside a planning loop, while a tractable model with poor rollout fidelity can mislead a long-horizon plan. A differentiable or queryable black-box transition model can still support control, but mechanical structure often provides more useful optimization form and more specific invariants to test.
Deformable Bodies
Not everything is rigid. Continuum-based deformable models discretize a body into many degrees of freedom, together with velocities and material state; other families begin directly from discrete particles and constraints. At finite resolution, the element type, mesh, integration rule, and parameter calibration can materially affect behavior. Consistent convergent discretizations should approach the same continuum response under refinement, but two coarse or differently calibrated cloth models can behave unlike each other.
The main discretization families, each with a distinct modeling tradeoff, are:
- Mass–spring systems: Represent the body as particles connected by elastic springs, often with damping. They are easy to implement, but the material behavior depends on the mesh, and capturing volume preservation or buckling requires care. Two different meshes of the same object can behave differently, which is a symptom that the model is describing the discretization rather than the material.
- Finite element methods (FEM): Discretize a continuum-mechanics model into elements and integrate its constitutive response. FEM supports linear elasticity, hyperelasticity, and plasticity; stability and accuracy depend on the formulation, mesh, elements, and solver. Parameters such as Young's modulus, Poisson's ratio, and yield stress can then be estimated from experiments when they are identifiable.
- Position-based dynamics (PBD): Solve constraint projections directly on particle positions rather than integrating forces. Extremely stable and fast, which made it the standard in interactive graphics (Müller et al., 2007), but its convergence behavior means results are iteration- and timestep-dependent. Extended Position Based Dynamics (XPBD) restores physical consistency by making compliance explicit, decoupling stiffness from the timestep and iteration count.
- Material point method (MPM): Hybridize material-carrying particles with a background grid. Graphics research demonstrated snow simulation for feature films, and related particle-grid methods have been applied to other granular and fluid-like materials. The representation accommodates large deformation and topology change without a permanently connected mesh, although fracture and material behavior still depend on the constitutive model and discretization.
Why should a world-model builder care about these simulation methods? High-fidelity deformable simulation can be costly, so an offline simulator can serve as a teacher for a faster learned surrogate. The teacher still matters: a surrogate trained on PBD output inherits its finite-timestep and iteration behavior, and a planner may optimize against those artifacts. Deformable simulation also supplies a useful constraint language. Equality constraints such as a cloth edge's rest length or a volume residual are held at . Unilateral contact is different: a signed gap is kept at , with equality only at contact.
Contact, Friction, and Collision
Contact is where otherwise smooth mechanics becomes especially difficult. Ideal rigid contact introduces unilateral constraints and instantaneous impulses; compliant contact instead uses large but finite forces over a short duration. In either case the active contact set can change abruptly, and Coulomb friction couples normal and tangential behavior. Naive fixed-step differentiation can miss how a perturbation changes impact time or the contact schedule, although event-aware derivatives and smooth approximations can provide useful gradients. This section develops the constraint machinery needed to manage those mode changes.
Signaling Contact: Distance and Penetration
The first ingredient is a way to know whether two bodies touch. A standard tool is a signed distance function (SDF) , positive when separated, zero at contact, and negative when penetrating. For a differentiable spatial SDF, has unit norm and gives the local surface normal. If is written as a function of generalized coordinates , its gradient is instead the contact Jacobian that maps generalized motion to gap change. Many primitives have closed or piecewise-closed distance formulas, although edges and medial axes can be nondifferentiable; for meshes the field is computed or precomputed, and learned implicit representations can approximate it. In a model whose state decodes to solid geometry, a predicted negative gap is an immediate, checkable nonpenetration violation.
Contact as a Complementarity Problem
Non-penetration is naturally expressed as a constraint with a one-sided force. The normal force magnitude satisfies:
At each contact, three conditions must hold simultaneously:
Read this as: the bodies do not overlap, the contact force can only push (never pull), and force exists only when contact exists. After time discretization, a fixed contact geometry, and often a polyhedral approximation to friction, these conditions can yield a linear complementarity problem (LCP). More general rigid-contact formulations lead to nonlinear complementarity or cone programs.
Complementarity couples the two nonnegativity conditions and selects the active mode: if the bodies are separated, the normal force is zero; if a positive normal force is active, the gap is zero. Together with the gap and force inequalities, this produces a nonsmooth switch between separation and sustained contact. Related time-stepping or impact formulations add velocity- or impulse-level conditions to handle impact.
- Gradients through a naive discrete contact event can be discontinuous, inaccurate, or omit the dependence of impact time on the state. Event-aware differentiation, smoothing, or alternative estimators can restore a signal, but the choice changes the model being optimized.
- A small state error near the contact boundary can flip a mode decision and cause two rollouts to diverge rapidly. How rapidly depends on the geometry, timestep, solver, and task; contact-rich prediction should therefore be evaluated with explicit mode and penetration metrics.
- When observations leave the next contact mode ambiguous, a deterministic model trained with squared error targets the conditional mean and can average bouncing and resting into a state that matches neither mode. A multimodal predictive distribution or an explicit mode variable can represent that uncertainty instead.
Friction
Coulomb friction constrains the tangential force to lie inside a friction cone whose radius is the normal force times a coefficient:
where:
- : the tangential force vector at the contact, lying in the local surface plane
- : the normal force magnitude, the pressing force perpendicular to the surface
- : the coefficient of friction, a property of the material pair that sets the cone's radius
Static contact sticks when the tangential force or impulse required to maintain zero relative tangential velocity lies inside the static friction set. If sticking would require leaving that set, a sliding law applies friction opposite the relative tangential motion, usually with a kinetic coefficient. Many engines approximate friction cones with polyhedra and solve a coupled constrained problem across active contacts, while others use cone, penalty, or compliant formulations. A learned contact model must likewise choose what its temporal discretization represents. At finite resolution, force targets can smear short impacts, while impulse targets align naturally with short velocity changes. Either representation can handle sustained contact when paired with suitable labels and a solver.
Impulses and Impacts
In the ideal rigid-body approximation, an impact is represented as instantaneous when its finite physical contact duration is unresolved by the timestep. For a frictionless point mass striking a stationary plane, an impulse update gives , where:
- and : the velocity immediately before and immediately after the impact
- : the unit contact normal, pointing out of the surface
- : the component of the pre-impact velocity along the normal, that is,
- : the Newton coefficient of restitution, the ratio of post-impact separating normal speed to pre-impact approaching normal speed
Under those stationary-plane, frictionless assumptions, the update reverses the normal component and scales it to while leaving the tangential component unchanged. The normal-direction kinetic-energy loss is the fraction . General two-body impact requires contact-point relative velocity, effective mass and inertia, and any tangential impulse. A learned model can predict an impact event and restitution parameter instead of resolving the short force profile, provided those assumptions match its setting.
Conservation Laws and Symmetries
Conservation laws are powerful structural priors. For systems described by a variational principle, Noether's theorem links differentiable continuous symmetries of the action, including invariance up to an appropriate boundary term, to quantities conserved along solutions.
For each qualifying continuous variational symmetry of the action, there is a corresponding conserved quantity along solutions:
- Time-translation symmetry (laws do not change over time) implies conservation of energy.
- Space-translation symmetry implies conservation of linear momentum.
- Rotation symmetry implies conservation of angular momentum.
Persistent violation is evidence that the learned-and-discretized model does not preserve the corresponding invariant under the audited conditions. The cause may be model mismatch, numerical integration, measurement error, or an open subsystem. A rocket alone exchanges momentum with its exhaust, and friction transfers resolved mechanical energy into internal energy; the corresponding closed-system totals still obey their conservation laws.
Noether's theorem turns conservation from a checklist into a diagnostic. If a model predicts spontaneous acceleration for an isolated, force-free system, it may have encoded position dependence with no physical source or omitted an interaction with the environment. For an open subsystem, however, external fields and unmodeled forces can change momentum without implying a broken symmetry of the full system. We will use energy as one evaluation tool in the worked example. Drift can come from the learned vector field, the integrator, finite step size, external forcing, or evaluating a physical energy different from the scalar the model conserves. Noether identifies the symmetry–conservation relationship; diagnosis still requires separating those sources.
Symplectic Integration: Respecting Structure in Time
There is a subtlety that trips up even careful modelers. Energy conservation is a property of an autonomous conservative system's exact flow, while numerical integration discretizes time. Explicit Euler generally does not preserve the Hamiltonian and produces secular energy growth for the harmonic oscillator and many pendulum trajectories, although the sign of a one-step energy error is not universally positive. Symplectic integrators such as semi-implicit Euler and velocity Verlet preserve the symplectic form. For sufficiently smooth autonomous Hamiltonians, small fixed steps, and bounded trajectories, backward-error analysis explains why their numerical energy often stays close to a nearby shadow Hamiltonian for very long times. Symplectic methods are therefore widely used for long-term Hamiltonian simulation, while implicit, adaptive, and other nonsymplectic schemes remain appropriate in different regimes.
The lesson for world models is architectural as well as numerical. An explicit-Euler-like update generally does not preserve Hamiltonian structure. A valid symplectic map applied to a suitable Hamiltonian with a stable step size can instead provide long-time near-conservation behavior. Update structure does not rescue a wrong vector field, and bounded energy does not imply small state error, but it removes one identifiable source of secular drift.
Equivariance: Symmetries in the Network Itself
Symmetries can also be built into the function approximator. An equivariant network commutes with a symmetry group: transforming the input transforms the output in the corresponding way. For gravity-aware dynamics, coordinate rotations must transform the geometry, vector features, outputs, and gravity vector together; rotating the bodies while holding gravity fixed is a physically different problem. Momentum-conserving interaction networks, rotation-equivariant point-cloud models, and SE(3)-aware dynamics networks build on this idea. For an isolated pairwise model, equal-and-opposite learned impulses can enforce total-momentum conservation by construction, provided external forces and non-pairwise interactions are handled separately.
Physics Priors and Constraint Enforcement
We now assemble the toolbox. Given a learned dynamics model, there is a spectrum of ways to make it respect physics, differing in how strongly the constraint binds and how much of the model is hand-designed. The spectrum is best organized around a single question: is physics a preference you trade off against data fit, or a guarantee you enforce unconditionally? Each position along the spectrum answers that question differently, and each comes with its own failure modes.
The Spectrum from Soft to Hard
At one end, physics is a preference; at the other, it is a guarantee.
- Soft penalties: Add physics violations to the training loss. A typical loss looks like . The weights balance data fit against the selected residuals: too little weight may leave large violations, while too much can distort the fit when the assumed law, state, or numerical tolerance is wrong. Soft penalties are broadly applicable to partial and approximate laws, but they do not guarantee satisfaction. PINNs use this idea by penalizing a governing-equation residual at collocation points.
- Structured architectures: Restrict the function class so that a stated property holds by construction. An autonomous HNN conserves its learned under exact unforced continuous flow; a regular autonomous LNN has an analogous learned energy law. Neither statement makes the learned scalar identical to physical energy, and numerical integration adds error. The price is commitment: an unforced canonical Hamiltonian architecture cannot represent friction without an added dissipative or forcing term.
- Hard projection: Let the network predict freely, then project the prediction onto a physically admissible set after each step: move positions out of penetration, project contact impulses into the friction cone, renormalize quaternions, or enforce joint limits. The selected feasibility condition can be exact up to solver tolerance, but gradients and interactions among constraints need care.
- Hybrid residual models: Use a simulator as a backbone and learn a correction, . The simulator enforces selected discrete constraints to solver tolerance; the residual can represent identifiable, sufficiently excited unmodeled effects. For passive dissipation, a precise construction is , where and , giving . This is useful when the backbone is accurate enough and the residual effects are observable, but it is not a universal best choice.
- Differentiable simulation: Write the simulator so its computation graph is differentiable, then train through it end to end. This preserves the simulator's specified equations while adapting parameters to data, subject to discretization error and model mismatch. Event-aware derivatives and explicit approximations address particular contact-gradient failures, but changing normals, simultaneous contacts, solver branches, and stiffness still require validation.
Choosing Where on the Spectrum to Sit
The right choice depends on what you know and what you can guarantee. Some guidelines:
- If an isolated autonomous conservative system has a known invariant, architectural enforcement can guarantee that selected property under its continuous-time and solver assumptions. A soft penalty supplies no such guarantee and introduces a tuning tradeoff, though hard enforcement can also be inappropriate when the state, law, or boundary is misspecified.
- In a passive dissipative regime, combine a conservative core with a positive-semidefinite dissipation operator or another parameterization that makes the identified energy rate nonpositive. This constrains that particular learned energy; it does not prevent penetration, momentum error, or legitimate energy input from actuation.
- If a constraint is safety-critical (no penetration, joint limits, table height), a finite soft penalty provides no worst-case feasibility guarantee. Prefer independently verified hard projection or constrained optimization when the constraint must hold, and test the projection itself under distribution shift. We will meet this again in Part XII on reliable world models.
- If the physics is uncertain in form, not just parameters, keep the soft end of the spectrum flexible and let data decide. Enforcing a guessed structure harder than your confidence justifies converts your uncertainty into systematic model error.
A useful mental model is to ask what each component guarantees. Architectural priors enforce only their encoded property under stated assumptions; learned components cover effects supported by the data. Revisit the partition as evidence accumulates. A systematic residual is evidence to investigate missing physics, state estimation, calibration, or data bias before deciding that the architecture itself must change.
Constraint Enforcement in Latent World Models
One caveat deserves emphasis. The directly geometric operations above, such as checking penetration and projecting velocities, assume that the model exposes physically interpretable quantities. Modern latent world models from Part V operate in abstract spaces where "penetration" has no direct meaning unless the state is decoded to geometry. Two representative responses are:
- Structured latents: Design the latent state to contain physical quantities, as in the object-centric models of Part III, Chapter 5, where each latent slot carries an object's pose. Physics constraints then apply to the decoded, physical readout.
- Latent geometric constraints: Design compatible, typically even-dimensional latent coordinates and impose a Hamiltonian vector field or symplectic map. This preserves the encoded latent structure under the relevant continuous flow or discrete update. Without an identified readout, the learned invariant need not equal a physical conservation law, and symplecticity alone does not guarantee bounded drift of arbitrary latent coordinates or physical predictions.
The first keeps constraints checkable and interpretable; the second applies to abstract latents deliberately designed with compatible geometry. Other hybrids combine equivariant encoders, probabilistic constraints, or learned simulators. If a safety filter must verify "the cup is above the table," the state must expose a readout the filter can check.
Worked Example: Two Models of a Pendulum
Let us make the distinction between structural guarantees and predictive accuracy concrete with an undamped, unit-mass pendulum. Its state is , angle and angular velocity, with exact dynamics
where is gravitational acceleration and is pendulum length. The first equation is kinematic; the second contains the nonlinear restoring term . For small swings, , while larger swings test behavior beyond that local linearization. With mass fixed to , the physical energy is , measured relative to the lowest point, and the exact unforced flow conserves it. We will fit two models to one simulated trajectory:
- A naive MLP that maps to with no structure at all.
- A Hamiltonian model that learns a scalar Hamiltonian candidate and derives its dynamics from antisymmetric autodiff gradients, with for unit mass.
This is a controlled illustration, not a general benchmark. Both models train on the exact instantaneous vector field at the same states, and we report the losses rather than assuming equal fit. The Hamiltonian architecture guarantees conservation of its learned under exact unforced continuous flow; it does not guarantee that equals or that the predicted trajectory is accurate. The rollout lets us inspect those properties separately for one seed and one held-out initial condition.
We will also demonstrate a simplified bouncing-ball projection: an unconstrained baseline passes through the floor, while the projected update clamps penetration and applies restitution. This enforces unilateral feasibility in the toy discretization but does not solve the full complementarity problem.
Code Implementation
First the hidden setup cell, which locates the shared plotting style and seeds all randomness for the book's figures.
Simulating the Ground-Truth Pendulum
We sample states from an RK4 trajectory that starts at radians, where the small-angle approximation is inadequate. At each sampled state, the training target is the analytic instantaneous derivative from the pendulum equation. Using the exact vector field avoids asking a continuous-time Hamiltonian model to reproduce a finite-step forward-difference target that need not itself be Hamiltonian.
import numpy as np
G = 9.81
L = 1.0
def pendulum_deriv(x):
theta, omega = x
return np.array([omega, -(G / L) * np.sin(theta)])
def rk4_step(f, x, dt):
k1 = f(x)
k2 = f(x + 0.5 * dt * k1)
k3 = f(x + 0.5 * dt * k2)
k4 = f(x + dt * k3)
return x + (dt / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4)
dt = 0.05
n_steps = 600 # 30 seconds of data
x = np.array([2.0, 0.0])
traj = [x.copy()]
for _ in range(n_steps):
x = rk4_step(pendulum_deriv, x, dt)
traj.append(x.copy())
traj = np.array(traj)From this trajectory we build supervised pairs using the analytic derivative at each sampled . Rollout behavior is evaluated separately on an initial condition outside the training trajectory's angle range.
X = traj[:-1]
dX = np.array([pendulum_deriv(x) for x in X])
print(
f"Training pairs: {X.shape[0]}, dt = {dt} s, horizon = {n_steps * dt:.0f} s"
)
print(f"Angle range: [{traj[:, 0].min():.2f}, {traj[:, 0].max():.2f}] rad")Training the Naive Model
The naive model is a plain multilayer perceptron from state to derivative. Nothing in its architecture requires or energy conservation. The finite network has ample capacity to approximate the field over the bounded training region, but the loss constrains it only at the sampled states.
import torch
import torch.nn as nn
torch.manual_seed(0)
X_t = torch.tensor(X, dtype=torch.float32)
dX_t = torch.tensor(dX, dtype=torch.float32)
naive = nn.Sequential(
nn.Linear(2, 64),
nn.Tanh(),
nn.Linear(64, 64),
nn.Tanh(),
nn.Linear(64, 2),
)
opt = torch.optim.Adam(naive.parameters(), lr=1e-3)
for step in range(3000):
opt.zero_grad()
loss = ((naive(X_t) - dX_t) ** 2).mean()
loss.backward()
opt.step()
print(f"Naive one-step MSE: {loss.item():.2e}")Training the Hamiltonian Model
The Hamiltonian model learns a scalar Hamiltonian candidate from the same data. Because mass and length are both one, the conjugate momentum equals numerically. Its derivatives come from autodiff: and . The implementation detaches the inputs and re-wraps them as leaf tensors so that autograd.grad differentiates the scalar with respect to the state. For every setting of the weights, the antisymmetric pairing conserves the learned autonomous under exact continuous flow. It does not guarantee agreement with the analytic pendulum field or exact conservation by a discrete integrator.
class HamiltonianModel(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(2, 64),
nn.Tanh(),
nn.Linear(64, 64),
nn.Tanh(),
nn.Linear(64, 1),
)
def h(self, x):
return self.net(x).squeeze(-1)
def deriv(self, x):
# x: (batch, 2) state [theta, p]. Returns time derivative.
xin = x.detach().clone().requires_grad_(True)
H = self.h(xin).sum()
(dH,) = torch.autograd.grad(H, xin, create_graph=True)
return torch.stack([dH[:, 1], -dH[:, 0]], dim=-1)
hnn = HamiltonianModel()
opt = torch.optim.Adam(hnn.parameters(), lr=1e-3)
for step in range(3000):
opt.zero_grad()
loss = ((hnn.deriv(X_t) - dX_t) ** 2).mean()
loss.backward()
opt.step()
print(f"Hamiltonian one-step MSE: {loss.item():.2e}")For seed 0, the final derivative MSE is approximately for the MLP and for the Hamiltonian model. Both are small on the sampled training states, with the Hamiltonian loss about 2.7 times lower in this run. A phase portrait shows what each fitted field asserts over a wider grid; Hamiltonian circulation is structural, while fidelity to the true arrows remains empirical.
import numpy as np
import torch
## Evaluation grid: a regular 21x21 grid over the phase plane, fixed by design
## (no randomness, no seed dependence). Range spans the training amplitude and
## the held-out rollout amplitude.
theta_grid = np.linspace(-np.pi, np.pi, 21)
omega_grid = np.linspace(-6.0, 6.0, 21)
Theta_grid, Omega_grid = np.meshgrid(theta_grid, omega_grid)
grid_pts = np.stack([Theta_grid.ravel(), Omega_grid.ravel()], axis=1)
## True derivative field on the grid, computed analytically
true_field = np.array([pendulum_deriv(p) for p in grid_pts])
## Learned derivative fields on the grid. The direct network needs no gradient
## tracking, while the Hamiltonian field is itself defined by an input gradient.
grid_t = torch.tensor(grid_pts, dtype=torch.float32)
with torch.no_grad():
naive_field = naive(grid_t).numpy()
with torch.enable_grad():
hnn_field = hnn.deriv(grid_t).detach().numpy()
grid_rmse_naive = np.sqrt(np.mean((naive_field - true_field) ** 2))
grid_rmse_hnn = np.sqrt(np.mean((hnn_field - true_field) ** 2))
print(
f"Grid RMSE naive: {grid_rmse_naive:.2f} Hamiltonian: {grid_rmse_hnn:.2f}"
)
Rolling Out and Measuring Energy Drift
We roll both models out from radians for 20 seconds, feeding each prediction back as the next input. This angle lies outside the training trajectory's range of about radians. We record state error, the analytic physical energy of each predicted state, and the Hamiltonian model's learned scalar . The exact pendulum conserves ; the architecture's continuous-time guarantee applies to instead.
def pendulum_energy(x):
theta, omega = x[..., 0], x[..., 1]
return 0.5 * (L**2) * omega**2 + G * L * (1.0 - np.cos(theta))
def rollout_torch(deriv_fn, x0, dt, steps):
x = torch.tensor(x0, dtype=torch.float32).unsqueeze(0)
out = [x.detach().numpy().copy()]
for _ in range(steps):
x = rk4_step(
deriv_fn, x, dt
) # same RK4 rule for both models; only the learned field differs
out.append(x.detach().numpy().copy())
return np.concatenate(out, axis=0)
def rollout_naive(x0, dt, steps):
x = torch.tensor(x0, dtype=torch.float32).unsqueeze(0)
out = [x.detach().numpy().copy()]
with torch.no_grad():
for _ in range(steps):
x = rk4_step(naive, x, dt)
out.append(x.detach().numpy().copy())
return np.concatenate(out, axis=0)
x0_test = np.array([2.5, 0.0])
roll_steps = 400 # 20 seconds
## Ground truth via RK4 at the same dt
gt = [x0_test.copy()]
x = x0_test.copy()
for _ in range(roll_steps):
x = rk4_step(pendulum_deriv, x, dt)
gt.append(x.copy())
gt = np.array(gt)
roll_naive = rollout_naive(x0_test, dt, roll_steps)
roll_hnn = rollout_torch(hnn.deriv, x0_test, dt, roll_steps)
times = np.arange(roll_steps + 1) * dt
err_naive = np.linalg.norm(roll_naive - gt, axis=1)
err_hnn = np.linalg.norm(roll_hnn - gt, axis=1)
E0 = pendulum_energy(x0_test)
E_naive = pendulum_energy(roll_naive) / E0
E_hnn = pendulum_energy(roll_hnn) / E0
with torch.no_grad():
learned_H = hnn.h(torch.tensor(roll_hnn, dtype=torch.float32)).numpy()
learned_H_drift = learned_H - learned_H[0]
print(
f"Final error @ {times[-1]:.0f}s naive: {err_naive[-1]:.2f} Hamiltonian: {err_hnn[-1]:.2f}"
)
print(
f"Final energy ratio naive: {E_naive[-1]:.3f} Hamiltonian: {E_hnn[-1]:.3f}"
)
print(f"Max |learned H drift|: {np.abs(learned_H_drift).max():.2e}")Both learned models use the same RK4 rule, which controls one source of variation but does not remove integration error or the different approximation errors in their vector fields. RK4 is nonsymplectic. In this seeded run, the HNN's learned scalar changes by at most about , while the analytic physical-energy ratio on the same trajectory ranges from about 1.000 to 1.035. The distinction is the point: nearly conserving is structural, while agreement with is empirical.
Now consider a minimal hard unilateral constraint. The unconstrained baseline is free fall with no collision handling. The constrained update projects a penetrated position back to and then reflects the normal velocity using a restitution coefficient. It illustrates feasibility plus an impact law; it is not a full complementarity solver because it computes no contact multiplier, impact time, sustained-contact solution, or friction.
def bounce_projected(dt=0.02, steps=200, y0=1.0, e=0.8):
y, v = y0, 0.0
ys = [y]
for _ in range(steps):
v = v - 9.81 * dt
y = y + v * dt
if y < 0.0: # constraint phi(y) = y >= 0 violated
y = 0.0 # projection: eliminate penetration
v = -e * v # impact impulse: reflect with restitution
ys.append(y)
return np.array(ys)
def bounce_unconstrained(dt=0.02, steps=200, y0=1.0):
y, v = y0, 0.0
ys = [y]
for _ in range(steps):
v = v - 9.81 * dt
y = y + v * dt
ys.append(y)
return np.array(ys)
ball_free = bounce_unconstrained()
ball_proj = bounce_projected()
t_ball = np.arange(len(ball_free)) * 0.02
print(
f"Min height, unconstrained: {ball_free.min():.2f} m (penetrates the floor)"
)
print(f"Min height, projected: {ball_proj.min():.3f} m (never below zero)")The position test implements by projecting violations back onto the feasible set, and the velocity reflection adds a restitution update. This code enforces nonpenetration exactly at the sampled states. A generic smooth predictor can approximate the bounce map, but it provides no exact nonpenetration guarantee unless the constraint is added explicitly.
Visualizing the Results
Both figures are built entirely from the arrays computed above. The first compares rollout error and energy drift for the two pendulum models; the second shows the constraint projection keeping the ball on the correct side of the floor.



The panels measure different properties. On the sampled training states, both derivative losses are small and the Hamiltonian loss is lower for this seed. On the held-out rollout, the HNN also has the lower 20-second endpoint error, 4.92 rather than 7.98, while neither trajectory stays close to the ground truth throughout. The energy panel shows a clearer structural contrast: the MLP trajectory gains about 40% physical energy, whereas the HNN trajectory remains within roughly 3.5% of its initial physical energy and its learned changes by only about . This one seed is an illustration, not evidence that Hamiltonian models generally win. It shows instead how to audit separate questions: Was the local field fitted? Is the learned invariant conserved? Does that invariant match the physical quantity of interest? Is the state trajectory accurate enough for the intended horizon?
Limitations and Impact
Physics priors are only as good as the physics assumed. An autonomous unforced conservative architecture preserves its learned invariant under exact continuous flow even when that makes it a poor model of driven or dissipative data. A rigid-body backbone with the wrong friction model can mispredict a lubricated joint or slipping tire. An additive residual may correct some backbone mismatch, but limited capacity or structural constraints may prevent the repair, while a flexible residual can hide a missing mechanism. Treat each prior as a falsifiable claim. Residual tests that find no detectable bias, autocorrelation, state dependence, or miscalibration are evidence, not proof, that the backbone is adequate.
Hard contact remains a major challenge because complementarity and event timing can make gradients discontinuous or inaccurate. Learned contact models can also face sparse coverage of short impact events and new contact geometries. Event-aware differentiation, compliant approximations, interactive data collection, and simulator-based training address different parts of the problem; none removes the need to evaluate contact-rich rollouts directly. We will revisit structured simulators and differentiable physics in Part IV, Chapter 4.
There is also a subtler tension between interpretable physical state and flexible learned representation. Direct constraints want positions, velocities, and contact geometry; latent models may discover coordinates with no immediate physical meaning. One active direction builds physics into a relational skeleton of objects, contacts, and interactions while leaving perceptual details learned. This connects to compositionality and systematic generalization in Part IV, Chapter 6, but its value remains an empirical design choice rather than a universal prescription.
Physics-structured learning has produced methods that enforce selected invariants, fit physical parameters through differentiable simulators, and improve some long-horizon benchmarks when the assumed structure matches the system. Hamiltonian and Lagrangian networks learn scalar functions from data while enforcing a designer-chosen variational form; they do not discover arbitrary symmetries automatically. These constraints do not calibrate uncertainty under shift, and a misspecified prior can create confident systematic error. For a downstream planner, the useful guarantee is therefore only the property enforced and independently tested. A correct, applicable conservation law can be an unusually strong inductive bias, but it does not replace data fit, uncertainty estimation, or model-mismatch checks.
Summary
Physical dynamics and constraints provide strong, testable priors for embodied world models. The key takeaways:
- Rigid-body dynamics reduces configuration to generalized coordinates. For regular conservative systems, Lagrangian or Hamiltonian formulations derive the dynamics from a scalar function; identifying the Hamiltonian with physical total energy requires the usual autonomous natural-system assumptions.
- Deformable media require many degrees of freedom. Continuum-based schemes such as FEM and MPM and discrete schemes such as mass–spring systems and PBD make different commitments about material behavior.
- Contact and friction introduce unilateral constraints, impulses, and stick–slip mode changes. A smooth predictor may approximate them, but exact nonpenetration or friction feasibility requires explicit enforcement or a verified solver.
- Noether's theorem links qualifying continuous variational symmetries to conserved quantities. Symplectic updates preserve a two-form, while equivariant architectures enforce one selected group action; neither automatically preserves every physical invariant.
- Enforcement is a spectrum: soft penalties discourage violations, structured architectures enforce specified properties, projections impose selected feasibility conditions to solver tolerance, and hybrid residual models combine a backbone with learnable mismatch. Each guarantee is conditional on the encoded law, state, and numerical method.
The pendulum experiment gives a narrower lesson: structural conservation and predictive accuracy must be checked separately. The HNN nearly conserves its learned scalar and has the lower 20-second endpoint error on this held-out rollout after both models are trained on the same analytic vector field, but a single seed cannot establish a general architecture ranking. Controlled mechanical models can represent how actions enter the dynamics; passive observational data may not identify those intervention effects without additional assumptions. The next chapter develops causal models for making that distinction explicit.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about physical dynamics and constraints in world models.
Reference
Citation details
Cite or share this article.
Continue with the full handbook
This chapter is part of World Models Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.
Explore World Models HandbookStay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.

Comments
No comments yet. Be the first to share your thoughts!