Variational Inference for RL (UC Berkeley CS 285)

Half the demos pass a tree on the left, half on the right. A Gaussian policy averages them and drives into the tree. Add one hidden number z, and the same policy picks a side.

Train latent-variable policies with the ELBO. See why the encoder gradient is a policy gradient. Read conditional VAEs and diffusion policies as one idea.

Pick a policy and press Roll out 20. Then drag z and watch one plan swing from left to right. Then we build the bound, the gradient and the two RL uses that make this policy trainable.

You need behaviour cloning and the policy gradient. For VAE basics, see the NEU 560 VAE lesson. We build the rest here.

A supplement to UC Berkeley CS 185/285, Deep Reinforcement Learning, taught by Sergey Levine. It follows Lecture 11: Variational Inference, the first part of Lecture 12: VI in RL, and Section 6. The words, toys and devices are our own.

Pass the tree

0.60

The tree scene is the course's example (Lecture 11, slide 4; Lecture 12, slide 15). The field, demos and policies are an illustrative toy. The latent policy steers by tanh(4z), with z from N(0, 1).

Chapter 0

A Hidden Variable Lets a Policy Pick a Side

See why one bell per state averages two good plans, and write the fix as an integral you cannot compute

Twenty drivers pass a tree. Ten go left and ten go right. You fit a policy to their actions by behaviour cloning: supervised learning from states to the expert's actions. At the fork, half the labels say "steer left" and half say "steer right".

A Gaussian policy outputs one mean and one spread for each state. For a 50/50 split, the best single bell puts its mean at zero: straight ahead, into the tree. This is the averaging trap of the imitation learning lesson. CS 285 fixes it with a hidden variable.

A policy is a conditional model p(a | s), like any p(y | x). Give it a latent variable z: a hidden number the policy draws first, like a driver's private choice of side. The policy draws z from a prior p(z), here the bell N(0, 1). A network, the decoder, then turns (s, z) into one simple bell over actions.

Say it aloud

p of a given s equals the integral over z of p of a given s and z, times p of z, d z.

p(a | s)
p of a given s the policy: how likely action a is in state s.
∫
the integral over z add up over every value of z, each weighted by how likely it is.
p(a | s, z)
p of a given s and z the decoder: one bell with mean tanh(4z) and width σ = 0.1 in our toy.
p(z)
p of z the prior over the hidden number: N(0, 1).
dz
d z marks z as the variable we add up over.
In plain words

Draw many values of z from the prior p(z). For each z, ask the decoder how likely action a is. The average of those answers is p(a | s).

With numbers

With made-up numbers: four draws z = −0.8, 0.1, 0.5, 1.3 give decoder means −1.00, 0.38, 0.96, 1.00. For a = 1 with σ = 0.1, the decoder values are 0.00, 0.00, 3.74 and 3.99. Their average is 1.93. The exact integral is 1.44, so four draws miss by a third.

Build p(a | s) from simple bells

Grey bars are demo actions at the fork. The dashed warm curve is the best single Gaussian fit. Purple is the average of M decoder bells. Add bells, change their width, and watch the mass over the red tree zone.

40
0.10

Illustrative toy: 40 demo actions at ±1 with jitter 0.1, and a decoder mean of tanh(4z). The tree zone is within 0.3 of straight ahead.

Training wants log p(ai | si) for each demo, and the integral sits inside the log. A grid sum works in one dimension, not for a 32-number z. Prior draws mostly land on z values that explain nothing. The course calls exact maximum likelihood here "completely intractable".

The failure. Symptom: a cloned policy freezes at forks or takes the middle path. Measure: plot the demo actions at one fork state; two humps with an empty middle mean a single bell will average. Fix: a latent-variable policy, trained with the bound from Chapter 1.

The road

  1. The ELBO and its gap: a bound you can compute, and what its two terms pull.
  2. The encoder gradient: amortise, then choose the score function or the reparameterisation trick.
  3. VAEs inside RL: codes for a Q-function, and conditional VAE policies.
  4. Diffusion as a chain of latents: why more steps stop the averaging, and world models over time.
  5. The field guide: terms, numbers, code, links and the course credit.
Half the demos steer left of the tree and half steer right. Why does a Gaussian behaviour-cloning policy hit the tree?

Chapter 1

The ELBO and Its Gap

