Foundations to Frontier
Tests

Variational Inference for Neural Networks

Variational inference replaces the intractable posterior over a network's weights with a simple distribution q, usually an independent Gaussian per weight, fitted by maximising the evidence lower bound: expected log-likelihood minus KL(q ‖ prior). Bayes by Backprop (Blundell et al., 2015) makes this trainable with ordinary backpropagation through reparameterised weight samples, θ = μ + σ ε. It doubles the parameter count, and the mean-field assumption has known costs: it ignores correlations between weights, so it is overconfident, and the KL term can make it underfit. This page covers the ELBO for networks, the reparameterisation and local reparameterisation tricks, KL weighting, and the failure modes. In the exercises you compute KL terms and ELBOs. You then show on Bayesian linear regression that the best mean-field fit has only 0.50 of the true posterior std when two features are 0.9-correlated (0.26 at 0.99). Finally you train Bayes by Backprop on a small network: its epistemic std was 0.10 on the data and 0.18 in a gap between the data clusters but only 0.10 far away, where the HMC reference grows. Down-weighting the KL to 0.1 shrank the std to 0.03 and fixed underfitting (RMSE 0.16 → 0.03).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Approximate the posterior with something simple

The exact distribution over a network’s weights is far too complicated to compute. Variational inference picks a simple family, such as “each weight is an independent bell curve with its own centre and width”, and tunes the centres and widths so the bell curves are as close as possible to the true posterior. Training looks like normal training with noise: each step uses randomly perturbed weights. The demo shows the price of “independent”: when two weights are correlated, the independent fit is much too narrow.

Bayesian deep learning lab
Shaded: the true posterior (2σ) of two weights with correlation 0.9. Circle: the mean-field Gaussian that minimises KL(q‖p). Its std per weight is 0.44 of the true marginal std, so strong correlations make mean-field VI overconfident.
Why engineers care

Bayes by Backprop and its descendants (IVON, 2024) let you train uncertainty-aware networks at the cost of about twice the memory, which makes them a candidate for onboard perception where ensembles are too expensive.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Variational inference turns inference into…
  2. 2. Mean-field VI assumes the weights are…
  3. 3. Ignoring correlations makes the approximation…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • ELBO: log p(D) ≥ E_q[log p(D | θ)] − KL(q(θ) ‖ p(θ)) = ELBO(q); maximising the ELBO minimises KL(q ‖ posterior). See the VI page for the derivation.
  • Mean-field Gaussian: q(θ) = Π_k N(μ_k, σ_k²), with σ_k = softplus(ρ_k) to keep it positive; 2P parameters for P weights.
  • Bayes by Backprop (Blundell et al., 2015): sample ε ~ N(0, I), set θ = μ + σ ε (reparameterisation), backpropagate −log p(D | θ) + KL through μ and ρ. With a Gaussian prior the KL is closed form; Graves (2011) did an early version.
  • Minibatches: scale the KL by 1/(number of batches) so the sum over an epoch is one KL. Many practitioners multiply it by β below 1 (“KL annealing”, tempering).
  • Variance reduction: local reparameterisation samples pre-activations, mean x μ and variance x² σ² (Kingma, Salimans and Welling, 2015); Flipout decorrelates samples within a batch (Wen et al., 2018).
  • Recent: natural-gradient variational methods (Vadam, VOGN, and IVON, Shen et al., 2024) train ImageNet-scale and GPT-2-scale models at nearly Adam’s cost; function-space VI puts the prior on functions instead of weights.
📝 Quick check (Level 1)
0/3 answered
  1. 1. σ = softplus(ρ) is used so that…
  2. 2. Local reparameterisation samples…
  3. 3. With minibatches the KL term is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Training a variational BNN

Exercise 1.

  • softplus and reparameterised weight samples.
  • The KL between independent Gaussians and the prior.
  • An ELBO estimate.

Practice.

  • Initialise σ small (ρ ≈ −5) so training starts near a normal network; initialise μ as for a deterministic net.
  • Use 1 sample per step with local reparameterisation or Flipout; average 10–100 samples at test time.
  • Watch for underfitting: if the training loss is far above a deterministic network’s, the KL is too strong (try β below 1 or a wider prior) and report that you tempered.
  • Libraries: Bayesian-Torch (Intel), TensorFlow Probability layers, Pyro/NumPyro with AutoNormal guides, and IVON’s optimiser for PyTorch.
  • Evaluate test NLL and calibration, and uncertainty on shifted inputs, not just accuracy.
import torch, ivon                     # IVON: variational learning with an Adam-like optimiser (Shen et al., 2024)
model = make_net(); opt = ivon.IVON(model.parameters(), lr=0.1, ess=len(train_set))
for x, y in loader:
    with opt.sampled_params(train=True):    # one weight sample per step
        loss = torch.nn.functional.cross_entropy(model(x), y); loss.backward()
    opt.step(); opt.zero_grad()

probs = []
for _ in range(32):                         # predictive: average over weight samples
    with opt.sampled_params():
        probs.append(model(x_test).softmax(-1))
