Back to all essays
Machine Learning · Physics · PIML

How Physics Shows Up in Machine Learning

A plain-language guide to SGD noise, states, flows, energy landscapes, constraints, symmetries, conservation laws, and physics-informed machine learning.

Physics and machine learning meet in a few different ways. Sometimes the model is literally learning a physical system, like weather, fluids, molecules, or a pendulum. Sometimes physics is used as a source of structure: conservation laws, symmetries, differential equations, energy, flow, and stable states. Sometimes physics is only a metaphor that helps us reason about a high dimensional model.

Those three cases are easy to mix up, so this post keeps them separate.

The short version is this: physics helps machine learning by saying, "not every function is equally plausible." A pure data model can fit many patterns. A physics-guided model is pushed toward patterns that obey a law, preserve a quantity, move smoothly through time, or respect a symmetry.

Step 1: machine learning starts too open

A neural network is a flexible function. Give it enough parameters and data, and it can approximate many relationships. That flexibility is useful, but it is also the problem. If the data is noisy, sparse, or outside the training range, there are many curves that fit what you have seen and disagree everywhere else.

Physics gives the model a smaller search space.

Instead of asking only, "what curve fits the points?", we can ask, "what curve fits the points and also behaves like a physical system?" That second question is much more constrained.

This is one reason physics-informed methods can be valuable when data is expensive. In many physical domains, you do not have billions of examples. You have a few sensors, a simulator, or an equation that is partly known.

Step 2: training is drift plus shake

The clean picture of learning is a ball rolling smoothly downhill. That picture is useful, but it hides the part that makes modern training work.

Full-batch gradient descent asks every training example where downhill is. That is expensive. Stochastic gradient descent uses a small mini-batch instead. The mini-batch direction is cheaper and usually points roughly downhill, but it is also noisy. The model lurches, not glides.

That noise is not only a mistake. Early in training the average downhill pull is large compared with the noise, so the model improves quickly. Later, once the average pull has shrunk near a minimum, the noise dominates the updates and the parameters jitter around the bottom instead of settling. Whether that jitter is useful is a separate, empirical question: in deep networks it is argued to bias training toward flatter minima that generalize better, but in a simple convex problem it only sets a floor above the minimum, as the figure below shows.

Drift plus shake: what SGD does near a minimum

Every number here comes from running SGD on a small regression problem. Change batch size, learning rate and schedule, and watch the blue path, the cloud of 40 independent end points and the loss.

Toy model · exact gradients · computed live

Batch size 4, learning rate 0.1, 300 steps, momentum 0, constant schedule. SGD ends with excess loss 0.015; full-batch gradient descent ends with 1.8e−11. The 40 end points lie at an RMS distance 0.148 from the optimum; the small-step theory predicts 0.131.

Batch size (256 = full batch)

Learning-rate schedule

Stability limit for exact gradients: 0.5

Draws different mini-batches.

More settings: momentum, number of steps

Heavy-ball momentum; widens the stability limit.

View

40 runs’ end points

  • SGD path
  • Full-batch GD (same η)
  • End points of 40 runs
  • Predicted 2σ ball

Hairline ellipses are contours of the loss above its minimum (each 4× the previous, labelled on two).

  • SGD (the run drawn above)
  • Full-batch GD
  • Theory: expected loss
SGD final excess loss
0.015
Full-batch GD final
1.8e−11
Spread: measured
0.148
Spread: predicted
0.131
Rate ÷ batch size
0.025

Spread is the RMS distance from the 40 end points to the optimum. “Predicted” propagates the mini-batch gradient covariance at the optimum through the update, step by step. In the small-step limit the stationary covariance S solves HS + SH = (η/B)C, with H the loss curvature and C the per-example gradient covariance. It applies for β = 0 with a constant or decaying η. Runs with a small η × steps have not finished converging, and the prediction includes the distance left to travel. Loss values below 10⁻⁶ are drawn on the bottom line.

