Skip to content

Variational inference: optimize instead of sample

Variational inference picks the closest member of a simple family to the posterior. Learn the ELBO, coordinate ascent and variational EM, the stochastic version that scales, and why mean-field answers are usually too confident.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write the ELBO and say which KL divergence variational inference minimizes
  • Describe a coordinate-ascent update and what variational EM adds
  • Explain why mean-field factors understate variance for correlated parameters
  • Describe stochastic variational inference's update, its N/B scaling and step schedule

Read first

01

From sampling to optimizing

Read

Samplers give draws that converge to the posterior if you run them long enough. Variational inferenceVariational inferenceTurns inference into optimization: pick the member of a simple family q closest to the posterior, by maximizing the ELBO. (VI) gives up that guarantee for speed: choose a family of simple distributions qq, then find the member closest to the posterior. The answer arrives as fast as an optimizer converges, and it is only as good as the family.

"Closest" means smallest KL(q ∥ p)\mathrm{KL}(q\,\|\,p), the KL divergenceKullback–Leibler divergenceHow many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match. from qq to the posterior. That can't be computed directly (it needs the evidence), but maximizing the ELBOEvidence lower boundThe quantity a VAE maximizes; minus it is the loss — how badly rows are rebuilt plus how far their codes stray from the prior. is equivalent:

L(q)=Eq[log⁡p(x,z)]−Eq[log⁡q(z)]=log⁡p(x)−KL(q ∥ p(z∣x)).\mathcal L(q)=E_q[\log p(x,z)]-E_q[\log q(z)]=\log p(x)-\mathrm{KL}\big(q\,\|\,p(z\mid x)\big).
02

Coordinate ascent

Read

The most common family is mean-field: q(z)=∏jqj(zj)q(z)=\prod_j q_j(z_j), independent factors. Coordinate-ascent VICoordinate-ascent variational inferenceUpdates one factor of a factorized q at a time to its best value given the others; each update can only raise the ELBO. (CAVI) updates one factor at a time to its optimum given the others:

log⁡qj∗(zj)=Eq−j[log⁡p(x,z)]+const.\log q_j^*(z_j)=E_{q_{-j}}\big[\log p(x,z)\big]+\text{const}.

In conjugate models each update is a standard distribution, and each one can only raise the ELBO, as in EM. Variational EM alternates these updates with a step that also improves the model's parameters θ\theta; EM is the special case where the E-step's qq is the exact conditional.

Reference · INF002 · Runs in CodeSplashCoordinate-ascent variational inference and variational EMApproximates a latent posterior by optimizing a tractable distribution, often a product of factors. Coordinate-ascent VI updates one factor at a time;
03

Mean-field is overconfident

Read

Minimizing KL(q∥p)\mathrm{KL}(q\|p) punishes qq for putting mass where pp has little, so qq hugs the posterior's core. For correlated parameters a product of independent factors can't tilt along the correlation, so it shrinks.

The reference's program applies CAVI to a standard bivariate normal with correlation 0.8. The factor means land exactly right, but each factor's variance is 0.36 where the true marginal variance is 1.0: the intervals come out far too narrow. A converged ELBO said nothing about that.

Raise the correlation and watch the mean-field fit keep the center but shrink the spread.

EExplorable · Mean-field VI and the direction of the KL

What does a mean-field variational fit get wrong, and why does it miss spread rather than add it?

Target

The posterior the fit approximates.

0.80

How strongly the Gaussian's coordinates move together; mean-field can't represent it.

1.5

Where the fit's mean starts; with two modes it decides which one it finds.

1000

Stochastic gradient steps on the ELBO.

0.050

Starting step size; it shrinks as 100 / (100 + t).

4

Monte Carlo draws behind each gradient estimate.

true SD of x₁best mean-field SD
  • Target
  • VI fit, minimizing KL(q‖p)
  • Forward-KL optimum, KL(p‖q)
