Variational EM and VAEs

A variational autoencoder fits a hidden-variable model of neural activity by climbing a lower bound it can compute, because the exact likelihood is out of reach.

Two neurons fire in step with one hidden variable you cannot see. Learn how a model finds that variable, and why a bent decoder fits where a straight one cannot.

Press Train with the straight decoder, then switch to the bent one and train again. Watch the orange samples chase the blue recordings. Then we build, piece by piece, the bound, the trick and the network underneath.

You need a feel for a probability density (a curve whose area says how likely a range of values is) and the idea of a slope. We build the rest from zero.

Based on Lecture 20 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. Slides (PDF). The data, devices and numbers on this page are our own and illustrative.

Fit the hidden variable

Illustrative: 160 made-up pairs of firing rates (centred, arbitrary units) generated from one hidden number. Both decoders share one training code: the straight one has no bend (no tanh units), the bent one has 8. The loss is the negative ELBO per point with constants dropped, noise variance fixed at 0.04.

Chapter 0

A Hidden Cause Behind the Spikes

See why neural recordings call for hidden variables, and why fitting them gets hard once the mapping bends

Two neurons sit side by side in motor cortex. You count their spikes in bins of 100 milliseconds. A spike count is a whole number: in this bin neuron A fired 4 times and neuron B fired 9. In the next bin the counts are 7 and 3. Over a thousand bins the two counts rise and fall together in a pattern.

Something you cannot see pushes both neurons. It may be the direction the animal plans to reach. It may be attention, or arousal, or a thought. You did not measure it. Yet one hidden number could explain much of what both neurons do.

That hidden number is a latent variable, written z. “Latent” means present but not seen. A latent variable model is a recipe in two steps. First, draw z from a simple distribution. Second, given z, draw the data x, here the two spike counts. Because the recipe produces data, we also call it a generative model.

The device below is that recipe with a single knob. The curves show how each neuron’s average spike count depends on z. The bars are one simulated recording at the z you choose.

Record two neurons from one hidden z

Top: how the average count of each neuron depends on z. Bottom: 30 recorded bins, one bar per bin. Drag z, then press Record again. Press Hide z to see what you really get in the lab.

0.60

Illustrative: neuron A prefers z near 0 (a bump, peak 10 spikes per bin) and neuron B rises with z (up to 8 per bin). Counts are Poisson draws, seeded, computed live in your browser. The curves are made up for this page.

Drag z left and right. Neuron A peaks near zero, and neuron B grows as z grows. The two rows of bars move together because one z feeds both. That shared push is the whole reason to posit a latent variable.

Now press Hide z. The purple marker vanishes, and you hold only the blue bars. This is the situation in a real experiment. From the bars alone, you must say what z was, and you must also learn the two curves. Saying what z was is called inference. Learning the curves is called fitting. They depend on each other, which is what makes the problem hard.

The number we want to make large

The model gives every recording a probability. It adds up, over every z that could have produced the recording, the chance of that z times the chance that this z yields the recording.

p(x | θ)
The marginal likelihood: how probable the recorded data x is under the model with parameters θ. The lecture also calls it the “evidence”. We want θ that makes it large.
p(x | z, θ)
The chance of the data when z is known. In the device, this is the Poisson draw from the two curves. θ holds the shape of those curves.
p(z)
The prior: how likely each z is before you look at any data. We will use a bell curve with mean 0 and width 1.

The integral sign is a sum over a continuum of z values. With one z, you can compute it on a grid of 200 points. With 20 hidden numbers, the grid is hopeless. The rest of this lesson is the answer to that single obstacle.

Where the lecture picks up

Lectures 15, 16 and 17 built expectation maximization (EM), the standard way to fit such a model. EM alternates two steps. The E-step asks: given my current θ, what do I now believe about z for each recording? That belief is the posterior, p(z | x, θ). The M-step then updates θ as if that belief were fact.

It works when the posterior has a closed form. For a mixture of Gaussians, it does, and the posterior is just a table of cluster odds. The lecture’s opening slide asks what happens when it does not: what if we can’t perform (exact) EM for a latent variable model? In our device, once the curves bend, the posterior over z becomes a lumpy shape with no formula.

The lecture has two parts. Part one, variational EM, swaps the exact E-step for an approximate one that we can always compute. Part two, the variational auto-encoder (VAE), turns that idea into a recipe for neural networks and large data sets, using one clever trick. The same recipe also fits spike trains, which the last chapter shows.

Housekeeping

The lecture opens with three announcements. Homework 4 drops that day. Final-project 1-to-1 meetings run from a signup sheet. Final presentations take place on May 6 or May 7, the Dean’s date. These matter only to enrolled students, and nothing below depends on them.

The road

  1. The bound we can compute: the ELBO, in its two forms.
  2. Climbing with a loose bound: variational EM, step by step.
  3. What a VAE is, and is not: a generative model, not just a squeezer.
  4. From straight to bent: factor analysis, then a network decoder.
  5. A gradient through a random draw: Monte Carlo and the resampling trick.
  6. The VAE as two networks: the generative and the recognition network.
  7. The VAE objective: reconstruction plus a KL penalty.
  8. Putting it together: the learning algorithm and the results.
  9. VAEs for spike trains: the neuroscience application and the summary.
  10. The lecture on one page: numbers, code, links, credit.
You record only spike counts from two neurons and fit a latent variable model. What is z?

Chapter 1

The Bound We Can Compute

Build the ELBO from a two-cause toy, see its two forms, and read off what each form lets you do

A neuron fires a burst. Two hidden states could have caused it: attending or resting. Before the burst, you believed “attending” had odds 0.3 and “resting” had odds 0.7. An attending neuron produces this burst with chance 0.4. A resting neuron produces it with chance 0.1.

Multiply each cause by its chance of the burst. Attending: 0.3 × 0.4 = 0.12. Resting: 0.7 × 0.1 = 0.07. These two numbers are the joint probabilities p(x, z). Their sum is the marginal likelihood of the burst: p(x) = 0.12 + 0.07 = 0.19, so log p(x) = −1.661.

With two causes, this sum is easy. With a continuous z and a bent decoder, it is an integral with no formula. We want something we can always compute that never exceeds log p(x), so that pushing it up pushes the likelihood up too.

Any distribution gives a floor

Pick any distribution q over the causes, for example 50:50. Weigh every term in the sum by q, then divide it back out. This changes nothing: p(x) = Σ q(z) · p(x, z) / q(z). Now the sum is an average of the ratio p(x, z) / q(z), taken with weights q.

Here comes Jensen’s inequality: the log of an average is at least the average of the logs. Picture the log curve bending over like a hill. A straight chord between two points on it lies under the curve. So the average of the logs sits under the log of the average.