View data as a table
Excess loss L minus L_min at selected steps
StepFull-batch GDSGD (drawn run)Mean of 40 runsTheory
017.817.817.817.8
250.1040.0530.1540.125
500.0140.0380.0340.034
750.00180.0190.0250.023
1002.3e−40.0210.0150.021
1253.0e−52.2e−40.0260.021
1503.9e−60.00260.0240.021
1755.0e−70.0650.0220.021
2006.5e−80.00920.0190.021
2258.4e−90.0280.0280.021
2501.1e−90.00560.0260.021
2751.4e−105.1e−40.0230.021
3001.8e−110.0150.0300.021
Linear regression with two parameters on 256 synthetic examples, so the loss is an exact quadratic and the contours are exact ellipses. Because it is convex, there is one minimum; real deep-network landscapes are non-convex, so what carries over is the drift-plus-noise decomposition, not this geometry. “Predicted” uses the small-step stationary covariance of SGD (Mandt et al. 2017; Smith & Le 2018) and holds for β = 0 only. Mini-batches are drawn without replacement at every step; the 40 runs use different seeds.

This is where the physics language becomes more than decoration. The gradient acts like drift or gravity. Mini-batch noise acts like heat, with a temperature that scales roughly like the learning rate divided by the batch size: halve the batch and you need to halve the learning rate to keep the same noise level. Decaying the learning rate lowers the temperature, which is why practical schedules end with a small rate. Momentum acts roughly like a larger effective learning rate, so it raises the noise rather than damping it. The analogy has limits: SGD noise is not isotropic thermal noise. Its shape is set by how the per-example gradients disagree, so it is stretched or squeezed along different directions of the loss.

Step 3: a state is the system right now

Physics often starts with a state. For a pendulum, the state might be angle and velocity. For a fluid, it might be velocity, pressure, and density at many locations. For a model conversation, the "state" is not physical, but we can still loosely talk about the current internal context or representation.

The important move is this: once you describe the state, you can ask how it changes.

That creates a trajectory. The system is here now, then here next, then here after that. In physics, that trajectory may be governed by differential equations. In machine learning, a model can learn either the state itself, the next state, or the rule that moves the state forward.

Neural ordinary differential equations are one clean example. Instead of viewing a network as a fixed stack of discrete layers, they learn a continuous change rule and use an ODE solver to move the hidden state forward.

Step 4: flow means "how the state moves"

A flow field tells you the direction a system wants to move at each point. Put a particle here, and the arrows tell you where it goes next.

This is a useful mental model for machine learning:

  • In a dynamical-system model, the flow may be literal.
  • In a neural ODE, the learned derivative is the flow.
  • In a diffusion model, generation can be described as a learned path from noise toward data.
  • In an LLM, "flow" is only an analogy: each token changes the context and therefore changes the next probability distribution.

The distinction matters. A language model is not automatically simulating physics. But physics gives us a vocabulary for thinking about states, directions, stability, and change.

Step 5: energy means "how compatible is this state?"

An energy landscape assigns a score to possible states. Lower energy usually means the state is more compatible with what the system wants. Higher energy means the state is less compatible.

This is not just metaphor in all of ML. Hopfield networks, for example, can be described as systems that settle into stable low-energy memories. Energy-based models also explicitly learn an energy function where observed or plausible configurations should have lower energy than implausible ones.

The marble-in-a-bowl picture is useful:

  • The marble's position is the current state.
  • A valley is a stable outcome.
  • A basin is the region that falls into that outcome.
  • A barrier is what separates one basin from another.

The important idea is not only "go downhill." It is "go downhill inside the world you are allowed to move through." A reward-only learner may discover a shortcut to a low-loss state. If the shortcut breaks physics, it is not a real solution. Adding physics changes the shape of the search space: the same basin can still be the goal, but the path toward it bends around impossible or expensive states.

For LLMs, be careful. During normal generation, the model is not training its weights and literally rolling downhill into a new minimum. The weights are fixed. But the analogy is still helpful if "low energy" means "more likely or more compatible with the current context."

There is one place where the energy language is exact. A language model's softmax is a Boltzmann distribution: p(token) ∝ exp(−E / T), with energy E equal to the negative score (logit) and T the sampling temperature. Lowering T concentrates probability on the lowest-energy token and raising T spreads it out; Prompt Trajectories in Latent Space shows this with real scores.

That is why initial context matters. A prompt can place the model near one answer family instead of another. A skill, system prompt, example, or long conversation can narrow the likely region even more.

Step 6: constraints make bad answers expensive

The most direct way to combine physics and ML is to add a constraint. The model still learns from data, but it is penalized when it violates a known rule.

For example, imagine fitting a curve through noisy sensor readings. A data-only model may chase every noisy wiggle, and says nothing reliable between or beyond the sensors. A physics-guided model can be told, "fit the data, but also stay close to the differential equation, conservation law, or simulator behavior we expect."

What does adding a physical law to the loss change?