Swap the log-likelihood you cannot compute for a bound you can, and see what each of its two terms pulls

Write xi for one data point; in a policy it is the demo action, and the state rides along. You cannot compute log p(xi). So guess which z made xi with a bell qi(z) = N(μi, σi). The course calls this guess wrong but convenient.

Jensen's inequality says the log of an average is at least the average of the log. It gives log p(xi) a lower bound, the ELBO (evidence lower bound). The NEU 560 lesson derives it.

Say it aloud

L-i equals the expected value, over z drawn from q-i, of log p of x-i given z plus log p of z, plus H of q-i.

ℒi
L-i the ELBO for data point i, in nats.
Ez∼qi
the expected value over z from q-i the average over many draws of z from the guess qi.
log p(xi | z) + log p(z)
log p of x-i given z plus log p of z the log joint: how well z explains xi, plus how plausible z is.
ℋ(qi)
H of q-i the entropy of qi, minus the average of log qi: how spread out the guess is. For a bell it is ½ log(2πeσ2).
In plain words

Draw z from qi and score each draw by the log joint. Average the scores. Add the entropy H(qi) as a bonus for width.

With numbers

In the made-up toy below, q = N(1.5, 0.52). The average log joint is −3.234 and the entropy is 0.726. So ℒ = −3.234 + 0.726 = −2.508 nats.

The first term alone pulls q onto a spike at the mode. The entropy pushes q wide. Together they make q cover the tallest bump.

Say it aloud

log p of x-i equals the KL divergence from q-i of z to p of z given x-i, plus L-i.

log p(xi)
log p of x-i the evidence. It depends on the model, not on the guess qi.
DKL(q ‖ p)
the KL from q to p the average under q of log q minus log p. It is zero only when q equals the true posterior p(z | xi), and positive otherwise. This lesson always puts q first.
ℒi
L-i the ELBO from the line above.
In plain words

The evidence log p(xi) is the bound ℒi plus a gap, the KL. The evidence does not move when q moves, so raising ℒi shrinks the gap.

With numbers

In the toy, log p(xi) = −2.000 (made up). At q = N(1.5, 0.52), ℒ = −2.508, so the gap is 0.508 nats. The posterior puts 0.6 on that hump, and −ln 0.6 = 0.511: the gap is the cost of the weight q leaves out.

Pull the two terms of the ELBO

Pink is the true posterior over z. Purple is your guess q. Move q and read the bars against the dashed ceiling.

0.00
1.00

Illustrative toy: the posterior is 0.6 N(1.5, 0.52) + 0.4 N(−1.5, 0.52), with log p(x) set to −2. Terms use a 2,001-point grid.

Try the presets. The spike loses 1.577 nats of entropy. The wide bell over both humps scores −2.975. The best single bell sits on the 0.6 hump at −2.508. This is the mode-seeking habit of KL(q ‖ p): one real hump beats a blur between two.

The failure. Symptom: the ELBO rises but samples do not improve. Measure: the ELBO is only a floor, so estimate log p directly on a few held-out points. Fix: give q more shapes, such as the chain of Chapter 4.

In the toy, q sits on the right hump and ℒ is 0.508 below log p(x). What is that 0.508?

Chapter 2

The Encoder Gradient Is a Policy Gradient

Share one encoder across all the data, then choose between the score-function and the reparameterised gradient

Chapter 1 gave every data point its own μi and σi, so the parameter count |θ| + (|μi| + |σi|) × N grows with the data. A million replay states with a 32-number z need 64 million extra numbers.

Amortised inference fixes this. One network, the encoder qφ(z | x) = N(μφ(x), σφ(x)), reads any x and outputs its bell.

To train φ, call the log joint a reward: r(xi, z) = log pθ(xi | z) + log p(z). The ELBO's first term J(φ) is the average of r over z drawn from qφ. That is RL: qφ is a policy, z its action, r its reward.

Say it aloud

grad-phi J is about one over M times the sum over j of grad-phi log q-phi of z-j given x-i, times r of x-i and z-j.

∇φJ
grad-phi J the direction in the encoder weights φ that raises J fastest.
(1/M) Σj
one over M times the sum over j the average over M codes zj drawn from qφ.
∇φ log qφ
grad-phi log q-phi the score: the direction that makes the draw zj more likely.
r(xi, zj)
r of x-i and z-j the reward: a log probability, often a large negative number.
In plain words