F(φ, θ)
The ELBO, the evidence lower bound. The lecture calls it the negative free energy. It is a number you can compute for any choice of q.
q(z | φ)
Your chosen distribution over the hidden z. The numbers φ are its dials, called the variational parameters. In the toy, φ is just the weight on “attending”.
p(x, z | θ)
The joint probability of the data and a cause. The model gives it directly, with no integral and no division.
log p(x | θ)
The log marginal likelihood, the number we truly care about. F never goes above it.

For q = 50:50, F = 0.5 · log(0.12 / 0.5) + 0.5 · log(0.07 / 0.5) = −1.7. That is below −1.661, as promised. The device lets you slide q and watch the floor move.

Slide q under the ceiling

The blue dashed line is log p(x), the ceiling. The orange curve is F as q moves. The yellow bar is the gap, which is the KL from Form 1 below. Drag q, or press Set q to the posterior.

0.30

Illustrative toy: p(attending) = 0.3, p(burst | attending) = 0.4, p(burst | resting) = 0.1, so p(x) = 0.19 and the true posterior on “attending” is 0.632. Natural logarithms throughout.

The curve is highest at q = 0.632. There it touches the ceiling exactly. Everywhere else it falls short. The size of the shortfall is the next thing to understand.

Two ways to write the same F

The lecture slide shows the ELBO in two forms. Each form answers a different question.

Form 1 splits the bound into the ceiling minus a gap. Replace the joint by p(z | x, θ) p(x | θ), which is the rule that a joint equals a conditional times a marginal. The p(x) part pulls out of the sum.

F(φ, θ)
The same bound as before.
log p(x | θ)
The ceiling. It depends on θ but not on q.
KL( q ‖ p )
The KL divergence (Kullback-Leibler divergence): a number that is zero when two distributions match and positive otherwise. Here it measures how far your q sits from the true posterior.

Check it with the toy at q = 0.3. The true posterior is 0.632 on “attending”. The KL is 0.3 · ln(0.3 / 0.632) + 0.7 · ln(0.7 / 0.368) = −0.223 + 0.449 = 0.226. So F = −1.661 − 0.226 = −1.887.

Form 1 tells you how to pick q. Only q appears in the KL. So to raise F with θ fixed, make the KL small. This is the E-step. If you can set q equal to the posterior, the KL is zero and F touches the ceiling. The lecture writes this as q(z | φ) = p(z | x, θ). A margin note on the slide adds that this “recognition distribution” may not exist in closed form.

Form 2 splits the bound into a term with the joint plus a term that only involves q.

F(φ, θ)
The same bound again.
Σ q log p(x, z | θ)
The average of the log joint, with weights q. For a continuous z this is an integral, and it is the only part that touches θ.
H[ q ]
The entropy of q: how spread out it is. The slide marks it “independent of θ”.

At q = 0.3 the first term is 0.3 · ln 0.12 + 0.7 · ln 0.07 = −2.497, and the entropy is 0.611. The sum is again −1.887. Both forms agree, and the device shows both numbers.

Form 2 tells you how to pick θ. The entropy ignores θ, so maximizing F over θ means maximizing the average log joint. This is the M-step, and it is the same step as in ordinary EM.

What “variational” adds

Slide 5 names the family. Variational EM is any version of the algorithm where q(z | φ) need not equal the true posterior. In the E-step you minimize the KL over φ and settle for a small KL instead of zero. Everyone calls q the variational approximation to p(z | x). The price is a gap under the ceiling. The gain is that q can always be a shape you can compute with.

The code below is the whole toy. Try it with any q.

import numpy as np
joint = np.array([0.3*0.4, 0.7*0.1])      # p(x, z) for z = attending, resting
log_px = np.log(joint.sum())               # -1.661, the ceiling
q = np.array([0.3, 0.7])
post = joint / joint.sum()                 # [0.632, 0.368]
kl = (q * np.log(q / post)).sum()          # 0.226, the gap
F1 = log_px - kl                           # form 1
F2 = (q * np.log(joint)).sum() - (q * np.log(q)).sum()   # form 2
print(F1, F2)                              # both -1.887
With θ fixed, which step of variational EM changes q, and what does it minimize?

Chapter 2

Climbing with a Loose Bound

Watch standard EM and variational EM climb the same hill, and see where a loose bound makes the climb stop short

You stand on a hill in thick fog. You want the top, but you cannot see the hill. That hill is the log likelihood, L(θ) = log p(x | θ). You do carry a lamp. It lights a smooth bowl hanging under the hill, and the bowl is the ELBO, F. You can see the bowl completely, and you can walk to its top.

This is how EM climbs. Chapter 1 gave the rules: F never rises above L, and F touches L exactly when q equals the posterior. So the lamp works in two moves. Light the bowl so it touches the hill where you stand. Then walk to the top of the bowl.

Standard EM, as a picture

The lecture draws this on slides 6 to 9. The blue curve is L. The red curve is the bowl F(φ1, θ), and it touches L at your first guess, θ0. The two steps are:

  1. E-step. Set q to the exact posterior at the current θ. This lights a bowl that touches the hill at your feet.
  2. M-step. Move θ to the top of the bowl. In symbols, θk = argmaxθ ∫ q(z | φk) log p(x, z | θ) dz. The word argmax means “the θ that makes this largest”.

Then repeat from the new θ. Each round can only go up. The proof is three lines. Write θ for the old value and θ′ for the new one. L(θ′) ≥ F(θ′) because F is a floor. F(θ′) ≥ F(θ) because the M-step climbed the bowl. F(θ) = L(θ) because the bowl touched the hill at θ. Chain them: L(θ′) ≥ L(θ).

Variational EM: the lamp falls short

Slides 10 to 14 change one thing. The E-step now reads φk = argminφ KL( q(z | φ) ‖ p(z | x, θk−1) ). You search over the dials φ for the q that sits closest to the posterior. But q lives in a family you chose, and the posterior may lie outside it. Then the KL cannot reach zero.

The slide flags the consequence in red: the lower bound is no longer tight. The bowl hangs under the hill instead of touching it. The M-step is unchanged. The lecture notes that the integral in it is the same thing as the expected log joint, Eq(z | φk)[ log p(x, z | θ) ].

Now try both. The toy has one parameter θ and a binary hidden cause that picks between two bell-shaped explanations of one recording. That gives a likelihood with two peaks. The M-step has a closed form here, so every number below is exact.

Climb in the fog

Blue: the log likelihood L, which you cannot see directly. Orange: the bowl F lit by your current q. Choose how flexible q is, then press E-step and M-step in turn, or Run to the end.

−0.50

