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.
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
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.
p of a given s equals the integral over z of p of a given s and z, times p of z, d z.
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 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.
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.
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.
Chapter 1
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.
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.
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.
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.
log p of x-i equals the KL divergence from q-i of z to p of z given x-i, plus L-i.
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.
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.
Pink is the true posterior over z. Purple is your guess q. Move q and read the bars against the dashed ceiling.
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.
Chapter 2
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.
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.
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 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 φ.
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.
Draw εj, build z from μφ and σφ, and differentiate r through z into φ. Average.
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.
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.
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.
| Estimator | Latent z | Variance | In practice |
|---|---|---|---|
| Score function (policy gradient) | discrete or continuous | high | many samples, small learning rates |
| Reparameterisation | continuous only | low | one 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.
Chapter 3
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.
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:
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.
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.
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.
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.
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.
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).
Chapter 4
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".
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.
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 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)
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.
Let z be a sequence of latent states z1 to zT. Let x be the frames o1 to oT. Now the prior has dynamics.
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.
Draw z1 from a bell. Roll the learned dynamics forward one action at at a time. Multiply the step chances.
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.
| Part | Form | Reads |
|---|---|---|
| Prior | p(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.
Chapter 5
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.
| Term | One line | Number on this page |
|---|---|---|
| Latent policy | p(a | s) = ∫ p(a | s, z) p(z) dz | tree zone mass 23% (one bell) vs 6% (latent) |
| ELBO | Eq[log p(x, z)] + H(q) | −3.234 + 0.726 = −2.508 |
| Gap | DKL(q ‖ p(z | x)), q first | 0.508 nats, close to −ln 0.6 |
| Amortisation | one encoder qφ(z | x) for all x | saves 2 × 32 × 106 numbers |
| Score function | ∇ log q · r, any z | std 4.66; 53.6 with offset −50 |
| Reparameterisation | z = μ + εσ, continuous z | std 1.00 at any offset |
| CVAE policy | q(z | s, a), prior p(z | s) | loss 1.102 at β = 1 |
| Posterior collapse | KL → 0, z ignored | β ≈ 8.6 in the toy |
| Diffusion | a chain of latents, fixed q | tree zone 100%, 24%, 0.7% at K = 1, 2, 5 |
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))
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.
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.