Fitted mean of x₁
−0.020
Fitted SD of x₁
0.618
Fitted SD of x₂
0.590
Share of the true spread
0.618
  • Puzzle: Find settings where the fit reports less than half of x₁'s true spread.
  • Puzzle: Make the fit land on the left mode of the two-mode target.
The fitted q has means (−0.02, 0.03) and standard deviations (0.62, 0.59). The target's true SD of x1 is 1.00, so the fit reports 62% of the real spread. On a Gaussian with correlation 0.80 the best mean-field fit has SD √(1 − ρ²) = 0.60: it is too confident, never too cautious.

The fitted q has means (−0.02, 0.03) and standard deviations (0.62, 0.59). The target's true SD of x₁ is 1.00, so the fit reports 62% of the real spread. On a Gaussian with correlation 0.80 the best mean-field fit has SD √(1 − ρ²) = 0.60: it is too confident, never too cautious.

04

Predict: compare two ELBOs

Predict

Predict first

Two variational fits of different models to the same data: model A's ELBO is higher than model B's. Which has the better posterior approximation?

Model A: its ELBO is higher, so its posterior approximation is betterNeither conclusion follows from the ELBOs alone
Reveal

Neither conclusion follows. The ELBO equals log evidence minus the KL gap, so a higher ELBO can come from a better model (higher evidence) with a worse approximation. Comparing ELBOs across different observation models or data encodings isn't even like for like. Check intervals against NUTS or SBC on a small case.

05

Stochastic variational inference

Read

CAVI touches every row each pass. Stochastic variational inference (SVI) handles a minibatch of BB rows: fit their local factors, scale their statistics by N/BN/B as if the batch were the whole dataset, form a noisy target for the global parameters, and step part-way toward it:

λt+1=(1−ρt)λt+ρt(η+NB∑i∈BtEqi[t(xi,zi)]).\lambda_{t+1}=(1-\rho_t)\lambda_t+\rho_t\Big(\eta+\frac NB\sum_{i\in\mathcal B_t}E_{q_i}[t(x_i,z_i)]\Big).

For conjugate models this is a natural-gradient step. The step size must shrink, usually ρt=(τ0+t)−κ\rho_t=(\tau_0+t)^{-\kappa} with κ\kappa between 0.5 and 1. In a Beta–Bernoulli example with N=1000N=1000 and a batch of 10, one step moves the posterior mean to 0.696.

Reference · INF003 · Partly runs in CodeSplashStochastic variational inference (SVI)Uses minibatch information to optimize a variational posterior over global latent quantities, avoiding a full-data coordinate pass at every update.
06

Batch and online topics in CodeSplash

Read

The Topic model's LDA runs variational Bayes in two ways. Batch is CAVI-style, every document each update; Online (stochastic variational) is SVI, after Hoffman, Blei and Bach, with Documents per batch, Step offset (τ0) and Step decay (κ) settings.

Topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 30 values compared
R

3 topics in 61 documents (85 terms); topic 1 (higher, …) is the most common.

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
higherTopic 10.0592
bankTopic 10.0590
ratesTopic 10.0538
profitsTopic 10.0475
inflationTopic 10.0472
fansTopic 10.0309
interestTopic 10.0297
coachTopic 10.0237
teamTopic 10.0228
bondTopic 10.0213
sharesTopic 20.0457
ratesTopic 20.0447
interestTopic 20.0416
marketsTopic 20.0405
investorsTopic 20.0399
teamTopic 20.0395
matchTopic 20.0383
strikerTopic 20.0377
fellTopic 20.0290
madeTopic 20.0254
garlicTopic 30.0524
onionsTopic 30.0422
sauceTopic 30.0419
lemonTopic 30.0334
addTopic 30.0329
oliveTopic 30.0328
herbsTopic 30.0327
oilTopic 30.0327
simmerTopic 30.0327
bakeTopic 30.0309

Topics

