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.
What runs in CodeSplash
- INF002Coordinate-ascent variational inference and variational EM Runs in CodeSplash
- INF003Stochastic variational inference (SVI) Partly runs in CodeSplash
- Topic model Verified in Python and R
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
From sampling to optimizing
ReadSamplers 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 , 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 , 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 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:
Coordinate ascent
ReadThe most common family is mean-field: , 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:
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 ; EM is the special case where the E-step's 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;Mean-field is overconfident
ReadMinimizing punishes for putting mass where has little, so 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.
How strongly the Gaussian's coordinates move together; mean-field can't represent it.
Where the fit's mean starts; with two modes it decides which one it finds.
Stochastic gradient steps on the ELBO.
Starting step size; it shrinks as 100 / (100 + t).
Monte Carlo draws behind each gradient estimate.
- 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 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.
Predict: compare two ELBOs
PredictPredict 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?
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.
Stochastic variational inference
ReadCAVI touches every row each pass. Stochastic variational inference (SVI) handles a minibatch of rows: fit their local factors, scale their statistics by as if the batch were the whole dataset, form a noisy target for the global parameters, and step part-way toward it:
For conjugate models this is a natural-gradient step. The step size must shrink, usually with between 0.5 and 1. In a Beta–Bernoulli example with 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.Batch and online topics in CodeSplash
ReadThe 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.
3 topics in 61 documents (85 terms); topic 1 (higher, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| higher | Topic 1 | 0.0592 |
| bank | Topic 1 | 0.0590 |
| rates | Topic 1 | 0.0538 |
| profits | Topic 1 | 0.0475 |
| inflation | Topic 1 | 0.0472 |
| fans | Topic 1 | 0.0309 |
| interest | Topic 1 | 0.0297 |
| coach | Topic 1 | 0.0237 |
| team | Topic 1 | 0.0228 |
| bond | Topic 1 | 0.0213 |
| shares | Topic 2 | 0.0457 |
| rates | Topic 2 | 0.0447 |
| interest | Topic 2 | 0.0416 |
| markets | Topic 2 | 0.0405 |
| investors | Topic 2 | 0.0399 |
| team | Topic 2 | 0.0395 |
| match | Topic 2 | 0.0383 |
| striker | Topic 2 | 0.0377 |
| fell | Topic 2 | 0.0290 |
| made | Topic 2 | 0.0254 |
| garlic | Topic 3 | 0.0524 |
| onions | Topic 3 | 0.0422 |
| sauce | Topic 3 | 0.0419 |
| lemon | Topic 3 | 0.0334 |
| add | Topic 3 | 0.0329 |
| olive | Topic 3 | 0.0328 |
| herbs | Topic 3 | 0.0327 |
| oil | Topic 3 | 0.0327 |
| simmer | Topic 3 | 0.0327 |
| bake | Topic 3 | 0.0309 |
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 35.0% | −1.296 | higher, bank, rates, profits, inflation, fans, interest, coach, team, bond |
| 2 | 34.6% | −1.392 | shares, rates, interest, markets, investors, team, match, striker, fell, made |
| 3 | 30.5% | −0.9037 | garlic, 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)
))
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
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 35.0% | −1.296 | higher, bank, rates, profits, inflation, fans, interest, coach, team, bond |
| 2 | 34.6% | −1.392 | shares, rates, interest, markets, investors, team, match, striker, fell, made |
| 3 | 30.5% | −0.9037 | garlic, 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.
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 . 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.
Where each idea stands in CodeSplash
Read| Entry | In 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 |
Check your understanding
CheckpointCheck yourself
Maximizing the ELBO is equivalent to minimizing which quantity?
Show the answer
Answer: b
and doesn't depend on . This direction of KL makes avoid regions where 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 ?
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.
Recap
Recap- VI maximizes the ELBO, which minimizes 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 and needs a shrinking step; CodeSplash runs both for LDA.
Concepts in this lesson