Variational Inference
A deliberate break from new RL algorithms. Levine builds up latent variable models, shows why maximum-likelihood training of them is intractable, and derives the evidence lower bound — including the exact decomposition showing that maximizing it both tightens the bound and raises the likelihood. Amortizing the posterior into a network and adding the reparameterization trick yields the variational autoencoder, and the lecture closes with the RL payoffs: learned state representations, multimodal policies, and latent state-space models.
Latent variable models: complex distributions from simple pieces
This lecture covers no new RL algorithm — deliberately. Variational inference “comes up again and again” across model-based RL, inverse RL, and exploration, and it has “a very deep connection to reinforcement learning and learning-based control” that next week’s control-as-inference lecture makes precise. Today is the tooling.
A probabilistic model is anything representing a distribution: fit to observed points, or a conditional — the course has been full of these, since every policy is a conditional probabilistic model.
The conditional version already appeared in lecture 2: the mixture density network for multimodal imitation (driving around the tree) is , with the network emitting the mixture means, variances, and weights. Whether depends on , or does, is a design choice.
In general the recipe is: a prior from some simple class (categorical, or a Gaussian), and a conditional that is also simple as a distribution — say — even though its parameters are arbitrarily complicated neural-net functions of . “Simple” here means explicitly parameterizable: a single Gaussian can capture perfectly and can represent , but no single Gaussian captures itself, which is
RL supplies the motivating cases: multimodal policies with a noise input , and the latent state models from the model-based RL lectures, where the “prior” over latents is structured — it models and , not just an isotropic Gaussian. The lecture returns to those at the end.
Why training them is hard
Given data and a model , the natural objective is the maximum likelihood fit. Substituting the latent variable decomposition:
That integral, evaluated every gradient step, is “completely intractable” for continuous . Even in the discrete-mixture case where you can sum over components, you often don’t want to — the resulting optimization landscape has “very poor numerical properties.”
The alternative — stated first, justified later — is the expected log likelihood:
The intuition: treat the latents as missing halves of the data. “Guess” the that goes with each and pretend it’s the right one — except that many ‘s are plausible, so average over the whole posterior instead of committing to one. And this objective is tractable in exactly the way the original wasn’t: the log of an integral doesn’t decompose, but an expectation of a log can be estimated by sampling and averaging — the same move policy gradient made. Everything now hinges on one question: how do we get ?
The variational lower bound
The posterior is in general complex — a single can come from many places in -space. The variational move is a crude approximation: fit some from a simple tractable class, say a Gaussian , one per data point. The slides are blunt about it: “this is incorrect but very convenient.” What makes it more than convenient is that any yields a lower bound on . Multiply and divide by inside the integral, recognize an expectation, and apply Jensen’s inequality (, since is concave):
The right-hand side is the evidence lower bound (ELBO), written . Every term is tractable: the expectation by sampling from , and the entropy in closed form for a Gaussian.
How loose is the bound, and what makes a good ? Intuitively should approximate , compared in KL divergence — and writing out that KL gives the lecture’s central identity.
This immediately suggests an algorithm: alternate maximizing with respect to (tighten the bound) and with respect to (raise the likelihood). Concretely, per data point: sample , take , step , then gradient-ascend on .
From per-datapoint posteriors to amortized inference
The catch is the parameter count: a separate per data point means parameters — fine for thousands of points, intractable for the millions typical in deep learning. But every is trying to approximate the same function evaluated at a different point: the posterior. So train one inference network that outputs the posterior parameters for any , amortizing inference across the dataset. Two networks now: the generative model and the inference network .
Training works exactly as before. The new question is , where appears both as the sampling distribution of the expectation and in the entropy term. The entropy is closed-form in — easy. The first term is
The reparameterization trick
In RL we’re stuck with the likelihood-ratio estimator because we can’t differentiate through unknown dynamics. Here there are no unknown dynamics — only — so a better estimator exists. A Gaussian sample can be rewritten as a deterministic function of independent noise:
so that, as a strict equality, . Now parameterizes only deterministic quantities: sample ‘s, and backpropagate directly through and . A single sample per data point usually suffices, because this estimator uses the derivatives of — information the policy-gradient version throws away.
An even cleaner grouping: the and entropy terms together are exactly , which for two Gaussians has an analytic formula. The working form of the ELBO becomes
with one Gaussian per data point, and autodiff handles everything.
The trade-off between the two estimators: the policy-gradient form handles discrete and continuous latents ( can be any distribution with log probabilities) but has high variance, needing multiple samples and smaller learning rates. Reparameterization needs differentiable in — continuous latents only — but is simple, low variance, and works with one sample. Continuous : reparameterize. Discrete : policy gradient.
VAEs, conditional VAEs, and sequence models for RL
The variational autoencoder is the most direct instantiation: an encoder network mapping an image to over a latent vector (dimension 64 or 128, say), and a decoder mapping back to a distribution over pixels. To sample: draw from the prior and decode.
Why does decoding prior samples give valid images? The KL penalty means the encoder “would pay a very heavy price” for producing ‘s unlike prior samples — that keeps encodings inside the prior. The converse — every prior sample decoding to something valid — is an efficiency argument: the encoder “wants to be pretty frugal in its use of the latent space,” expanding its variance toward 1 to fill any unused region, so nearly every under the prior maps to some valid .
Three RL applications close the lecture:
Representation learning. Train a VAE on the states in your replay buffer (Atari images, say) and feed the Q-function instead of raw pixels. Because the prior factorizes into independent dimensions, the VAE is pushed toward disentangling the underlying factors of variation — the position and velocity of the player character and the skull in Montezuma’s Revenge, not per-pixel colors. The Higgins et al. 2017 interpolations (chairs rotating, faces relighting) show latent traversals tracking factors rather than pixel blends — though Levine notes it’s “debatable in practice” how fully VAEs achieve this. The loop also pre-trains cleanly from prior data.
Conditional VAEs for multimodal policies. Condition encoder and decoder on (the prior usually stays unconditional): the decoder is a policy taking a noise sample as extra input. These appear mostly in imitation learning — fully observed MDPs admit deterministic optimal policies, but human demonstrations are multimodal and non-Markovian (left or right around the tree, never the middle). Examples from the lecture: latent “plans” learned from free-form human play data, and a Transformer-based conditional VAE driving a real bimanual robot putting a shoe on a foot.
Sequence VAEs for partially observed systems. The latent variable is the entire sequence ; the observed variable is the trajectory of observations; and the whole thing is conditioned on the action sequence. The prior carries the dynamics — , learned, so latents correlate across time. The decoder is deliberately independent per step, , forcing the ‘s to constitute a Markovian state space. The encoder cannot be per-step — a single underdetermines — so it is the most complex piece, a sequence model (LSTM or Transformer) inferring , optionally conditioned on ; any choice yields a valid bound, better encoders just tighten it. This is the machinery behind embed-to-control’s recovered pendulum state spaces, latent-space planning from pixels, and stochastic latent actor-critic running RL in the learned state space.
Check yourself
Derivation and modeling exercises in the lecture’s spirit — work them on paper.
Without using Jensen’s inequality, derive the evidence lower bound: expand , arrive at , and state the two optimization consequences this equality delivers.
Show solution
Start from the definition and substitute : , where exits the expectation because it doesn’t depend on . The middle term is , so ; rearranging gives the identity. Consequence one: always, so — the bound, with no Jensen step. Consequence two: the left side is independent of , so maximizing with respect to must minimize the KL — the same objective simultaneously tightens the bound (over ) and raises the likelihood (over ), which is what licenses alternating ascent on a single quantity.
A model has one binary latent: , and for a particular data point, and . Compute , the true posterior, and the ELBO for (a) equal to the posterior and (b) a point mass on . Verify that each gap equals .
Show solution
, so . Posterior: , . (a) with . The expectation term is , so : the bound is tight, and indeed since is the posterior. (b) Point mass on : and . Gap: . And — exactly the gap, as the decomposition demands. Committing to the single most likely costs precisely the KL to the true posterior.
For with : (a) write both the policy-gradient estimator and the reparameterized estimator of ; (b) explain why the reparameterized one has lower variance; (c) explain why the same trick is generally unavailable for the RL objective it resembles.
Show solution
(a) Policy gradient: sample , use . Reparameterized: sample , use , valid because makes the expectation over , which is independent of , a strict equality. (b) The likelihood-ratio form treats as a black-box scalar weight — it uses only ‘s value, so noise in the samples multiplies large score terms. The reparameterized form differentiates through , injecting first-order information about how changes with ; empirically a single sample per data point suffices where the policy gradient needs many. (c) In RL the role of is played by the return, which depends on the environment dynamics: writing the trajectory as a deterministic differentiable function of policy parameters and external noise would require differentiating through , which is unknown and not assumed differentiable. In amortized VI, is just another neural network — its derivatives are available to autodiff. (The trick also fails for discrete , where is undefined; there the policy-gradient estimator remains the tool.)
You have trajectories of image observations and actions from a partially observed system and want a latent state-space model as a variational autoencoder. Identify: the latent variable, the observed variable, the conditioning information, and the factorized forms of the prior and decoder. Then explain why the decoder should be independent per time step while the encoder must not be.
Show solution
The latent variable is the whole sequence (not one latent per step in separate VAEs); the observed variable is the trajectory ; and the model is a conditional sequence VAE conditioned on the actions — the one part of the data not being modeled. The prior carries the structure: , with a unit Gaussian but the dynamics factors learned — so are not unit Gaussians, and the latent dimensions deliberately correlate across time. The decoder factorizes per step: . This is a modeling choice that forces each to summarize everything needed to render its own observation — i.e., forces the latents to form a Markovian state space; letting the decoder peek at other steps would let off the hook. The encoder cannot be per-step precisely because the system is partially observed: alone underdetermines , so the encoder must aggregate history, , typically with an LSTM or Transformer, optionally also conditioning on . Any such encoder yields a valid lower bound; richer ones give more accurate posteriors and hence tighter bounds.