TopicShare of textCoherence (UMass)Top terms
135.0%−1.296higher, bank, rates, profits, inflation, fans, interest, coach, team, bond
234.6%−1.392shares, rates, interest, markets, investors, team, match, striker, fell, made
330.5%−0.9037garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b02ad770d34d7157
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L  # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 3
SEED <- 42
alpha <- NULL
if (is.null(alpha)) alpha <- 1 / K
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
fit <- cs_topics_best_of(function(sd) {
  f <- cs_topics_lda_online(X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)
  list(doc_topic = cs_ml_shares(f$gamma), topic_term = cs_ml_shares(f$lambda), extra = NULL)
}, X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/lda_online/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

3 topics in 61 documents (85 terms); topic 1 (higher, …) is the most common.

To keep this page light, the plots are shown once, under the R tab.

Topics

TopicShare of textCoherence (UMass)Top terms
135.0%−1.296higher, bank, rates, profits, inflation, fans, interest, coach, team, bond
234.6%−1.392shares, rates, interest, markets, investors, team, match, striker, fell, made
330.5%−0.9037garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b02ad770d34d7157
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())  # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 3
SEED = 42
alpha = None or 1.0 / K
eta = None or 1.0 / K
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
doc_topic, topic_term, loglik, start, _ = cstopics.best_of(lambda sd: tuple(cstext.shares(m) for m in cstopics.lda_online(
    X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)) + (None,), X, 2, SEED)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/lda_online/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})

On the same 61-document corpus with three topics, the batch fit's log-likelihood of the words is −925.6; the online fit's is −959.7. On a corpus this small, online learning only adds noise; it earns its keep when the corpus doesn't fit a full pass per update.

07

Pitfalls

Read
  • The family limits the answer. No amount of optimizer tuning fixes a factorization that drops a correlation that matters.
  • Local optima. Run several initializations; compare their ELBOs on the same model only.
  • Wrong N/BN/B. Scaling the batch wrong changes how much the data outweigh the prior, silently.
  • "SVI" in libraries often means any stochastic ELBO optimizer, not the natural-gradient update above. Say which you used.
  • Check against a reference. On a small problem, compare means and intervals with NUTS, or run SBC.
08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
CAVI and variational EM (INF002)Runs in CodeSplash: batch variational Bayes in Topic model (LDA), Python ≡ R
SVI (INF003)Partly runs in CodeSplash: Topic model's online learning is SVI for LDA; no general SVI for other models
09

Check your understanding

Checkpoint

Check yourself

Maximizing the ELBO is equivalent to minimizing which quantity?

Show the answer

Answer: b

L(q)=log⁡p(x)−KL(q∥p)\mathcal L(q)=\log p(x)-\mathrm{KL}(q\|p) and log⁡p(x)\log p(x) doesn't depend on qq. This direction of KL makes qq avoid regions where pp is small, which is why mean-field fits hug the core.

Check yourself

A mean-field VI fit of a regression with two strongly correlated coefficients gives the right means. What do you expect about its 95% intervals?

Show the answer

Answer: b

In the reference's example the factor variance is about a third of the true one. Mean-field VI is a fast first look; check intervals against NUTS when they matter.

Check yourself

What does variational EM add to coordinate-ascent VI?

Show the answer

Answer: b

CAVI approximates the posterior for fixed parameters; variational EM also improves the parameters, like EM with an approximate E-step.

Check yourself

In stochastic variational inference, why are a minibatch's expected statistics multiplied by N/BN/B?

Show the answer

Answer: b

The update aims at the optimum as if the batch were the full data. Wrong scaling silently changes the prior-to-data balance.

Check yourself

An online LDA run uses a constant step size of 0.5 forever. What's the risk?

Show the answer

Answer: b

Stochastic approximation needs shrinking steps whose sum diverges but whose squares sum to a finite value. τ0 and κ set that schedule.

10

Recap

Recap
  • VI maximizes the ELBO, which minimizes KL(q∥p)\mathrm{KL}(q\|p) within a chosen family.
  • CAVI updates one factor at a time; variational EM also updates the parameters.
  • Mean-field fits get means right and variances too small for correlated parameters.
  • SVI scales batch statistics by N/BN/B and needs a shrinking step; CodeSplash runs both for LDA.

Concepts in this lesson