Stochastic-gradient MCMC: posterior draws from minibatches?
SGLD and SGHMC trade exactness for speed on big data: a minibatch gradient step plus carefully scaled noise. Learn the scaling that makes them aim at the posterior, and why noisy training alone never does.
What runs in CodeSplash
- INF013Stochastic gradient Langevin dynamics (SGLD) Explained here
- INF014Stochastic gradient Hamiltonian Monte Carlo (SGHMC) Explained here
You will be able to
- Write one SGLD update with the right N/B scaling and noise variance
- Explain what SGHMC's friction corrects, and why plain HMC with minibatches fails
- Say why a constant-step run without an accept test stays biased
- Tell posterior sampling from optimizer noise
The big-data problem
ReadEvery Metropolis–Hastings or HMC step evaluates the likelihood (or its gradient) on all rows. For a neural network on a million images, one step is a full pass over the data. Optimizers sidestep that with minibatches: a random batch of rows gives an unbiased, noisy gradient.
Stochastic-gradient MCMC asks whether the same trick can give posterior draws instead of a single point. The answer is "approximately, if you scale everything correctly", and the lesson is mostly about that "if".
SGLD: a gradient step plus noise
ReadStochastic gradient Langevin dynamicsStochastic gradient Langevin dynamicsAdds Gaussian noise of variance ε to each minibatch gradient step on the log posterior, aiming at posterior draws without full-data passes. takes a half-step up the estimated log-posterior gradient and adds Gaussian noise with variance equal to the step size:
Two scalings matter. The batch gradient is multiplied by , so it estimates the full-data likelihood gradient; forget it and the prior silently dominates. The noise standard deviation is , not .
Reference · INF013 · Explained hereStochastic gradient Langevin dynamics (SGLD)Adds appropriately scaled Gaussian noise to minibatch log-posterior gradient updates to approach Langevin posterior sampling.Langevin dynamics with exact scores, before any minibatches: turn annealing off and watch particles miss the small mode.
DExplorable · Score and Langevin sampling
Can you sample from a density knowing only which way is uphill?
What share of the particles will end in the small mode?
Modes at (−a, −a) and (a, a).
Each level steps α = η(1 + σ²).
Start from the score of heavily noised data and sharpen it level by level.
Start
Commit your prediction above to see the result
Make your prediction to see the result.
One update, by hand
ReadThe reference's example: a normal mean with a standard-normal prior, , a batch of four, step and one supplied noise draw.
import numpy as np
theta = 0.2; batch = np.array([1.0, 0.5, 1.2, 0.8]); N = 100; eps = 0.001; innovation = 0.3
gradient = -theta + N / len(batch) * np.sum(batch - theta) # prior + scaled batch likelihood
next_theta = theta + 0.5 * eps * gradient + np.sqrt(eps) * innovation
print("full-log-posterior gradient estimate", gradient, "new state", next_theta)theta <- 0.2; batch <- c(1, 0.5, 1.2, 0.8); N <- 100; eps <- 0.001; innovation <- 0.3
gradient <- -theta + N / length(batch) * sum(batch - theta) # prior + scaled batch likelihood
next.theta <- theta + 0.5 * eps * gradient + sqrt(eps) * innovation
print(c(gradient = gradient, new.state = next.theta))The gradient estimate is 67.3 and the new state 0.243. Python and R agree exactly here because the noise draw is supplied, not generated.
Why it is only approximate
ReadBasic SGLD has no accept test. The discretization error that HMC's Metropolis step would correct stays in. The theory needs a step size that shrinks over time (, ); as it shrinks, the chain mixes ever more slowly. A practical run with a constant step is biased, often toward too little or too much spread depending on the model.
So check it the way you'd check any approximation: on a model with a known posterior, compare moments across step sizes and batch sizes, and compare predictive calibration on held-out data, not training loss.
Predict: noisy training
PredictPredict first
Plain minibatch SGD already wanders around because its gradients are noisy. Are its iterates posterior draws?
Reveal
No. Minibatch noise depends on the batch size and the data, not on the posterior; its size and shape are wrong. SGLD adds noise of a precise variance and scales the gradient so the stationary behavior aims at the posterior. Adding arbitrary noise to an optimizer isn't the same thing.
SGHMC: momentum with friction
ReadPlain HMC with minibatch gradients drifts away from the posterior: the gradient noise keeps pumping energy in. SGHMCStochastic gradient Hamiltonian Monte CarloHMC with minibatch gradients plus a friction term that cancels the extra noise the minibatches add, so momentum still helps exploration. adds friction that drains energy, and injects only the noise not already supplied by the minibatches, :
must be non-negative. In the reference's scalar example the injected noise variance is 0.006. If underestimates the gradient noise, the stationary spread is wrong; there's no accept test to catch it.
Reference · INF014 · Explained hereStochastic gradient Hamiltonian Monte Carlo (SGHMC)Uses momentum, friction, and calibrated noise to counter the extra diffusion introduced by stochastic gradients.Where they stand in CodeSplash
ReadCheck your understanding
CheckpointCheck yourself
An SGLD implementation averages the likelihood gradient over a batch of 64 rows from 64,000, but forgets the factor. What goes wrong?
Show the answer
Answer: b
The batch gradient must estimate the full-data gradient. Without the sampler targets a posterior with a thousandth of the data.
Check yourself
Why does SGLD with a constant step size give biased draws even after a long run?
Show the answer
Answer: b
HMC's Metropolis step removes integration error. Basic SGLD skips it to save full-data passes, so its accuracy depends on the step size and schedule.
Check yourself
What does SGHMC's friction term correct?
Show the answer
Answer: b
Friction drains energy; the injected noise is reduced by the estimated gradient noise, so the total stays balanced. If that estimate is wrong, so is the stationary spread.
Check yourself
A paper calls its method "SGHMC" but uses Adam with momentum plus some added Gaussian noise of a hand-picked size. What should you conclude?
Show the answer
Answer: b
The names describe specific dynamics with matched friction and noise. Arbitrary noise on an optimizer has no guarantee of targeting the posterior.
Recap
Recap- SGLD: half gradient step on the log posterior (batch gradient times ) plus noise of variance .
- No accept test, so constant steps stay biased; check against a known posterior.
- SGHMC adds friction to cancel minibatch noise; mismatched noise breaks it.
- Explained here: CodeSplash's Bayesian fits use full-data NUTS.
Concepts in this lesson