Draw M codes zj. Push up each one's probability in proportion to its reward r, and average. This is the score-function estimator (REINFORCE).

With numbers

With made-up numbers: q = N(μ, 1) at μ = 0, and r(z) = −(z − 2)2/2. The true gradient in μ is 2. One draw gives an estimate with mean 2.00 and standard deviation 4.66.

Worse, r is a log probability, far below zero. Add −50 to r and the spread grows from 4.66 to 53.6, which is why the policy gradient lesson needs a baseline.

The reparameterisation trick moves the randomness out of φ: draw ε from N(0, 1) and set z = μφ(x) + εσφ(x). Now z is a smooth function of φ.

Say it aloud

grad-phi J is about one over M times the sum over j of grad-phi r, at x-i and mu-phi of x-i plus epsilon-j times sigma-phi of x-i.

∇φJ
grad-phi J the same gradient as above, estimated a new way.
(1/M) Σj
one over M times the sum over j the average over M noise draws.
∇φ r
grad-phi r the slope of the reward through z into φ. Autodiff computes it.
μφ(xi)
mu-phi of x-i the encoder's mean for this data point.
εj
epsilon-j noise from N(0, 1). It does not depend on φ.
σφ(xi)
sigma-phi of x-i the encoder's width for this data point.
In plain words

Draw εj, build z from μφ and σφ, and differentiate r through z into φ. Average.

With numbers

Same toy: z = 0 + ε, and the slope of r is 2 − ε. The mean is 2.00 and the standard deviation is 1.00. The −50 offset changes nothing, because a constant has zero slope.

Race the two gradient estimators

Yellow is the score-function estimate, blue the reparameterised one. Both aim at the true value 2. Shift the reward down like a real log probability, and add samples.

0

Illustrative toy from the worked example: q = N(0, 1), r(z) = −(z − 2)2/2 + offset. The read-out counts estimates outside the axis.

EstimatorLatent zVarianceIn practice
Score function (policy gradient)discrete or continuoushighmany samples, small learning rates
Reparameterisationcontinuous onlylowone sample works well; autodiff does it

With the trick, the ELBO is a rebuild term minus DKL(qφ(z | xi) ‖ p(z)). That is the VAE objective.

The failure. Symptom: the encoder's loss jumps around and q barely moves. Measure: log the spread of the per-sample gradients in a batch. Fix: reparameterise; for a discrete z, keep the score function and subtract a baseline.

Adding −50 to the reward r makes the score-function estimate far noisier but leaves the reparameterised one unchanged. Why?

Chapter 3

VAEs Inside RL

Use a VAE to give a Q-function a compact state, and a conditional VAE to give a policy its choice

The course shows two uses. One gives RL a better state. The other gives the policy its z.

A code for the state

Here z is a compact representation of a state s, such as a game frame. The VAE trains on states alone, with no reward, so old data without rewards also helps. The loop:

  1. Collect a transition (s, a, s′, r) and add it to the replay buffer R.
  2. Update the decoder pθ(s | z) and the encoder qφ(z | s) on a batch from R.
  3. Update Q(z, a) on a batch from R, with z in place of s.

A conditional VAE policy

A conditional VAE (CVAE) puts a condition in every term. For a policy, the condition is the state s and the output is the action a. In training the encoder sees the demo action, so it can place z on the correct side. At test time there is no action, so z comes from the prior.

Say it aloud

L-i equals the expected value, over z from q-phi of z given s-i and a-i, of log p-theta of a-i given s-i and z, minus the KL from q-phi to p of z given s-i.

ℒi
L-i the CVAE's ELBO for demo pair i.
Ez∼qφ(z | s, a)
the expected value over z from q-phi given s and a the average over codes the encoder draws after it sees the state and the demo action.
log pθ(ai | si, z)
log p-theta of a-i given s-i and z the rebuild term: how well the decoder recovers the demo action.
DKL(qφ ‖ p(z | s))
the KL from q-phi to the prior a penalty for codes far from the prior. The prior may depend on s, or be plain N(0, 1).
In plain words

Encode the demo pair (si, ai) into z. Rebuild the action from si and z. Subtract a penalty for codes far from the prior, so prior draws decode well at test time.

With numbers