Illustrative toy: L(θ) = log( 0.35 N(θ; −1.5, 0.5) + 0.65 N(θ; 1.5, 0.8) ), and the hidden cause is which of the two bells explains the recording. The bound is F = r log(0.35 N₁ / r) + (1 − r) log(0.65 N₂ / (1 − r)), where r is the weight q puts on the left bell. The limited family clamps r to the range 0.25 to 0.75.

Start with Any q at θ0 = −0.5. Press E-step. The posterior puts 0.726 on the left bell, so q gets that weight, and the bowl touches the hill: F = L = −2.956. Press M-step. θ jumps to −1.115. Repeat. After a few rounds, θ settles at −1.499, where L = −1.275. That is a peak of the hill, though not the highest one.

Now reset and pick Limited q. Round one is the same, because 0.726 is inside the allowed range. At θ = −1.115 the posterior is 0.993 on the left bell. The limited family cannot say 0.993. It says 0.75. The bowl now hangs under the hill: F = −2.234 against L = −1.565, a gap of 0.669 nats. The M-step moves θ to −1.154. From there, nothing changes: θ stays at −1.154, with L = −1.509 and a gap of 0.723.

What the loose bound costs, and what it keeps

The lecture states the result in two bullets on slide 14. A variational EM estimate converges to a local optimum of the ELBO. And its maximum is not necessarily at the same place as the maximum of the likelihood. The device shows both. The exact run ends on a peak of L. The limited run ends 0.35 away from that peak, at a place where L is 0.23 nats lower.

It keeps one more thing: the climb is still honest. Each E-step lowers the KL, so F rises. Each M-step raises F. So F never falls, and the algorithm stops at a stable point. What you lose is the chain from the last section: it relied on F touching L, and now it does not. L itself can wander.

Read the failure as three facts. The symptom: your estimate stops at −1.154, but the likelihood has a peak at −1.499. The measurement: the gap between F and L at the stopping point is 0.723 nats, so q is far from the posterior there. The fix: give q more shapes to choose from, so the KL can shrink. A VAE does exactly that. It lets a neural network choose q for every recording.

In variational EM the E-step cannot make the KL zero. What follows?

Chapter 3

What a VAE Is, and Is Not

Separate a compressor from a generative model, and see why the name “auto-encoder” misleads

Part two of the lecture opens with a question on slide 15: how can we fit richer, continuous latent variable models than factor analysis or probabilistic PCA? Factor analysis is the straight-line model from earlier lectures: a few hidden numbers, multiplied by a fixed matrix, plus noise. The hero at the top showed what it cannot do. A bent decoder can follow an arch, and a straight one cannot.

The answer the lecture gives is the variational auto-encoder, or VAE. Slide 16 gives its history. Two groups found it at the same time. Diederik Kingma and Max Welling published “Auto-encoding variational Bayes” at ICLR in 2014. Danilo Rezende, Shakir Mohamed and Daan Wierstra published “Stochastic backpropagation and approximate inference in deep generative models” at ICML the same year. The slide lists about 34,000 and 5,500 citations for the two papers as of the lecture. It also recommends Carl Doersch’s 2016 arXiv tutorial.

A photocopier and a printing press

Imagine a photocopier with a tiny memory. You feed it a page. It squeezes the page into a short code, then prints the page back from the code. If the copy matches, the copier worked. This is an auto-encoder. The lecture draws it on slide 17 as a network with a narrow middle layer: input x, a code z, an output x̂ that should equal x. Under the picture it says “do not think of” a VAE this way. The goal there is a compressed representation of the data.

Now imagine a printing press that holds a recipe instead. It can write a new page that looks like the pages in the training pile. It can also look at any page and say how typical it is. This is a generative model, and slides 18 and 19 say “do think of” a VAE this way. The goal: describe the probability distribution P(x) over complex data. The lecture’s own pictures of such data are natural images and spike trains.

Slide 19 adds how: P(x) is parametrized as arising from a latent variable z. Draw z from a simple distribution P(z). Push it through a conditional P(x | z) to get data. The blob of complex data is what you get after those two steps. This is the same two-step recipe as Chapter 0.

For neural data the difference is concrete. Say you record 100 neurons in many trials. An auto-encoder gives each trial a short code. A generative model gives you more: it can simulate a new trial, it can score a trial as ordinary or odd, and it can fill in neurons you did not record. The next device lets you feel the two jobs on one toy curve.

Compress, or generate

Click or drag in the plane to place a recording x (the two rates of neurons A and B). Choose what the model does with it. In generative mode, also press Invent 10 recordings.

Illustrative: one fixed decoder, f(z) = (1.045 z, 0.55 − 0.545 z2), with a bell-curve prior on z and noise of 0.2 on each rate. The density is the integral over z, computed live on a grid of 241 values. Real VAEs learn f from data (Chapter 8).

In auto-encoder mode, place a point near the arch. The model finds the code z that rebuilds it best, and shows the rebuild. Place a point far from the arch: the rebuild snaps back onto the curve, and the error is large. The auto-encoder never says how likely your point was.

Switch to generative mode. Your point now gets a density, and the read-out compares it with the highest density the model gives anywhere. Points on the arch score high. Points off it score near zero. Then press Invent 10 recordings. The model draws z from its bell curve, decodes it, and adds noise. The new orange points land where real recordings would.

Why the name misleads, and what it costs

A VAE does contain an encoder and a decoder, so the name is fair as a description of the parts. The slides ask you to look at the purpose. The decoder with its prior is the model. The encoder is a helper used while fitting: it is the “recognition distribution” that Chapter 6 builds.

Here is the failure you get by thinking of a VAE as a compressor. The symptom: the model reconstructs training data well, but samples drawn from its prior look wrong. The measurement: the codes the encoder produces for the training data cover odd, scattered regions of z, and the bell-curve prior puts most of its weight elsewhere. The fix is a penalty that pulls each code distribution toward the prior. That penalty is the KL term of Chapter 7, and it is the part a pure compressor lacks.

Which question can a generative model answer that a plain auto-encoder cannot?

Chapter 4

From Straight to Bent

Start from factor analysis, swap one matrix for a network, and meet the integral that blocks exact fitting

You record 100 neurons while an animal does a task. On each trial you get a list of 100 firing rates. Plot trial after trial, and the points do not fill 100-dimensional space. They hug a thin sheet, because a few hidden causes steer all the neurons together. The model for such a sheet is a latent variable model with a small z.

The straight model: factor analysis

Slide 20 reviews factor analysis (FA). It is the simplest such model, and it is linear. The recipe: draw a small latent vector z from a round bell curve. Multiply by a matrix A. Add independent noise to each neuron.