Fit the same noisy sensors twice: once by data alone, once with a penalty for violating the equation of motion. Then see what happens where there are no sensors.

Linear surrogate · closed-form optimum · computed live

With the correct law at weight 21.54, error outside the sensor window is 0.0092 for the physics-informed fit against 0.467 for data only. Inside the window: 0.022 against 0.162. Residual of the true law: 0.0027 against 1.46.

Loss, as computed here

Loss = data mismatch + λ × law violation. Symbols: u(t) is the model curve, yi the sensor reading at time ti, and c, k the damping and stiffness in the law u″ + c·u′ + k·u = 0.

Log scale, 1e-5 to 1000. Far left = 0.

Law used in the penalty

Penalises u″ + 0.4 u′ + 4.0 u. This is exactly the law that generated the data.

  • Sensors (noisy)
  • True solution
  • Data only (λ = 0)
  • Physics-informed
  • No sensors here
View data as a table
True solution, data-only fit and physics-informed fit every 0.5 seconds
t (s)True uData onlyPhysics-informed
011.0431.001
0.50.5690.4190.602
1-0.258-0.196-0.226
1.5-0.72-0.745-0.715
2-0.498-0.53-0.52
2.50.0990.0450.073
30.5050.0970.497
3.50.4170.5720.43
4-0.0031.0620.016
4.5-0.3440.718-0.336
5-0.3370.213-0.344
5.5-0.050.023-0.064
60.226-0.0020.219
6.50.264-0.0010.268
70.075-00.085
7.5-0.142-0-0.136
8-0.202-0-0.203
8.5-0.082-0-0.089
90.084-00.078
9.50.15-00.15
100.079-00.084
Error inside 0–3.5 s
Data only0.162Physics-informed0.022
Error outside (3.5–10 s)
Data only0.467Physics-informed0.0092
Law residual (true law)
Data only1.46Physics-informed0.0027

Errors are root-mean-square gaps to the true solution on a 0.05 s grid. Law residual is the RMS of u″ + 0.4u′ + 4u, always judged by the true law, whichever law was used in training.

Error outside the window, as the weight grows

Same sensors, every law, 25 weights. Too small does nothing (the curve sits at the orange level); a correct law drives the error down and keeps it there; a wrong law stops improving and stays biased. The dot marks the current setting. Wrong laws can still beat a wild data-only curve outside the window, but they cost accuracy inside it. Try n = 24 and noise 0: the data alone is then good enough that the wrong laws are plainly worse.

View weight sweep as a table
Error outside the sensor window for each penalty law and physics weight
λCorrect lawWrong k=6Wrong c=1.2
1e-50.4560.2890.390
2.2e-50.4440.2750.368
4.6e-50.4130.2500.339
1e-40.3620.2130.301
2.2e-40.2930.1720.258
4.6e-40.2180.1450.219
1e-30.1520.1470.190
2.2e-30.1020.1670.170
4.6e-30.0650.1890.158
0.010.0400.2090.152
0.0220.0240.2280.150
0.0460.0160.2480.152
0.10.0120.2720.155
0.2150.00960.2980.159
0.4640.00830.3220.163
10.00820.3390.168
2.150.00860.3490.171
4.640.00900.3540.172
100.00920.3570.173
21.540.00920.3580.174
46.420.00920.3580.174
1000.00910.3580.174
2150.00880.3570.174
4640.00840.3550.174
10000.00780.3520.174
Toy model. A damped oscillator (u″ + 0.4u′ + 4u = 0, u(0) = 1, u′(0) = 0) is observed by noisy sensors only for the first 3.5 s. Both curves are linear combinations of 36 Gaussian bumps whose loss minimum is solved exactly, so this isolates the effect of the loss term; it is not a neural network and says nothing about training difficulty. Sensor times and noise come from a seeded generator.

Physics-informed neural networks are a concrete version of this idea. They train neural networks to solve supervised tasks while respecting physical laws, often written as partial differential equations. The loss is no longer only "match the observed data." It can also include "do not violate this equation at these points in space and time."

That does not make the method magic. The law enters as a soft penalty, not a guarantee, so the fit is pulled toward solutions of the equation rather than forced onto them. If the equation is wrong, incomplete, or too expensive to enforce, the model can still fail, and a wrong law with a heavy weight can override good data. Real physics-informed networks are also often hard to optimize because the data and equation terms compete. But it changes the game: the model is no longer free to fit any pattern that happens to match the data, and the help is largest where there are no sensors, because the law still constrains the shape there.

Step 7: conservation laws reduce drift