In the made-up toy below, at a KL weight of 1: the rebuild cost is 0.143 and the KL is 0.959. The loss, minus the ELBO with constants dropped, is 0.143 + 1 × 0.959 = 1.102 nats.

Weigh the KL penalty

Top: the prior (grey, dashed) and the encoder's bells for left demos and right demos (purple). Bottom: 16 test-time plans from prior draws. Raise the weight β and find where the encoder gives up.

1.0

Illustrative toy, solved on this page. Demo actions are ±1, the encoder is N(±m, s2), and the decoder mean is c · tanh(4z) with width 0.3. For each β the page searches m and s on a grid and picks the best c in closed form.

Two systems in the course use this. Learning Latent Plans from Play (Lynch et al.) encodes a window of play data into a plan z. ACT (Zhao, Kumar, Levine and Finn) runs a transformer encoder over the joints and an action sequence to make a style variable z. A second transformer reads four cameras, the joints and z, and outputs a whole action sequence.

The failure. Symptom: the CVAE policy averages again and hits the tree. Measure: log the KL term; near zero means the encoder ignores the action. This is posterior collapse. Fix: lower β. In the toy, the collapse comes at β ≈ 8.6, where the loss jumps to 5.556 = 1 / (2 × 0.32).

A CVAE policy's KL term falls to about zero and the robot takes the middle path again. What happened?

Chapter 4

Diffusion Is a Chain of Latents

Read a diffusion or flow policy as a VAE with many latent steps, and a world model as a VAE over time

A CVAE has one latent. A diffusion policy has a chain. It starts from noise a1, and a network p(aτ−Δτ | s, aτ, τ) steps down to the action a0. The course calls diffusion "a hierarchical VAE".

Say it aloud

log p of a-zero given s is at least the expected value, over the noisy chain from q, of log p of a-zero given s and the chain, minus the KL from q of the chain given a-zero to p of the chain.

log p(a0 | s)
log p of a-zero given s the policy's log-likelihood of the clean action a0.
EaΔτ:1∼q
the expected value over the chain from q the average over noisy versions aΔτ, a2Δτ, up to a1, made by the forward process q.
log p(a0 | s, aΔτ:1)
log p of a-zero given s and the chain the rebuild term: how well the last denoising step recovers a0.
DKL(q ‖ p)
the KL from q to p q is the forward noising process, fixed. p is the reverse denoising process, learned.
In plain words

These are the VAE's two terms, but the encoder q is fixed: it adds noise step by step. Only the decoder p learns.

With numbers

With made-up numbers: a step Δτ = 0.25 gives 1 / 0.25 = 4 latents, a0.25 to a1. The KL compares 4 fixed noising steps with 4 learned denoising steps.

Why does the chain stop the averaging? Each small step is close to one bell. One big step from pure noise must average the modes. In our toy, with demo actions ±1, the best guess of a0 from aτ = x is m = tanh((1 − τ)x / τ2). Each Euler step subtracts Δτ × (x − m) / τ.

x1 = 0.5 → x0.5 = 0.5 − 0.5 × 0.5 = 0.25 → x0 = 0.25 − 0.5 × (0.25 − 0.462) / 0.5 = 0.462 (2 steps)

Denoise in K steps

Each line starts as noise at the top (τ = 1) and steps down to an action (τ = 0). The red band is the tree zone. Pick the number of steps K below.

Illustrative toy: data at ±1, aτ = (1 − τ)a0 + τε, the exact best denoiser for that data, and plain Euler steps. Over 100,000 samples, K = 1, 2, 3 and 5 put 100%, 24%, 7% and 0.7% of actions within 0.3 of zero.

The failure. Symptom: a diffusion policy cut to one or two steps drives the middle path. Measure: count sampled actions between the demo modes. Fix: more steps, or a model trained for few-step sampling.

A world model is a VAE over time

Let z be a sequence of latent states z1 to zT. Let x be the frames o1 to oT. Now the prior has dynamics.

Say it aloud

p of z equals p of z-one times the product over t of p of z-t-plus-one given z-t and a-t.

p(z)
p of z the prior over the whole latent sequence.
p(z1)
p of z-one the first latent state: N(0, I).
∏t
the product over t multiply one factor for each time step.
p(zt+1 | zt, at)
p of z-t-plus-one given z-t and a-t the learned dynamics: where the latent state goes after action at.
In plain words