x
The data: a list of N firing rates, shape [N]. With 100 neurons, N = 100.
A
The loadings: a fixed matrix of shape [N, d] that says how much each hidden number pushes each neuron.
z
The latent vector, shape [d], with d much smaller than N. Its prior is a spherical Gaussian: a bell curve of equal width in every direction, written N(0, I).
ε
Independent noise on each neuron. Its covariance Γ is diagonal: no neuron’s noise tells you about another’s.

Because z is Gaussian and the map is linear, the data are Gaussian too: N(0, AAT + Γ). The slide labels AAT the covariance structure of the data, and links it to the principal components. Linear in, ellipse out. Whatever A you choose, the cloud is one flat ellipse.

The bent model: put a network in the middle

Real population activity bends. Tuning curves saturate. Head-direction cells trace a ring. A straight sheet cannot follow a ring. Slide 21 makes the one change that fixes this: replace the matrix with a nonlinear function fθ, a deep neural network, with weights θ.

x
Still the data, shape [N].
fθ(z)
The decoder: a network that takes z of shape [d] and returns the mean of the data, shape [N]. The slide labels it a nonlinear mapping.
ε
Independent noise, as before.

The lecture draws the data as a gray blob with a twisted shape and says the goal is to adjust the parameters until the model’s probability density matches the data (slides 22 to 27). Dots of data fall on the blob, and the model’s blob slides over them as θ changes. The final picture has the blob wrapped around the dots, labeled P(x | θml).

Try the swap yourself. The device keeps the latent bell curve fixed and slides the decoder from a straight line to an arch.

Bend the decoder

Blue dots are 160 recordings. Orange dots are 300 recordings invented by the model. Drag Bend from 0 (a straight map) to 1 (an arch). The second slider shows what the integral would cost in a bigger latent space.

0.00
1

Illustrative: both ends use the same bell-curve prior and noise of 0.2. The straight end is the line y = 0.55 − 0.35 x/1.045, a fixed tilt, not the best possible line. The average log density is the integral over z, summed on a grid of 241 values per recording. The grid cost assumes 100 points per axis.

At Bend 0 the orange cloud is a thin straight smear. Most blue dots lie far from it, so the average log density of the data is −8.7 nats. At Bend 0.5 the cloud curves, and the score rises to −2.6. At Bend 1 the cloud follows the blue arch and the score is −1.2. A higher score means the model gives the recordings more probability.

The generative model, written out

Slide 28 collects the model in a box. It has a prior over the latent, z ~ N(0, I), and a conditional for the data, x | z ~ N(fθ(z), σ2 I). Together they are the “VAE generative model”. The slide then writes the probability of one recording as the integral from Chapter 0, and names it the marginal likelihood, or “evidence”. It marks the integral intractable.

The second slider shows why. To compute the integral by a grid, you need a grid in every latent direction. With 100 points per axis and d = 1, that is 100 evaluations of the decoder per recording. With d = 3 it is a million. With d = 20 it is 1040. Even for d = 1, once the decoder is a network, there is no formula for the posterior p(z | x, θ) that EM needs in its E-step. Chapter 2’s fix works here: do not compute the likelihood, climb a lower bound.

That is the plan slide 28 states in its last line: maximize a tractable lower bound on log P(x | θ). Slide 27 adds a short remark. A VAE is basically a set of clever tricks for doing this. The next two chapters give the tricks, and the chapter after them assembles the bound.

Why can factor analysis never fit data that lie on a ring?

Chapter 5

A Gradient Through a Random Draw

Learn Monte Carlo averaging and the resampling trick, the two tools that let a network adjust the distribution it samples from

You throw darts at a board. Your score depends on where the darts land. Your aim decides where they land on average, but each throw wobbles. Now you want to know: if I move my aim one centimeter right, does my average score go up or down?

The trouble is that the aim only acts through the random throw. You cannot take a slope through a coin flip. Slide 29 opens a “math warmup” that fixes this, and the whole VAE rests on it. The function it studies is an average of a log probability, taken over a distribution that has its own dials.

F(φ, θ)
The score we want to raise. It has two sets of dials.
qφ(x)
The distribution we draw from, the “thrower”. Its dials are φ. E is the expectation: the average over many draws.
log p(x | θ)
The “board”: a score for each landing spot x, with its own dials θ.

The slide poses two questions. How would you maximize F over θ? And how would you maximize it over φ? (The slides write x for the thing being drawn. In the VAE, that thing will be the latent z.)

Question 1: the board’s dials, by Monte Carlo

The first question is easy, and the slide says so. Swap the order of differentiation and integration, so the slope sits inside the average.

That gives ∂F / ∂θ = ∫ q(x | φ) [ ∂ log p(x | θ) / ∂θ ] dx. This is again an average over q, so you can estimate it with Monte Carlo integration: draw k samples xi from q, compute the slope at each, and average. The slide boxes the recipe: xi ~ q(x | φ), then (1/k) Σi ∂ log p(xi | θ) / ∂θ. Use these slopes to climb.

Monte Carlo works because averages of random draws settle down. The error shrinks like 1/√k. Lecture 18 covers it in depth, and so does the Monte Carlo lesson. Here we only need the recipe.

Question 2: the thrower’s dials, and why they are hard

The second question is the trap. The slide shows it in blue and writes “Hmmm… idea below no longer works”. If you take the slope with respect to φ, the dials sit inside q, so the swap above no longer leaves a clean average. The samples themselves depend on φ. After you have drawn xi, nothing in your computer records how it came from φ. There is no way to take derivatives with respect to φ.

The slide’s solution is the resampling trick (the VAE papers call it the reparametrization trick). It works when q is a Gaussian with mean φ1 and variance φ2. The idea: split the throw into a fixed wobble and your aim. The slide says, do not sample xi from N(φ1, φ2) directly. Instead:

  1. Draw εi from the standard Gaussian N(0, 1). It has no dials.
  2. Transform it: xi = φ1 + φ21/2 εi. This has exactly the distribution N(φ1, φ2), but now φ appears in a formula.
  3. Plug into the average: ∂F / ∂φ ≈ ∂/∂φ [ (1/k) Σi log p(φ1 + φ21/2 εi | θ) ]. Now the slope with respect to φ is an ordinary derivative.

The slide’s summary has four bullets. Use Monte Carlo integration to evaluate the integral. Sample from a fixed distribution. Transform to get samples of the desired distribution, so the dependence on φ becomes explicit. Then take the derivative with respect to φ.

One worked number

Take the board g(x) = log p(x | θ) = −(x − 2)2, with its peak at x = 2. Let the thrower have φ1 = 0.5 and φ2 = 1. Use k = 3 wobbles: ε = 0.4, −0.9, 1.1. The samples are x = 0.5 + ε = 0.9, −0.4, 1.6. The slope of g at each is −2(x − 2) = 2.2, 4.8, 0.8. The slope of F with respect to φ1 is the average, which is 2.6. The exact answer is −2(0.5 − 2) = 3.0. The estimate is a little low, because k = 3 is small, but it points the right way.

