Skip to content

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.

Advanced ~12 min9 steps

What runs in CodeSplash

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

Read first

01

The big-data problem

Read

Every Metropolis–Hastings or HMC step evaluates the likelihood (or its gradient) on all NN 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 BB 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".

02

SGLD: a gradient step plus noise

Read

Stochastic 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:

θt+1=θt+ϵt2[∇log⁡p(θt)+NB∑i∈Bt∇log⁡p(xi∣θt)]+ϵt ξt,ξt∼N(0,I).\theta_{t+1}=\theta_t+\frac{\epsilon_t}{2}\Big[\nabla\log p(\theta_t)+\frac NB\sum_{i\in\mathcal B_t}\nabla\log p(x_i\mid\theta_t)\Big]+\sqrt{\epsilon_t}\,\xi_t,\qquad \xi_t\sim N(0,I).

Two scalings matter. The batch gradient is multiplied by N/BN/B, so it estimates the full-data likelihood gradient; forget it and the prior silently dominates. The noise standard deviation is ϵ\sqrt{\epsilon}, not ϵ\epsilon.

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?

How sure?
0.20
4.0

Modes at (−a, −a) and (a, a).

0.50

Each level steps α = η(1 + σ²).

50

Start from the score of heavily noised data and sharpen it level by level.

10
300

Start

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

One update, by hand

Read

The reference's example: a normal mean with a standard-normal prior, N=100N=100, a batch of four, step ϵ=0.001\epsilon=0.001 and one supplied noise draw.

Python
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)
R
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.

04

Why it is only approximate

Read

Basic 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 (∑ϵt=∞\sum\epsilon_t=\infty, ∑ϵt2<∞\sum\epsilon_t^2<\infty); 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.

05

Predict: noisy training

Predict

Predict first

Plain minibatch SGD already wanders around because its gradients are noisy. Are its iterates posterior draws?

Yes: minibatch noise already spreads the weights like a posteriorNo: the noise has the wrong size and shape unless it is added and scaled on purpose
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.

06

SGHMC: momentum with friction

Read

Plain 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 CC that drains energy, and injects only the noise not already supplied by the minibatches, C−B^C-\hat B:

θ+=θ+ϵp,p+=(I−ϵC) p−ϵ ∇U^(θ+)+2ϵ (C−B^)  ξ.\theta^+=\theta+\epsilon p,\qquad p^+=(I-\epsilon C)\,p-\epsilon\,\widehat{\nabla U}(\theta^+)+\sqrt{2\epsilon\,(C-\hat B)}\;\xi .

C−B^C-\hat B must be non-negative. In the reference's scalar example the injected noise variance is 0.006. If B^\hat B 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.
07

Where they stand in CodeSplash

Read
08

Check your understanding

Checkpoint

Check yourself

An SGLD implementation averages the likelihood gradient over a batch of 64 rows from 64,000, but forgets the N/BN/B factor. What goes wrong?

Show the answer

Answer: b

The batch gradient must estimate the full-data gradient. Without N/BN/B 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.

09

Recap

Recap
  • SGLD: half gradient step on the log posterior (batch gradient times N/BN/B) plus noise of variance ϵ\epsilon.
  • 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