Draw z1 from a bell. Roll the learned dynamics forward one action at at a time. Multiply the step chances.

With numbers

With made-up numbers: if p(z1) = 0.5 and two steps have chances 0.8 and 0.6, then p(z) = 0.5 × 0.8 × 0.6 = 0.24.

PartFormReads
Priorp(z1) ∏t p(zt+1 | zt, at)a bell, then learned dynamics
Decoder∏t p(ot | zt)each frame from its own state
Encoder∏t qφ(zt | o1:t)each state from all frames so far

See model-based RL, latent world models, uncertainty-aware model-based RL and partial observability.

In the toy, why does a one-step sampler put every action at 0?

Chapter 5

The Field Guide

Keep the terms, the numbers, the training step and the links on one page

A latent z turns a one-bell policy into one that can pick a side. The ELBO trains it, and its gap is a KL from q to the posterior. The encoder's gradient is a policy gradient; the reparameterisation trick cuts its noise. CVAE policies and diffusion policies are the same bound with one latent or a chain.

TermOne lineNumber on this page
Latent policyp(a | s) = ∫ p(a | s, z) p(z) dztree zone mass 23% (one bell) vs 6% (latent)
ELBOEq[log p(x, z)] + H(q)−3.234 + 0.726 = −2.508
GapDKL(q ‖ p(z | x)), q first0.508 nats, close to −ln 0.6
Amortisationone encoder qφ(z | x) for all xsaves 2 × 32 × 106 numbers
Score function∇ log q · r, any zstd 4.66; 53.6 with offset −50
Reparameterisationz = μ + εσ, continuous zstd 1.00 at any offset
CVAE policyq(z | s, a), prior p(z | s)loss 1.102 at β = 1
Posterior collapseKL → 0, z ignoredβ ≈ 8.6 in the toy
Diffusiona chain of latents, fixed qtree zone 100%, 24%, 0.7% at K = 1, 2, 5

Checklist

  1. Plot the demo actions at a fork. Two humps mean you need a latent, a mixture or a chain.
  2. Write down the KL direction. This page uses DKL(q ‖ p) throughout.
  3. Reparameterise any continuous z. Use the score function with a baseline only for a discrete z.
  4. Log the KL term every batch. Near zero means collapse; lower β.
  5. Sample from the prior at test time, and check that different z give different actions.
  6. For a diffusion policy, count actions between the modes when you cut the step count.

The core step in code

pythonimport torch, torch.nn.functional as F

def cvae_policy_loss(enc, dec, s, a, beta=1.0):
    # s: (B, ds) states, a: (B, da) demo actions
    mu, log_std = enc(torch.cat([s, a], -1)).chunk(2, -1)   # q(z | s, a), each (B, dz)
    eps = torch.randn_like(mu)                              # noise, independent of phi
    z = mu + eps * log_std.exp()                            # the reparameterisation trick
    a_hat = dec(torch.cat([s, z], -1))                       # mean of p(a | s, z), (B, da)
    rebuild = F.mse_loss(a_hat, a, reduction='none').sum(-1)   # minus log p(a|s,z), up to scale
    kl = 0.5 * (mu**2 + (2*log_std).exp() - 1 - 2*log_std).sum(-1)  # KL(q || N(0, I))
    return (rebuild + beta * kl).mean(), kl.mean()            # log the KL: near 0 means collapse

def act(dec, s, dz):
    z = torch.randn(s.shape[0], dz)                           # test time: z from the prior
    return dec(torch.cat([s, z], -1))

Keep going

The takeaway. A latent policy is trainable because the ELBO turns an integral into an average, and the reparameterisation trick turns that average into a low-noise gradient.
You train a CVAE policy for a robot with a continuous 16-number z. Which gradient for the encoder, and what do you log?

Now press Present or Teach. From memory, explain why one bell hits the tree, the two ELBO terms, the encoder gradient, and posterior collapse. Then go back to the tree and drag z through zero.

Credit and source

This supplement follows UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine. Course page: rail.eecs.berkeley.edu/deeprlcourse. Slides: Lecture 11, Lecture 12 and Section 6. The explanations, toys and devices are our own.

Variational Inference for RL (UC Berkeley CS 285)
The course page · Lecture 11 PDF · Lecture 12 PDF · Section 6 PDF · Back to Gleams