Throw, then take the slope

Top: k wobbles ε (grey) become samples x (purple) by a shift and a stretch. Bottom: 400 repeats of the slope estimate for the mean φ1, by the resampling trick (teal) and by a noisier method that does not use it (yellow). Change k and press Draw again.

0.5
1.0
5

Illustrative board: g(x) = −(x − 2)2, so the true slope of F with respect to φ1 is −2(φ1 − 2). The yellow method is the score-function (REINFORCE) estimator, the other standard route, not in the slides. Both are unbiased; they differ in spread. Draws are seeded and computed live.

Both estimators aim at the same true slope (the dashed line), and both average to it. The teal histogram is narrow. The yellow one is wide. With k = 5 the yellow spread is several times larger, so a learner using it takes jittery steps. The resampling trick has low spread because it sends the slope of the board straight through the sample, instead of weighing noisy scores.

The failure to expect is the symptom of training with a noisy slope: the loss curve zigzags and the encoder learns slowly. The measurement is the spread you just read off. The fix is the resampling trick, which a VAE uses for the encoder’s dials in Chapter 7.

Why can we not differentiate F with respect to φ if we sample x directly from q(x | φ)?

Chapter 6

The VAE as Two Networks

Follow one recording through the encoder, a random draw and the decoder, and see why the E-step as first written fails

Take one recording of 100 neurons. Ask a colleague: what hidden state was the animal in? A good colleague does not answer with a single number. She says, “probably near here, give or take this much.” That answer is a bell curve over z: a center and a width. This chapter gives the VAE such a colleague, built from a neural network.

The old model, and the new one

Slide 36 shows probabilistic PCA, the straight special case of factor analysis with equal noise on every neuron. Draw z from N(0, I). Compute Az. Add noise of variance σ2. Equivalently, x ~ N(Az, σ2I). The PCA lesson teaches the plain version of this.

Slide 37 gives the VAE version. Swap Az for a network fθ. The generative model is z ~ N(0, I), then x ~ N(fθ(z), σ2I). This network is the generative network, or decoder. It maps z of shape [d] to a mean for the data of shape [N].

The slide then adds the new part, boxed under the heading Recognition. Chapter 1 told us the exact posterior p(z | x, θ) is out of reach. So approximate it with a bell curve whose center and width come from a second network that reads x.

qφ(z | x)
The recognition distribution: your guess about z after seeing x. The network that produces it is the recognition network, or encoder.
gφ1(x)
A network that takes x, shape [N], and returns the center of the bell, shape [d]. Its weights are φ1. The slide labels it “mean”.
Hφ2(x)
A second network that returns the width (the covariance) of the bell, with weights φ2. The slide labels it “cov”.
p(z | x, θ)
The true posterior. We never compute it. q is the stand-in.

Before, q had its own dials φ for each recording. Now the dials are the weights of one network that serves every recording. You show it x, and it hands back that recording’s center and width. This sharing is often called amortized inference: the cost of finding a good q is paid once, in training, rather than once per recording.

The code below is the whole architecture. Read the shapes in the comments.

class VAE(nn.Module):
    def __init__(s, N=100, d=2, H=64):
        super().__init__()
        s.enc = nn.Sequential(nn.Linear(N, H), nn.Tanh())   # x [B,N] -> h [B,H]
        s.mu  = nn.Linear(H, d)                             # h -> center of q   [B,d]
        s.lv  = nn.Linear(H, d)                             # h -> log variance  [B,d]
        s.dec = nn.Sequential(nn.Linear(d, H), nn.Tanh(), nn.Linear(H, N))  # z [B,d] -> mean of x [B,N]
    def forward(s, x):
        h = s.enc(x); mu, lv = s.mu(h), s.lv(h)
        z = mu + torch.exp(0.5 * lv) * torch.randn_like(mu) # the resampling trick
        return s.dec(z), mu, lv

The device runs this flow on the finished VAE from the hero (the bent decoder, trained when the page loaded). Pick a recording, then press Next stage to walk through it. The model is tiny: x has 2 numbers and z has 1.

Follow one recording

Choose a recording, then press Next stage six times. Press Redraw ε to see the random draw change z and the rebuilt x̂.

12

Real numbers from a tiny VAE trained in your browser on 160 illustrative recordings: encoder 2 → 8 tanh units → (mean, log variance), decoder 1 → 8 tanh units → 2. Noise variance fixed at 0.04. The recordings are made up for this page.

At stage 2 the encoder returns a mean and a variance. For recordings in the middle of the arch the variance is small: the encoder is confident. At stage 4 the draw turns that bell into one z. Stage 5 decodes it. Redraw ε a few times: z jitters, and x̂ slides along the arch by a small amount.

Variational EM in theory: one step breaks

Slide 38 writes out variational EM for this model. The E-step trains the recognition networks gφ1 and Hφ2 to minimize KL( qφ(z | x) ‖ p(z | x, θ) ). The M-step trains the generative network fθ to maximize ∫ qφ(z | x) log p(x | z, θ) dz. By Monte Carlo that is about (1/k) Σj log p(x | zj), with zj drawn from q. With Gaussian noise, log p(x | zj) is minus (1 / 2σ2) times the squared error between x and fθ(zj), plus a constant. So the M-step is a squared-error fit.

Slide 39 crosses out the E-step in red and marks the M-step OK. Slide 40 explains: the M-step is fine, but the E-step is not. It is not obvious how to minimize that KL. The KL contains p(z | x, θ), whose normalizer is the intractable integral from Chapter 4. And q depends on φ only through its random draws, which is Chapter 5’s trap.

The slide’s alternate approach is the reparametrization trick. To get zj from N(gφ1(x), Hφ2(x)), draw εj from N(0, I), then compute zj = Hφ2(x)1/2 εj + gφ1(x). That is exactly stage 3 and 4 in the device. Now zj is a formula in φ, so a slope can flow from the loss back through the decoder and into both recognition networks.

Read this as the failure and its repair. The symptom: the E-step as written gives the encoder nothing to learn from. The measurement: to score the KL to the posterior you need the evidence, which you cannot compute. The fix comes next chapter: use the ELBO’s other form, in which every term can be computed, and differentiate the whole bound with the trick.

What does the recognition network return for a recording x?

Chapter 7

The VAE Objective

Rewrite the ELBO as a rebuild cost plus a pull toward the prior, compute both terms, and see the tug of war between them

Two coaches shout at the encoder. The first says: be exact. Tell the decoder precisely where this recording lives, so it can rebuild the recording well. The second says: stay simple. Keep your answer close to the plain bell curve the model uses when it invents data. The VAE objective is the sum of those two shouts. The slides call it the key expression, and this chapter derives it from the ELBO in Chapter 1.

