A skilled reach is still random. It wanders most mid-way and lands on target. Give each step a chance of being optimal equal to e to its reward. Then planning becomes inference: two cones of messages meet, and their overlap is the path.
Pick a layer, then drag the temperature. Turn on the slippery floor and compare the two backups. Then we build each piece: the optimality variable, backward messages and the exp-advantage policy. Last come the gamble of exact inference and the variational fix behind SAC's entropy term.
You need Q-learning, the SAC chapter of Off-Policy Actor-Critic and the ELBO from Variational Inference for RL. We build the rest from zero.
Based on UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine (Spring 2026): Lecture 12, Lecture 13, the Lecture 22 review and Section 6. A supplement to the Deep RL lessons: it re-teaches only what they lack, in our own words and toys.
Illustrative toy, computed exactly on this page: 13 lanes, 12 steps, a lane move costs 1, ending y lanes off the goal costs 4y². On the slippery floor, 1 move in 5 becomes a random move. Teal lines are paths sampled from the soft policy.
Chapter 0
See why a model of skilled behaviour must give mistakes a chance, and why some mistakes cost more than others
Reach for a cup a hundred times. No two hand paths match. The hand wanders most in the middle and lands on the cup every time. A monkey trained to reach for a target does the same.
Optimal control predicts one path: the best one. Every other path gets probability zero. One wobble in your data, and the model calls your data impossible. You cannot fit a model to data it calls impossible.
We want a model with three properties. Good behaviour is the most likely. Worse behaviour is less likely, but never impossible. A mistake that costs a lot is rarer than a mistake that costs little.
Here is the toy for the whole page. A hand moves right one column per step for 12 steps. At each step it picks a lane move: up one, stay, or down one. A reward is a number the agent wants large. A lane move has reward −1. Ending y lanes away from the cup has reward −4y².
Four demos of the same reach. Pick a demo, then switch the model and compare the chance each model gives it.
Illustrative demos on our toy. Soft optimality chances come from the policy of Chapter 3 at temperature 1.
Demo B makes two extra moves and still lands. Demo D makes one move, at the last step, so it misses by one lane and pays 1 + 4 = 5. Soft optimality ranks D below B, though D moved less. Where the mistake happens matters.
With our toy numbers, the straight demo A has chance 0.0074. Demo B costs 2 more, so its chance is 0.0074 × e−2 = 0.0010. Optimal control gives B zero.
The failure. Fit deterministic optimal control to human demos and the fit breaks on the first wobble. The symptom is a log-likelihood of minus infinity, or a learned reward bent to explain noise. Count the demos the model gives zero chance. The fix is a model whose chance falls smoothly with cost.
Chapter 1
Turn "this step was optimal" into an observed event, and read good behaviour off Bayes' rule
Add one yes-or-no variable per step. Call it Ot, the optimality variable: it is 1 when step t counts as optimal. We never ask what it means in the world. We only fix its chance.
The graph above has one O per step, shaded because we observe it. How likely is Ot = 1? Let it grow with the reward of that step. Rewards here are 0 or negative, so the chance stays at or below 1.
p of O-t given s-t and a-t equals e to the r of s-t, a-t.
Take the reward r of the step. Raise e to it. That is the chance the step counts as optimal.
A stay has r = 0, so the chance is 1. A lane move has r = −1, so the chance is e−1 = 0.37.
Now observe O = 1 at every step. Ask Bayes' rule which trajectory τ (tau), the full list of states and moves, produced it.
p of tau given O one to T is proportional to p of tau, times e to the sum over t of r of s-t, a-t.
Start from the prior p of tau. Multiply by e to the return. Normalise. Better paths win, and worse paths keep a chance.
Demo A has return 0 and demo B has return −2, with equal priors. B over A is e−2 = 0.135, so B is 7.4 times less likely.
The page rolls random reaches and flips one coin per step, heads with chance er. It keeps only all-heads reaches. Purple marks the exact spread for comparison.
Illustrative toy. Each roll picks up, stay or down with chance 1/3 at every step.
The kept reaches form a diamond: tight at the start, wide mid-way, tight at the cup. Nobody told the sampler to plan. Conditioning on O did it.
The failure is cost. About 1 reach in 3,900 survives, because p(O1:T) = 0.026% here. With a longer horizon the rate falls toward zero. Measure the acceptance rate. The fix is to compute the posterior with messages, with no sampling.
Chapter 2
Pass the chance of future success back from the goal, and find value iteration with a soft max
Stand in lane 1 at step 11, one step before the end. What is the chance that every step from here counts as optimal? Call it the backward message βt (beta-t). It depends on the state and the next move.
beta-t of s-t, a-t equals p of O-t given s-t, a-t, times the average over s-t-plus-one of beta-t-plus-one of s-t-plus-one.
Start at the last step and walk back. For each state and move, multiply this step's chance by the average beta of the next state.
At the end, beta is e−4y²: 1 in lane 0 and 0.018 in lane 1. From lane 1 at step 11, a move down gives e−1 × 1 = 0.368. A stay gives 1 × 0.018.
Products of chances underflow, so take logs. Call Qt the log of βt(s, a) and Vt the log of βt(s). Averaging β over the moves becomes a log of a sum of exponentials.
V-t of s-t equals log of the sum over a-t of e to the Q-t of s-t, a-t.
Raise e to each move's Q. Add them. Take the log. The best move dominates V; close runners-up add a little.
Lane 1, step 11: Q is −1, −4 and −17 for down, stay and up. V = log(e−1 + e−4 + e−17) = −0.951, a little above the max of −1.
Warm dots are two Q values. Drag the gap and watch the soft max close in on the max.
The surplus of the soft max over the max is log(1 + e−gap) for two actions.
Put the logs into the recursion. The backup is Q = r + log E[exp V(st+1)]. With sure moves the average has one term, so Q = r + V(st+1): a move down from lane 1 scores −1 + 0 = −1. Compare with value iteration.
| Step | Value iteration | Backward messages |
|---|---|---|
| Value of a state | max over moves of Q | log Σ exp Q (soft max) |
| Next-state average | E[V(s′)] | log E[exp V(s′)] |
The soft max over moves is harmless. The second row is the bug of Chapter 4.
The failure. e to a Q of 800 is infinity in float64. The symptom is V turning into inf or NaN. Watch the largest Q. The fix is to subtract the max before exp: the log-sum-exp trick in the Field Guide code.
Chapter 3
Read the policy off the backward messages, then add forward messages to see where the agent goes
Which move does the agent make? Ask for the chance of a-t, given the state and given success from here on. Bayes' rule gives βt(s, a) over βt(s). In logs that is Q minus V.
pi of a-t given s-t equals e to the Q-t minus V-t, which is e to the A-t.
Take each move's Q. Subtract the state's V. Raise e to it. The chances sum to 1, because V is the log of the sum.
Lane 1, step 11: Q is −1, −4, −17 and V = −0.951. Down gets e−0.049 = 0.953. Stay gets e−3.049 = 0.047. Up gets about 0.
Better moves are more likely and ties split evenly, like Boltzmann exploration. Divide Q and V by a temperature and the policy turns greedy as it falls. The SAC chapter has a device for that; the hero slider does the same here.
The policy says what to do. Where does the hand go? A forward message αt(s) (alpha-t) is the chance of being in s at step t, given success on steps 1 to t−1. Push it forward from the start, weighting each move by e to its reward.
p of s-t given O one to T is proportional to beta-t of s-t times alpha-t of s-t.
Multiply beta-t and alpha-t lane by lane. Normalise the column. The overlap of the two cones is where the agent goes.
Step 6 in the toy: lane 0 has alpha 0.247 and beta 1 (scaled); lane 1 has alpha 0.205 and beta 0.83. The products are 0.247 and 0.170. Normalised, lane 0 gets 0.346 and lane 1 gets 0.238.
Each curve is one message across the 13 lanes at the chosen step. Drag the step from start to goal.
Toy at temperature 1, dry floor. We scale each curve to its own peak. Spreads are standard deviations in lanes.
Each cone alone is narrow only at its own end. The product is narrow at both ends: ±1.15 lanes at step 6, and 97% on the cup at step 12. Human reaching data in the course slides (Li and Todorov, 2006) has the same shape: the hand varies most mid-path.
The failure. Read α alone as the agent's path and you ignore the goal, so the path keeps spreading. Measure the spread at the last step: α alone gives ±2.24 lanes. The fix is to multiply by β.
Chapter 4
See why conditioning on success also bends the dynamics, and measure the optimism on a lottery
Add chance to the world. From one state, a safe move leads to a state worth −1 for sure. A gamble leads to a jackpot worth 0 with chance p, or else to a pit worth −10. Both moves have reward 0.
The exact backup scores the gamble as log(p + (1 − p) e−10). How does that compare with the plain average of the outcomes?
log of the average of e to the V of s-prime is at least the average of V of s-prime.
Average the values V, or average e to the values and take the log. The second is never smaller. The gap grows with the spread of outcomes.
At p = 0.2: E[V] = 0.2 × 0 + 0.8 × (−10) = −8.0. log(0.2 + 0.8 e−10) = −1.61. The gap is 6.4. The safe move still scores higher, but the policy picks the gamble with chance 0.35.
The tree shows the two moves. Drag the jackpot chance and watch where each backup switches to the gamble.
Illustrative toy. The policy chances use exp(Q − V) over the two moves.
Exact inference takes the gamble once p passes 0.37 (that is e−1). The expected value says to wait until p passes 0.9. Why the gap? Inference answers the question: given that you succeeded, what happened? Given success, the jackpot is likely, so the posterior changes the transition chances too. The agent plans as if it controls the dice.
The failure is a risk-seeking agent that walks near cliffs. Compare the backed-up value with the return you get when you run the policy. Try the hero's slippery floor. Exact inference promises 1.70 more soft value at the start. Its paths end ±1.01 lanes off the cup, against ±0.60. The fix is to keep the true dynamics.
Chapter 5
Choose an approximate posterior that may change only the policy, and get reward plus entropy
We want the move chances given success, with the transition chances left alone. Use variational inference: pick a distribution q, from a family you choose, close to the posterior. The evidence x is O1:T and the hidden z is the whole trajectory.
q of the states and moves equals p of s-one, times the product over t of p of s-t-plus-one given s-t, a-t, times q of a-t given s-t.
Build paths the way the world does: the real start p of s-one and the real dynamics. Only q of a-t given s-t is yours to choose.
In the lottery at p = 0.2, q may move chance between safe and gamble. It may not raise the jackpot chance above 0.2.
Put this q into the ELBO, log p(x) ≥ Eq[log p(x, z) − log q(z)]. The start and dynamics terms appear once with a plus and once with a minus, so they cancel. Raising this bound lowers KL(q ‖ posterior), the reverse KL of the VI lesson.
log p of O one to T is at least the sum over t of the average under q of r of s-t, a-t, plus H of q of a-t given s-t.
Run the policy. At each step add the reward r and the entropy H of the move chances. Average over runs, then raise it.
One step, two moves with rewards 0 and −1, q = 0.6 on the first: E[r] = −0.40 and H = 0.673, so the bound is 0.273. The best q is 0.731, which gives 0.313: the soft max V of Chapter 2.
Yellow is the expected reward, purple the entropy, warm their sum. Drag the chance of the better move and find the peak.
Illustrative one-step toy: rewards 0 and −1.
Solve this bound backward and the backup changes in one place.
| Part | Exact inference | Variational inference |
|---|---|---|
| Q backup | r + log E[exp V(s′)] | r + E[V(s′)] |
| V | log Σ exp Q | log Σ exp Q |
| Policy | exp(Q − V) | exp(Q − V) |
| Lottery at p = 0.2 | gamble −1.61, chance 0.35 | gamble −8.0, chance 0.001 |
With sure moves the two columns agree. That is why the hero's two backups match on the dry floor.
The failure. Drop the entropy term and the bound becomes plain expected reward, so the best q is greedy. The symptom is a policy that collapses onto one move early. Log the policy entropy. The fix is to keep H, scaled by a temperature, as SAC does.
Chapter 6
Turn the variational backup into soft Q-learning, an entropy-regularised policy gradient and SAC
Add a discount γ (gamma) and replace the tables with networks. One algorithm falls out for each family of RL.
Soft Q-learning is DQN with one change: the target takes the soft max over next moves.
y equals r plus gamma times log of the sum over a-prime of e to the Q-bar of s-prime, a-prime.
Look up Q-bar for each next move. Take the soft max. Multiply by gamma and add r. Regress Q(s, a) onto y.
With made-up numbers: r = 1, gamma 0.9, next Q-bar values 2, 1 and −1. The soft max is 2.349, so y = 1 + 0.9 × 2.349 = 3.114. DQN's hard max gives 2.8.
The policy is exp(Q − V), so discrete moves need no actor. An entropy-regularised policy gradient raises Σ E[r] + H(π) with the REINFORCE estimator. H has a closed form for Gaussian and softmax policies, so it adds one term.
Soft actor-critic (SAC) handles continuous moves, where the sum over a′ is an integral nobody can compute. It samples a′ from the actor instead.
y equals r plus gamma times the average, over a-prime drawn from pi, of Q-bar of s-prime, a-prime minus log pi of a-prime given s-prime.
Sample a next move a-prime from pi. Take Q-bar minus log pi. Average, multiply by gamma, add r.
If the actor is exactly exp(Q − V), then Q − log π = V for every sample. The average is 2.349, so y = 3.114: the soft Q-learning target.
Teal bars are the actor's chances over three next moves. Drag its sharpness and watch the target term against the soft max.
Made-up next-state values Q-bar = 2, 1, −1. The actor is proportional to e to the sharpness times Q-bar; sharpness 1 is exp(Q − V).
Any other actor gives a smaller average. So the soft target is highest when the actor equals exp(Q − V), and the SAC actor update pushes it there. The SAC chapter covers the two critics, the reparameterised actor and the tuned temperature.
The failure is reward scale. The bound fixes the temperature at 1, so rewards in the thousands drown the entropy, and rewards in the thousandths drown the reward. The symptom is entropy pinned at its floor or its ceiling. The fix is a temperature in front of H, tuned as SAC does.
Chapter 7
Keep the terms, the toy numbers, the code and the links in one place
Give each step a chance er of counting as optimal, and condition on success. Backward messages become soft value iteration and the policy becomes exp(Q − V). Forward times backward gives the path. Exact inference bends the dynamics and gambles. Variational inference keeps them and yields reward plus entropy: soft Q-learning and SAC.
| Term | What it is | Toy number on this page |
|---|---|---|
| Optimality variable Ot | chance er that step t counts as optimal | stay 1, lane move 0.37 |
| p(O1:T) | chance a random reach succeeds | 0.026%, about 1 in 3,900 |
| Backward message β | chance of success from here | 0.368 for down from lane 1 at step 11 |
| Soft value V | log Σ exp Q | 0.313 for Q = 0 and −1 |
| Policy π | exp(Q − V) = exp(A) | down 0.953, stay 0.047 |
| Forward message α | chance of reaching s well from the start | 0.247 in lane 0 at step 6 |
| State marginal | β × α, normalised | ±1.15 lanes at step 6, 97% on the cup |
| Optimism gap | log E[eV] − E[V] | 6.4 in the lottery at p = 0.2 |
| Max-ent bound | Σ E[r + H(q)] | peak 0.313 at q = 0.731 |
| Soft target | r + γ softmax Q̄ | 3.114, against 2.8 for the hard max |
Finite-horizon soft value iteration for a table. It reproduces every corridor number above, and the exact flag reproduces the optimism.
pythonimport numpy as np def soft_value_iteration(r, P, V_end, T, exact=False): # r: [S, A] rewards, P: [A, S, S'] dynamics, V_end: [S] log beta at the end V, pis = V_end, [] for t in reversed(range(T)): if exact: # optimistic: log E[exp V'] m = V.max() nxt = np.log(np.einsum('asj,j->sa', P, np.exp(V - m))) + m else: # variational: E[V'] nxt = np.einsum('asj,j->sa', P, V) Q = r + nxt # [S, A] m = Q.max(1, keepdims=True) # log-sum-exp trick V = (m + np.log(np.exp(Q - m).sum(1, keepdims=True)))[:, 0] pis.append(np.exp(Q - V[:, None])) # pi = exp(Q - V) return V, pis[::-1] import torch # the soft target of soft Q-learning, for a batch def soft_target(r, q_next, gamma=0.99): # q_next: [B, A] from the target network return r + gamma * torch.logsumexp(q_next, dim=1)
The backward and forward messages are the same algorithm as in a hidden Markov model. The SAC details live in Off-Policy Actor-Critic, and the ELBO in Variational Inference for RL. Run this model backward, from demos to rewards, in Inverse RL and Adversarial Imitation. For learned rewards in practice, see Reward Learning.
Now press Present or Teach and explain from memory. Say why Ot has chance er and how β becomes soft value iteration. Say why the policy is exp(A), why exact inference gambles, and where SAC's entropy comes from. Then go back to the hero, turn on the slippery floor and say why the two backups split.
This lesson re-teaches part of UC Berkeley CS 185/285, Deep Reinforcement Learning, taught by Sergey Levine. The course page is rail.eecs.berkeley.edu/deeprlcourse. Sources: Lecture 12 (slides 20 to 37), Lecture 13 (slides 1 to 16), Lecture 22 (slides 21 to 29) and Section 6. The main reading is Levine (2018), Reinforcement Learning and Control as Probabilistic Inference: Tutorial and Review. The corridor, the lottery and every number on this page are our own toys.