probs = torch.stack(probs).mean(0)
🐍 Exercise 1: softplus, reparameterisation, KL and ELBO
Write softplus, a reparameterised weight sample, the Gaussian KL to the prior and an ELBO estimate.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Initialise ρ around −5 so that…
  2. 2. If a variational BNN underfits, try…
  3. 3. At test time, predictions average over…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Mean-field is overconfident. For a Gaussian posterior with precision Λ, the q minimising KL(q ‖ p) among fully factorised Gaussians has the true mean and variances 1/Λ_kk. Since 1/Λ_kk ≤ Σ_kk (Schur complement), every marginal is too narrow; for two weights with correlation ρ the ratio of stds is √(1 − ρ²). Neural-network posteriors have strong correlations (for example between a hidden unit’s incoming and outgoing weights), so this matters.

Why KL(q ‖ p) under-covers. It is zero-forcing: q is penalised heavily wherever q is large but p small, and not where p is large but q small, so q fits inside one mode.

In-between uncertainty. Foong et al. (2020) proved that for one-hidden-layer networks, mean-field Gaussian and MC dropout cannot have predictive variance between two separated data clusters much larger than at the clusters, and showed mean-field fails in practice on such data. Deeper networks escape the theorem, but mean-field often still under-represents uncertainty away from the data.

Underfitting and pruning. The KL term pays for every weight that moves away from the prior. Weights not worth the cost are set to μ ≈ 0, σ ≈ prior std (overpruning; Trippe and Turner, 2018), and for wide networks the posterior can collapse to the prior, ignoring the data (Coker et al., 2022). Tempering with β below 1 trades Bayesian correctness for fit.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The optimal mean-field variance for weight k is…
  2. 2. KL(q ‖ p) tends to make q…
  3. 3. Weights that revert to the prior under VI are said to be…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much does the mean-field assumption cost, and what does Bayes by Backprop’s uncertainty look like?

History.

  • A. Graves, “Practical variational inference for neural networks” (2011).
  • C. Blundell, J. Cornebise, K. Kavukcuoglu, D. Wierstra, “Weight uncertainty in neural networks” (Bayes by Backprop, 2015).
  • A. Foong, D. Burt, Y. Li, R. Turner, “On the expressiveness of approximate inference in Bayesian neural networks” (2020).
  • Y. Shen et al., “Variational learning is effective for large deep networks” (IVON, 2024).

Exercise 2. Two experiments.

  • Mean-field vs exact: Bayesian linear regression on 50 points with two features of correlation ρ, prior N(0, I), noise 1. Ratio of mean-field to exact std of w₁ and of the prediction at x* = (1, −1).
  • Bayes by Backprop: 40 points of sin(3x) + N(0, 0.1²) in two clusters; 1-20-1 tanh network (61 weights), priors as on the BNN page; 3000 Adam steps, 2 weight samples per step, KL weight β = 1 or 0.1; predictive from 300 samples. Epistemic std averaged over the data region, the gap and far away (x in 1.6–2).
feature correlation std ratio, w₁ std ratio, prediction
0 0.99 0.91
0.9 0.50 0.37
0.99 0.26 0.18
Bayes by Backprop std data std gap std far RMSE KL (nats) weights at prior
β = 1 0.10 0.18 0.10 0.16 92 16%
β = 0.1 0.03 0.05 0.04 0.03 213 2%
  • Mean-field is overconfident in proportion to the correlation; predictions along poorly determined directions suffer most.
  • β = 1: more uncertain in the gap than on the data, but far away no more uncertain than on the data. HMC on the BNN page (different sample, 24 points) grew about fivefold far away.
  • β = 1 underfits on this seed (RMSE 0.16 against 0.03): the KL makes some weights (16%) revert to the prior.
  • β = 0.1 fits well but is nearly deterministic: this is the tempering trade-off.
  • Seeds 1 and 2: ratio at 0.9 was 0.47 and 0.49; β = 1 far std 0.10 and 0.12 against gap 0.20 and 0.16; β = 1 RMSE 0.10 and 0.03.
🐍 Exercise 2 (research): how much does the mean-field assumption cost, and what does Bayes by Backprop's uncertainty look like?
Compare mean-field and exact posteriors on correlated linear regression, then train Bayes by Backprop with two KL weights and measure its uncertainty.

Variational BNNs in AI, robotics and aerospace

  • Onboard uncertainty at low cost: one network with sampled weights fits in memory budgets where an ensemble does not.
  • Continual learning: the previous posterior becomes the next task’s prior (variational continual learning, Nguyen et al., 2018).
  • Active learning and exploration: VIME (Houthooft et al., 2016) rewards robots for information gain measured with a variational dynamics model.

References

  1. C. Blundell et al. (2015). “Weight uncertainty in neural networks.” ICML.
  2. D. P. Kingma, T. Salimans, M. Welling (2015). “Variational dropout and the local reparameterization trick.” NeurIPS.
  3. A. Foong et al. (2020). “On the expressiveness of approximate inference in Bayesian neural networks.” NeurIPS.
  4. B. Coker et al. (2022). “Wide mean-field Bayesian neural networks ignore the data.” AISTATS.
  5. Y. Shen et al. (2024). “Variational learning is effective for large deep networks.” ICML.