Deriving the objective, line by line

Slide 41 uses a third form of the ELBO. Take N recordings x1 to xN. The log likelihood is the sum of log p(xi), one per recording. Work on one recording and drop the index.

  1. Start from log p(x) = log ∫ p(x, z | θ) dz.
  2. Multiply and divide by q(z | x) inside the integral. Jensen’s inequality (Chapter 1) then gives log p(x) ≥ ∫ q(z | x) log [ p(x, z | θ) / q(z | x) ] dz.
  3. Split the joint as p(x | z, θ) p(z). The log of the ratio becomes log p(x | z, θ) + log [ p(z) / q(z | x) ].
  4. The first part is an average of the decoder’s log probability. The second part, averaged under q, is minus a KL divergence.
log p(x)
The log likelihood of one recording, the number the model wants to raise.
Eq[ log p(x | z, θ) ]
The reconstruction term: how well the decoder explains x from z drawn by the encoder. With Gaussian noise it is minus the squared error divided by 2σ2. The slide marks the other two pieces with arrows: the encoder’s bell N(g(x), H(x)) and the prior N(0, I).
KL( q ‖ p )
The prior penalty: how far this recording’s bell sits from the model’s prior N(0, I). Note that this is the KL to the prior, not to the posterior of Chapter 1, and every part of it can be computed.

This is the VAE objective. It is the same ELBO as before in a different form. Chapter 1’s Form 1 was the ceiling minus a KL to the posterior, and that KL cannot be computed. This form trades it for a KL to the prior, and that one can.

The KL has a formula

The slide notes that there is an analytic formula for the KL between two Gaussians. Here q = N(g(x), H(x)) and the prior is N(0, I). For one latent number with mean μ and variance σ2, the formula is KL = ½ ( μ2 + σ2 − ln σ2 − 1 ). With d latent numbers, add this up over the d numbers.

Check it with μ = 1 and σ = 0.5. Then μ2 = 1, σ2 = 0.25 and −ln 0.25 = 1.386. The KL is ½ (1 + 0.25 + 1.386 − 1) = 0.818 nats. It is zero only when μ = 0 and σ = 1, when q is the prior itself.

The reconstruction term has no formula, because fθ is a network. Slide 43 estimates it by Monte Carlo (the label MC integration) and applies the trick of Chapter 5: for each recording i draw k wobbles εij, set zij = H(xi)1/2 εij + g(xi), and average the decoder’s log probability. Slide 46 adds that in practice you often use one sample, k = 1: one draw per recording per step.

Tug of war

You are the encoder for one recording. Set the center μ and the width σ of your bell. The orange bar is the rebuild cost, the yellow bar is the prior penalty, and the loss is their sum. Press Use the trained encoder’s bell to see what training chose.

12
0.00
1.00

The decoder is the tiny VAE trained in your browser when the page loaded. The rebuild cost is a 400-draw Monte Carlo average of the squared error over 2σ2 with noise variance 0.04. The KL uses the closed formula; the second read-out checks it against 5,000 draws. Illustrative recordings.

Start at μ = 0 and σ = 1. The KL is zero: your bell is the prior. But the rebuild cost is large, because the decoder has no idea where this recording sits. Now shrink σ and move μ toward the encoder’s own choice. The rebuild cost falls, and the KL rises. The loss is lowest somewhere in between, near the trained encoder’s bell.

Slide 42 carries a warning in red: this does not mean the VAE is trying to make q(z | x) equal p(z). Each recording keeps its own bell. The KL is only a pull. If it won outright, every recording would get the same bell, the code would say nothing about x, and the decoder would output the average recording. The symptom is a KL near zero and rebuilds that ignore x. Its measurement is the KL term per recording. Common remedies (not from the slides) are to let the KL weight grow slowly from zero at the start, or to weaken the decoder.

The learning algorithm

Slide 44 gives it in four lines. (1) Sample the wobbles εij, for i = 1 to N and j = 1 to k. (2) Compute the gradient of the objective with respect to θ, φ1 and φ2. (3) Take a small step along it. (4) Repeat until it converges. The slide highlights the key expression:

(1/k) Σ (1 / 2σ2) ‖ x − f(…) ‖2
The squared reconstruction error, averaged over recordings i and wobbles j. This is the term to push down. The KL term is added to it.
H1/2 ε + g
The resampling trick. The slide marks εij as N(0, I), so a slope can flow from the error, through the decoder fθ, into gφ1 and Hφ2.

A single training step on a batch of B recordings therefore does the forward pass of Chapter 6, scores the reconstruction error plus the KL, and updates all three networks at once. The hero ran exactly this loop in your browser, with 32 recordings per step.

What would happen if the KL penalty to the prior completely dominated the reconstruction term?

Chapter 8

Putting It All Together

Assemble the encoder, the draw and the decoder into one training loop, then read what the lecture’s results show

You now hold every part. A recording goes into the encoder and comes out as a bell. A wobble turns the bell into one z. The decoder turns z back into a rebuilt recording. A cost, the rebuild error plus a pull toward the prior, tells all three parts how to change. Slide 45 draws the whole thing on one page under the title putting it all together.

Reading the boxed expression

The slide starts with the ELBO as an integral in a box. Below it, the same quantity appears as the Monte Carlo sum from Chapter 7 minus the KL, and red labels point to each network. There are three networks, not two.

The instruction on the slide is short: differentiate with respect to θ, φ1 and φ2, and take gradient steps. A modern library does the differentiating for you. You write the forward pass and the loss, and it applies the chain rule through the decoder, through z = μ + σε, and into the encoder.

def vae_loss(model, x, sigma2=0.04):            # x [B, N]
    xhat, mu, lv = model(x)                      # [B, N], [B, d], [B, d]
    rec = ((x - xhat) ** 2).sum(1) / (2 * sigma2)        # [B]  rebuild cost
    kl  = 0.5 * (mu ** 2 + lv.exp() - lv - 1).sum(1)     # [B]  prior penalty
    return (rec + kl).mean()                     # the negative ELBO per recording

opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(2500):
    x = data[torch.randint(len(data), (32,))]    # a minibatch of 32 recordings
    loss = vae_loss(model, x)                    # one wobble per recording: k = 1
    opt.zero_grad(); loss.backward(); opt.step() # slopes reach theta, phi1, phi2

The second slide of the pair adds the geometric picture. On the left sits z-space with a round cloud of latents. A recording xi in the data blob on the right is sent through the encoder, giving the pair gφ1(xi) and Hφ2(xi), a small red patch in z-space. The wobble picks a point zij in the patch. The decoder fθ maps zij back to a point x̂ij. The cost compares xi with x̂ij by squared error. The slide adds that in practice you often use one sample, k = 1.