Some physical systems preserve quantities. Energy, momentum, mass, or charge may stay constant under the right assumptions.

Ordinary neural networks do not automatically know that. A model trained on a pendulum may look right for a short time and then slowly invent or destroy energy. That kind of drift is a warning sign: the model learned a pattern, but not the structure behind the pattern.

Hamiltonian neural networks attack this by building Hamiltonian mechanics into the model. The network learns a single energy-like function H(q, p) and derives the motion from it, so H itself is conserved along the learned flow by construction. That is slightly weaker than conserving the true energy: the conserved quantity is the learned H, which is close to the true energy only if it was learned well, and numerical integration can still add drift. The goal is dynamics that respect a conservation law instead of merely matching the next few examples.

The broader lesson is simple: if a quantity should be conserved, encode that fact somehow. Put it in the architecture, the loss, the data generation process, or the simulator loop.

Step 8: symmetries tell the model what should not matter

Physics is full of symmetries. A law may not care where an object is translated. It may not care how the coordinate system is rotated. It may care about relative distances but not absolute labels.

Machine learning can use the same idea. If a task has a symmetry, the model should not need to relearn the same pattern in every possible orientation or position. Convolutional networks exploit translation structure in images. Group equivariant networks generalize that idea to transformations like rotations and reflections.

This is another way physics helps: it tells the model which differences are real and which are just coordinate choices.

Step 9: simulators can teach or correct models

Many physical domains already have simulators. They may be slow, imperfect, or expensive, but they contain knowledge.

Machine learning can use simulators in several ways:

  • Generate training data where real measurements are scarce.
  • Learn a fast surrogate that approximates a slow simulation.
  • Compare model predictions against simulated rollouts.
  • Use simulation inside reinforcement learning or planning.
  • Correct a data-driven model when it drifts into physically impossible states.

The practical pattern is hybrid: let data handle what the law does not capture, and let the law or simulator keep the model from making physically absurd moves.

Step 10: physics in reinforcement learning

Reinforcement learning is a good place to see physics as an environment rather than as a penalty. An agent chooses actions, the environment responds, and the agent slowly learns which actions lead to reward.

The simplest story is: "maximize reward." But the environment decides what actions are available, what happens after each action, and which shortcuts are allowed. Physics changes that environment. It does not necessarily change the goal. It changes the routes that are feasible on the way to the goal.

In a physics simulator the physics is simply the environment: a simulated robot cannot ignore gravity, so actions that could never work just fail. What physics-informed reinforcement learning adds is knowledge handed to the learner. That can be a known dynamics model for planning, a reward shaped by energy or stability, limits on the action space such as torque limits and safe sets, reference motions such as the demonstrations in DeepMimic, or an architecture with built-in structure. The aim is sample efficiency and safety, and a smaller gap between the simulation and the real machine.

Physics can enter the RL loop through the simulator, the reward, the action space, or the model architecture. The goal is not to remove learning. The goal is to make the agent spend more of its learning budget on plausible behavior. In the landscape picture, the agent may still settle into a good basin, but physics reshapes which slopes, ridges, and paths actually exist.

Step 11: how this connects back to latent space

Latent space is not automatically a physical space. The axes are learned representations, not meters or seconds. Still, physics gives useful language for thinking about it.

A representation can be thought of as a state. A prompt can move the starting state. A conversation can create a trajectory. A set of likely outputs can look like a basin. A model's uncertainty can look like spread around a path.

The safe version of the analogy is:

  • State: the current representation or context.
  • Flow: how new input changes the next distribution.
  • Basin: a family of likely continuations.
  • Energy: compatibility, plausibility, or negative preference.
  • Noise: sampling variation, numerical variation, or real uncertainty.

This language is useful as long as we remember which parts are literal and which parts are pictures.

Step 12: the practical takeaway

Physics in machine learning is not one technique. It is a toolbox of ways to add structure:

  • States and flows describe change.
  • Energy landscapes describe stable outcomes.
  • Constraints make impossible behavior expensive.
  • Conservation laws reduce drift.
  • Symmetries reduce unnecessary learning.
  • Simulators provide structured experience.

The common theme is inductive bias. Physics tells the model what kinds of solutions should be easier to learn before it sees all possible examples.

That is the reason the physics analogy is powerful for understanding ML. It turns "the model found a pattern" into a more precise question: what state is it in, how does it move, what basins are nearby, what constraints shape the path, and what laws should it respect?

Papers behind the mental model