The device replays the training of the hero’s bent VAE. Slide the training step to see the decoder bend into the data, and slide z to see where it lands.

Replay the training

Top: the decoder’s curve at the chosen training step (orange), the recordings (blue) and the point it makes for your z (purple). Bottom: the loss over 2,500 steps, split into the rebuild cost and the prior penalty. Drag both sliders.

2,500
0.80

A real run: the same tiny VAE as the hero (encoder 2 → 8 tanh → mean, log variance; decoder 1 → 8 tanh → 2), Adam with rate 0.01, 32 recordings per step, one wobble each, noise variance 0.04. Loss values are averages over the 100 steps around the chosen step. The recordings are made up for this page.

At step 0 the decoder is a random squiggle and the loss is above 15 per recording. By step 300 the curve lies on the arch, and the loss is near 2.6: 0.7 of rebuild cost and 1.9 of prior penalty. After that the loss is flat. Now drag z. Near 0 the decoder lands on the crest of the arch, where most recordings are. Past ±2.5 the prior density is under 5% of its peak, and the decoder has seen almost no training signal there. That is why samples from the prior come out well, but only where the prior has weight.

The results slides

Slides 47 and 48 show figures from Kingma and Welling (2014) on handwritten digits (MNIST). The first is a learned manifold for a 2-D latent z. The decoder fθ(z) is evaluated on a grid of z values, and the digit images vary smoothly across the grid: neighboring z give similar digits. The next figure shows random samples for latent sizes of 2, 5, 10 and 20. A row of plots follows, of the lower bound against the number of training samples evaluated, for several latent sizes. These plots are the ELBO of this chapter, measured as training proceeds.

Slide 49 shows a result from Rezende, Mohamed and Wierstra (2014). The encoder gφ1 maps digit images from x-space into a 2-D z-space. In the picture the embedded points form colored clusters. The slide gives no color key, but the colors appear to mark digit classes, and a model trained on pixels alone has no class labels. Both results point the same way: a smooth, low-dimensional latent learned from pixels alone gathers similar digits together.

Now the failure that this chapter’s loss makes easy to see. The factor 1 / (2σ2) multiplies the rebuild error, so σ2 sets the exchange rate between the two terms. The symptom of a σ2 that is too big is blurry outputs that look like the average recording. The measurement is the KL falling toward zero while the error stays high. The fix is to set σ2 near the real noise level in the data, or to learn it.

In one training step of a VAE, which parts receive a gradient?

Chapter 9

VAEs for Spike Trains

Swap the Gaussian output for a Poisson one, put a dynamical system on z, and read the lecture’s summary

You record 30 neurons for 60 time bins. The raw data is a grid of whole numbers: how many spikes each neuron fired in each bin. Behind that grid, the lecture’s neuroscience example posits something small and smooth: a latent path z(t), a point that glides through a plane as time passes. Every neuron’s firing rate is a function of where the point is.

The lecture’s example

Slide 50, credited to Gao, Archer, Paninski and Cunningham (2016), draws the model as three boxes in a row. On the left, the prior p(z) is a linear dynamical system (LDS): z at one time step is a fixed rotation and shrink of z at the previous step, plus a little noise. The Kalman filter lesson teaches this kind of model in depth. In the middle sits a deep network fθ. On the right is a raster of spike trains, with the relation x | z ~ Poisson( fθ(z) ).

This is the VAE of the last chapters with two changes, and both are the point of the example. First, the prior is not a round bell curve but a path through time, so the latent has structure. Second, the output is not Gaussian but Poisson, because spike counts are non-negative whole numbers. Slide 51 plays a video of the fitted model. We do not reproduce it. The device below builds the generative half from scratch.

A Poisson distribution describes counts of events that arrive at random with a given average rate. If a neuron’s rate in a bin is 2.1 spikes, the Poisson says it fires 0, 1, 2, 3 or more spikes, with the most likely counts near 2. Its variance equals its mean, and it never gives a negative count.

Steer a population with two numbers

Top: the latent path z(t) in 2-D, from a rotating linear dynamical system. Bottom: spike counts, one row per neuron and one column per bin; darker means more spikes. Choose the output kind, then change the rotation speed and the number of neurons.

0.25
30

Illustrative generative model, ours and not the paper’s: z(t+1) = 0.97 R(ω) z(t) plus noise, log rate = −0.2 + 1.1 (ai · z), with ai a random unit vector per neuron. The Gaussian case draws from N(rate, rate), so it has the right mean and variance. Seeded draws.

Drag ω slowly. The path in the top panel sweeps round faster or slower, and the rows of the raster brighten and dim in waves that move together. Raise N to 60: more rows, the same two hidden numbers behind them. Two numbers per time bin steer all the neurons. That is the low-dimensional structure that the VAE is built to find.

Now switch to Gaussian output. The mean and the variance stay the same, so on average the picture looks alike. But many bins now show red marks: negative spike counts. A neuron cannot fire −0.8 spikes. The read-out counts them.

What changes in the loss

Only the reconstruction term of Chapter 7 changes. With a Gaussian output it was the squared error divided by 2σ2. With Poisson output it is the negative log of the Poisson probability, summed over neurons: Σn ( λn − xn log λn + log xn! ), where λn = fθ(z)n is the decoder’s predicted rate for neuron n and xn is its observed count. The last term does not depend on the network and can be dropped. The KL term, the encoder and the resampling trick stay as they were.

lam = torch.nn.functional.softplus(model.dec(z))      # [B, N]  rates, always above 0
rec = (lam - x * torch.log(lam)).sum(1)               # [B]  Poisson cost (dropping log x!)
loss = (rec + kl).mean()                              # same KL, same trick, same loop

Read the failure through the Gaussian case. The symptom: the model assigns probability to counts below zero, and, if its spread is one fixed number, treats a neuron firing 0 spikes with the same spread as one firing 10. The measurement is the Fano factor, the variance divided by the mean of the counts. A Poisson count has a Fano factor of exactly 1, and real spike counts are often near that or above it. A Gaussian with a fixed spread ignores the link between rate and variability. The fix is the Poisson output, as slide 50 shows.

The summary slides

Slides 52 to 54 build up one summary, in two boxes. The first, in red, is black-box variational inference (BBVI): maximize the ELBO as an approximate way to fit by maximum likelihood, and estimate the integrals by Monte Carlo. The second, in blue, is the VAE: use the reparametrization trick, and use deep networks to parametrize the generative model p(x | z) and the recognition distribution q(z | x).

The last slide lists many extensions: structured priors for p(z), as in this chapter’s LDS; other parametrizations of q(z | x); non-Gaussian outputs, as with Poisson counts; sequential models for time series, with LFADS as the example the slide names; and control variates, alternative objectives and improved training methods. The LFADS lesson carries the sequential VAE for neural populations further, and the latent variable models lesson before it sets the stage for brain–computer interfaces.

You move a VAE from Gaussian pixel outputs to spike counts. Which part of the objective changes?

Chapter 10

The Lecture on One Page

Keep the numbers, the terms, the checklist and the core code, then follow the links onward

Here is the whole lecture in one paragraph. When a latent variable model has no exact E-step, you fit it by climbing a lower bound on the log likelihood, the ELBO, which you can always compute. Variational EM does that with a q you choose. A VAE does it with deep networks: a decoder for p(x | z), an encoder for q(z | x), one loss made of a rebuild cost and a KL to the prior, and the resampling trick to carry slopes through the random draw. For spikes, swap the Gaussian output for a Poisson one.

The numbers to keep

QuantityValueWhere it comes from
Course and sessionNEU 560, Lecture 20, Spring 2024, 54 slidesThe course deck
VAE co-inventorsKingma and Welling; Rezende, Mohamed and Wierstra, both 2014Slide 16
The two ELBO formslog p(x) minus KL to the posterior; average log joint plus entropy of qSlide 4, Chapter 1
Two-cause toylog p(x) = −1.661; at q = 0.3 the gap is 0.226 and F = −1.887Our toy, Chapter 1
Loose-bound climbstops at θ = −1.154 with gap 0.723, while the likelihood peaks at −1.499Our toy, Chapter 2
Straight vs bent decoderaverage log density −8.7 (straight) against −1.2 (arch)Our toy, Chapter 4
Grid cost of the evidence100d decoder runs per recording: 1040 at d = 20Chapter 4
Slope spread, k = 5resampling trick about 3.6 times steadier than the score-function methodOur toy, Chapter 5
KL of N(1, 0.5²) from N(0, 1)0.818 natsClosed formula, Chapter 7
Hero training, 3,000 stepsloss 5.4 (straight decoder) against 2.6 (bent decoder) per recordingOur toy, hero

The terms, in plain words

TermPlain meaning
Latent variable zA hidden number the model assumes drove the data.
Marginal likelihoodThe probability of the data after adding up over every z.
ELBO (negative free energy)A computable number that never exceeds the log likelihood.
KL divergenceZero when two distributions match, positive otherwise.
Variational approximation qA stand-in for the true posterior, from a family you can compute with.
Recognition networkThe encoder: reads x and returns the center and width of q.
Generative networkThe decoder: turns z into the mean of x.
Resampling trickWrite z as mean plus width times a fixed-bell wobble, so slopes flow through.
Black-box variational inferenceMaximize the ELBO using Monte Carlo draws, with no model-specific algebra.

A checklist for building one

  1. Write the generative model. A prior p(z), and an output distribution for x given z that suits the data: Gaussian for real values, Poisson for counts.
  2. Pick the recognition family. A Gaussian with a mean and a variance, both produced by networks that read x.
  3. Write the loss. The negative log probability of x under the decoder, plus the KL of q to the prior.
  4. Draw z with the trick. z = mean + sd × ε, with ε from N(0, I), one draw per recording.
  5. Train all networks on one loss. Report the rebuild cost and the KL separately.
  6. Check the failure signs. A KL near zero and blurry outputs mean collapse. A large rebuild cost means the decoder or the noise setting is off.

The core as code

import torch, torch.nn as nn

class VAE(nn.Module):
    def __init__(s, N=100, d=2, H=64):
        super().__init__()
        s.enc = nn.Sequential(nn.Linear(N, H), nn.Tanh())
        s.mu, s.lv = nn.Linear(H, d), nn.Linear(H, d)        # mean and log variance of q(z|x)
        s.dec = nn.Sequential(nn.Linear(d, H), nn.Tanh(), nn.Linear(H, N))
    def forward(s, x):                                       # x [B, N]
        h = s.enc(x); mu, lv = s.mu(h), s.lv(h)              # [B, d] each
        z = mu + torch.exp(0.5 * lv) * torch.randn_like(mu)  # resampling trick
        return s.dec(z), mu, lv                              # rebuilt [B, N]

def neg_elbo(model, x, sigma2=0.04):
    xhat, mu, lv = model(x)
    rec = ((x - xhat) ** 2).sum(1) / (2 * sigma2)            # Gaussian output
    kl = 0.5 * (mu ** 2 + lv.exp() - lv - 1).sum(1)          # closed-form KL to N(0, I)
    return (rec + kl).mean()

model = VAE(); opt = torch.optim.Adam(model.parameters(), 1e-3)
for step in range(10000):
    x = data[torch.randint(len(data), (64,))]
    loss = neg_elbo(model, x); opt.zero_grad(); loss.backward(); opt.step()

Where it sits, and where to go next

The VAE is the end point of a chain you can walk backward. Probabilistic PCA and factor analysis are its straight special case (PCA). EM for a mixture is its exact-E-step ancestor (EM for Gaussian mixtures, and lectures 16 and 17). Monte Carlo is its engine (lecture 18 and the Monte Carlo lesson). The linear dynamical prior of Chapter 9 is the Kalman filter’s model (Kalman filter), and Poisson outputs come from the generalized linear models lesson.

To go further, try microVAE, which takes the VAE to discrete tokenizers, and autoencoders, which gives the plain compressor of Chapter 3. For neural data, see latent variable models for BCIs and LFADS.

The takeaway. You cannot compute how likely your data are, but you can compute a floor under it. Raise the floor with one loss and one trick, and the encoder, the decoder and the hidden variable all learn together.

Credit and sources

This lesson re-teaches Lecture 20 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow, and follows his slides in order: slides (PDF). All the pictures, devices and toy numbers here are our own. Sources named in the slides: D. Kingma and M. Welling, “Auto-encoding variational Bayes”, ICLR 2014 (arXiv 1312.6114); D. Rezende, S. Mohamed and D. Wierstra, “Stochastic backpropagation and approximate inference in deep generative models”, ICML 2014 (arXiv 1401.4082); C. Doersch, “Tutorial on variational autoencoders”, 2016 (arXiv 1606.05908); and Y. Gao, E. Archer, L. Paninski and J. Cunningham, “Linear dynamical neural population models through nonlinear embeddings”, NeurIPS 2016.

Open Teach in the dock above and explain the resampling trick on a whiteboard, as if to a friend. Then go back to the hero, train the bent decoder once more, and watch the loss settle near 2.5.

Which loss does a VAE minimize for one recording, in the form the lecture uses?
NEU 560, Lecture 20: Variational EM and VAEs
Course site · Slides (PDF) · Back to Gleams