Keep every try and learn from it many times. In this toy, replay reaches 80% of the best reward in 50 to 160 steps. Reusing each batch 10 times takes about 500. Using each try once takes more than 600.
Learn how an actor-critic reuses old experience safely: importance weights, a Q critic, the deterministic policy gradient, target networks, two critics and an entropy bonus.
Press Run and watch three learners race on one task. The right panel shows what the replay learner's critic believes. Then switch on Two critics: the red gap between belief and truth closes. Then we build each piece from zero.
You need a little Python and what a probability is. The policy gradients and actor-critic lessons help. We build the rest from zero.
Re-taught from the off-policy actor-critic lecture of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy with one state. An action is a number from −1 to 1. The reward is a hill that peaks at 1.0 at action 0.55, plus noise with a standard deviation of 0.8. Each curve is the average of 8 runs.
Use once: one policy gradient step per batch of 20 tries, then it drops the batch. Reuse ×10: 10 clipped passes per batch, PPO style. Replay: it keeps every try and does 4 critic updates per step on minibatches of 8. Its critic is a table over 21 action bins with gamma 0.9, and its actor takes the critic's best action.
Chapter 0
Count how many updates one batch of robot time buys
A robot arm practises a pick-and-place task at 10 steps per second. In 3.4 minutes it collects 2,048 steps. REINFORCE turns that batch into one gradient step and throws the batch away. The next gradient step needs 2,048 new steps of robot time.
REINFORCE is an on-policy method: its gradient is an average over the actions of the current policy. After one update the policy changes, so the old batch no longer comes from it. An off-policy method learns from data that a different policy collected. That policy is the behavior policy. The policy we improve is the target policy.
The warm strip is 2,048 robot steps. The ticks below it are the gradient steps they buy. Pick a method, then change the robot's speed.
Illustrative budget: suppose learning needs 320,000 gradient steps. Use once is REINFORCE (1 step per batch). Reuse ×10 is PPO's usual setting: 10 passes of 32 minibatches of 64. Replay is SAC's usual setting: 1 gradient step per robot step.
At 10 steps per second, 320,000 gradient steps cost 655 million robot steps with REINFORCE: about 2.1 years. PPO buys 320 steps per batch, so it needs 1,000 batches: 57 hours. SAC buys one step per robot step: 8.9 hours.
The failure. Reuse a batch with no correction, and the gradient points the wrong way. The symptom is a batch loss that keeps falling while the return in the world falls. Measure the return of fresh episodes, not the loss on the batch. The fix is this lesson: correct the data, or learn a critic that does not care who collected it.
Chapter 1
Store every transition, draw random minibatches, and count the uses of each one
Keep every step instead of throwing it away. One step is a transition: the state s, the action a, the reward r and the next state s′. A replay buffer is a store of the most recent N transitions. When it is full, each new transition replaces the oldest one.
Each gradient step draws a random minibatch of B transitions from the buffer. Random draws break the order of the data. Neighbouring steps of one episode look alike, so a minibatch of neighbours would teach one moment of one episode.
Each cell is a transition. Bright cells are new, faint cells are old. Blue rings are the current minibatch. Press Play, then change the size and the updates per step.
Toy buffer with minibatches of B = 8. The policy changes every 10 steps; a cell's shade is its age in policy versions.
How often is one transition used? Each gradient step draws B of the N transitions, so one transition has a chance of B ÷ N per step. It stays in the buffer for N environment steps, which is G × N gradient steps. The expected number of uses is G × N × B ÷ N = G × B.
SAC's usual settings are B = 256 and G = 1, so the agent uses each transition about 256 times. A buffer of 1 million transitions holds the last 27.8 hours of a robot that runs at 10 steps per second.
The failure. Old transitions came from old, worse policies. A value fitted to their returns answers for no policy in particular (Chapter 4). A buffer that is too small fails the other way: the critic sees only recent states and forgets the rest. Measure the age of the sampled transitions in policy updates. The fix is a Q critic, which can use old data, and a buffer that covers the states the policy still visits.
Chapter 2
Reweight old data so it counts as the new policy's, and watch a few weights swallow the batch
An old policy stood at a cliff edge and jumped with chance 0.1. The new policy jumps with chance 0.4. So a jump in the old data gets weight 4, and staying put (0.9 to 0.6) gets weight 0.67.
That ratio is the importance weight: the new chance of the action divided by the old chance. An average of weighted samples from the old policy equals the average under the new policy. That is exact. The trouble starts with whole trajectories.
Call the target policy π (pi) and the behavior policy μ (mu). A trajectory τ (tau) is the list of states and actions from step 0 to step T − 1.
Rho of tau equals the product over t, from zero to T minus one, of pi of a-t given s-t, divided by mu of a-t given s-t.
At each step, divide the new chance pi of the action by the old chance mu. Multiply all T ratios. The world's chances of each next state are the same under both policies, so they cancel and never appear.
With made-up policies: mu picks left with chance 0.5 and pi with chance 0.6. A left step gets 1.2, a right step gets 0.8. The trajectory left, left, right gets rho = 1.2 × 1.2 × 0.8 = 1.152.
Warm bars count trajectories at each weight. Pink bars show each weight band's share of the total weight. Make the episodes longer, or the policies more different.
Toy: two actions per step; mu picks left with chance 0.5 at every step. Effective sample size = (sum of weights)² ÷ (sum of squared weights). A sample often reads above the formula's 20, because the heaviest trajectories are rare.
The weights average 1, but their spread grows with T. The average squared weight of one step is (0.6² + 0.4²) ÷ 0.5 = 1.04. Over T steps it multiplies: 1.04 to the power 100 is about 50. The effective sample size is the number of equally weighted samples with the same noise. It is about N divided by that average: 1,000 trajectories count as about 20. At chance 0.7 the factor per step is 1.16, and 1.16 to the power 100 is 2.8 million.
The failure. One trajectory gets a weight in the thousands and decides the update. The symptom is a gradient that jumps from batch to batch. Measure the effective sample size of each batch. The fixes: use one ratio per step instead of the product (Chapter 3). Cap each ratio at 1 (Retrace, Munos et al., 2016). Or use a critic that needs no weights on actions (Chapter 4).
Chapter 3
Use one ratio per step, reuse a batch for a few passes, and stop each sample's pull at the edge of a band
PPO (Schulman et al., 2017) reuses each batch for several passes, with one ratio per step instead of the product. That ratio is a fair stand-in only while the new policy stays close to the old one. So PPO removes the reward for pushing a sample's ratio out of a band.
Call the new policy's chance of the action at step t, divided by the old policy's chance, r-t of θ. Call the advantage of that action, how much better than usual it turned out, A-hat-t. A small number ε (epsilon), such as 0.2, sets the band from 1 − ε to 1 + ε.
L-clip of theta equals the average over t of the minimum of two things: r-t times A-hat-t, and r-t clipped between one minus epsilon and one plus epsilon, times A-hat-t.
Multiply the ratio r-t by the advantage A-hat-t. Also multiply the clipped ratio by it. Keep the smaller. Once a sample's ratio leaves the band in the direction its advantage wants, its term goes flat and stops pulling.
With made-up numbers: A-hat = +2, epsilon 0.2 and ratio 1.5. The plain term is 3.0, the clipped term is 1.2 × 2 = 2.4, so PPO keeps 2.4. For A-hat = −2 and ratio 0.5, the terms are −1.0 and −1.6, and PPO keeps −1.6.
Warm dots are 20 tries: above the line if they did better than the batch average, below if worse. The yellow bell is the old policy, the teal bell the new one. Pink dots below are the ratios. Add passes, then switch on the clip.
The hero's task and noise; the old policy has mean 0.40 and spread 0.2; step size 0.01 per pass. We simulated 200 batches for 60 passes each. Without the clip, 44% ended worse than they started; with it, 27%. The median largest ratio was 2.7 without the clip and 1.3 with it.
PPO's usual settings for robot control: batches of 2,048 steps, 10 passes, minibatches of 64. That is 10 × 2,048 ÷ 64 = 320 gradient steps per batch.
The failure. The clip limits each sample, not the policy. Many passes still drift. The symptom is a batch objective that rises while fresh returns fall. Measure the share of clipped samples and the average KL divergence between the old and new policy after each pass. The fix is fewer passes, or a stop when the KL passes a limit.
Chapter 4
Swap the state value for an action value, and draw the next action from the current policy
An actor-critic needs a critic. The actor-critic lesson used the state value V(s): the return the current policy expects from state s. V(s) averages over the policy's own first action. In a buffer full of old actions, that average comes out wrong.
Fix the first action instead. The action value Q(s, a) is the return expected after taking action a in state s and then following the current policy. Q holds for any a, so an old action is fine. Only the next action must come from the current policy, and we can draw that one fresh.
Take one stored transition (s, a, r, s′). Call the critic's weights φ (phi), the discount γ (gamma), the current policy π-θ, and the number the critic should move toward the target y.
y equals r plus gamma times Q-phi of s-prime and a-prime, with a-prime drawn from pi-theta given s-prime.
Take r and s-prime from the stored transition. Ask the current policy for an action a-prime in s-prime. Add r to gamma times the critic's value of that pair: that is y. Move Q-phi of s and a toward y by shrinking the squared gap.
In the toy world below, gamma is 0.9. A stored transition has r = 0 and leads to s-prime. The current policy picks the good action C, worth 4: y = 0 + 0.9 × 4 = 3.6. It picks C 90% of the time, so the targets average 0.9 × 3.6 = 3.24. That is the true Q of the stored action.
The diagram is the world, with the buffer's action shares on the arrows. The bars are two estimates of the current policy's value at s. The dashed line is the truth. Slide the share of old data.
Toy world, gamma 0.9. At s: A pays 0 and leads to s′; B pays 1 and ends. At s′: C pays 4, D pays 0. The old policy picks A and C 20% of the time; the current policy picks them 90%.
With half the buffer from the old policy, the V fit says 1.54 while the truth is 3.02. The Q route gives 3.02 at every mix.
The failure. Q is reliable only near actions the buffer has tried. If the policy asks about an action the buffer never saw, Q guesses, and the guess can be far too high. Online, the agent then tries that action and the error corrects. In offline RL it never does. The symptom is Q above any return ever seen. Measure Q at the policy's actions against the returns of fresh episodes.
Chapter 5
Let the actor output one action, and push it uphill along the critic's slope
A robot with seven joints has a continuous action: seven numbers. The actor can output one action vector instead of a chance for every action. That is a deterministic policy, written μ-θ of s (mu-theta of s). To explore, the agent adds noise to the action when it acts. The learned actor stays deterministic.
How should θ change? The critic Q says how good each action is. Move the action in the direction that raises Q. Then move θ in the direction that moves the action that way. That is the chain rule.
Silver et al. (2014) proved it gives the policy gradient of a deterministic policy. DDPG (Lillicrap et al., 2015) ran it with deep networks, a replay buffer and target networks.
Call the actor's action in buffer state s-i μ-θ of s-i, and the number of states in a minibatch N. The objective J is the expected return.
Nabla-theta of J is about one over N times the sum over i of nabla-a of Q at s-i and a, taken at a equals mu-theta of s-i, times nabla-theta of mu-theta of s-i.
For each buffer state s-i, ask the actor for its action. Ask the critic which way that action should move. Multiply by how the action responds to theta. Average over the N states and step theta that way.
With a made-up critic Q(a) = 3 − 4(a − 0.6)² and actor a = θ × s, with s = 0.5 and θ = 0: the action is 0. The critic's slope there is −8 × (0 − 0.6) = 4.8. The action moves 0.5 per unit of θ, so the gradient is 4.8 × 0.5 = 2.4. A step size of 0.1 moves θ to 0.24 and the action to 0.12.
The blue curve is the critic. The dashed curve is the true value. The teal dot is the actor's action, and the arrow is the critic's slope. Step or play, then give the critic a false bump.
Toy critic with one state, s = 0.5; the actor is a = θ × s. The true value is 3 − 4(a − 0.6)². The false bump adds up to 1.2 near a = 0.15.
No log-probability appears, and no importance weight on actions. The gradient averages over states only, and those states come from the buffer.
The failure. The actor climbs the critic, errors included. With the false bump on, the actor stops at a = 0.24, where the critic says 3.54 but the true value is 2.47. The symptom is a Q at the actor's action that keeps rising while returns stall. Measure the gap between Q and fresh returns. Chapters 6 and 7 shrink the errors.
Chapter 6
Chase a target that moves slowly, and trade speed for calm
The target y contains Q itself. So each update of the critic also moves the target it chases. Noise from one minibatch goes into Q, then into the next target, then back into Q. That loop makes Q swing.
A target network is a slow copy of the critic, used only to compute y. DQN (Mnih et al., 2015) copied the weights every 10,000 steps. DDPG, TD3 and SAC use a soft update after every step. Call the critic's weights φ (phi), the copy's weights φ-bar, and the mixing rate τ (tau).
Phi-bar becomes tau times phi, plus one minus tau times phi-bar.
After each critic update, move every target weight phi-bar a fraction tau of the way toward the critic's weight phi. Compute y with phi-bar, never with phi.
With tau = 0.005, each update closes 0.5% of the gap. After 138 updates the copy has closed half the gap. After 200 updates it has closed 1 − 0.995200 = 63% of it.
Blue is the critic's estimate, purple the target copy, dashed the truth. Pick tau. Tau 1 means no target network.
Toy: one state and action that loop back to themselves. The reward is 1 plus noise with a standard deviation of 1; gamma 0.95, so the true value is 20. Critic step 0.2. Over 100 runs: tau 1 reached 18 in a median of 205 updates and swung by ±1.3; tau 0.03 took 1,484 updates and swung by ±0.5.
You trade speed for calm. With tau 1 the estimate reaches 90% of the truth in about 205 updates but swings by about ±1.3. With tau 0.03 it takes about 1,480 updates and swings by about ±0.5.
The failure. A target network slows the loop. It does not guarantee convergence. With function approximation, bootstrapping and off-policy data together, Q can still grow without limit; Sutton and Barto call these three the deadly triad. Measure the largest Q in each minibatch. The fixes are a smaller tau, a smaller learning rate, and the second critic of Chapter 7.
Chapter 7
See why a critic that picks its own best action overrates it, and how a second critic cancels the luck
Ten actions are all worth 1.0. A critic estimates each one with a random error of about ±0.5. The actor goes to the action with the highest estimate. That estimate is high partly because its error is high. On average the best of ten such estimates is 0.77 too high, though each estimate alone has no bias.
Bootstrapping copies that error into the target, and the next target copies it again. With gamma 0.99, an error of 0.77 at each backup settles near 0.99 × 0.77 ÷ 0.01 = 76 above the truth. Fujimoto et al. (2018) measured this creep in DDPG and built TD3 to stop it.
TD3 trains two critics, Q-1 and Q-2, with their own weights. For the target it takes the smaller of the two. Call their target copies Q-bar-1 and Q-bar-2, and the next action a-tilde-prime: the target actor's action in s-prime plus a little clipped noise.
y equals r plus gamma times the minimum, over j equals one and two, of Q-bar-j of s-prime and a-tilde-prime.
Score the next action a-tilde-prime with both target critics. Keep the smaller score. Multiply by gamma and add the reward r. That is y for both critics.
With made-up numbers: r = 1, gamma 0.99, Q-bar-1 = 5.4 and Q-bar-2 = 4.9. The minimum is 4.9, so y = 1 + 0.99 × 4.9 = 5.85. With Q-bar-1 alone, y would be 6.35.
Every action is truly worth 1.0, the dashed line. Blue dots are critic 1, purple dots critic 2. Critic 1 picks the ringed action. The bars compare what one critic says there with the minimum of two.
Toy: each critic's error is Gaussian with the chosen standard deviation, drawn independently for each action and each critic. With 10 actions and 0.5, a million draws give +0.77 for one critic and −0.02 for the minimum of two.
Critic 2's errors do not know which action critic 1 picked, so at that action critic 2 has no bias. The minimum of the two is a little low: −0.02 here. A small underestimate does little harm, because new data corrects it.
The failure. With one critic, the estimate creeps above the true value and stays there. In the hero it settles 20 to 30% too high; with two critics, within about 10%. Measure Q at the actor's action against the discounted return of fresh episodes. TD3 adds two more fixes. It updates the actor once per two critic updates. Its target noise stops the actor from exploiting a narrow spike in Q.
Chapter 8
Pay the policy for staying random, and see how a temperature turns Q values into action chances
A policy that settles on one action too early stops learning about the others. Entropy measures how spread out a policy's choices are: zero for one sure action, largest for an even spread. Soft actor-critic (SAC, Haarnoja et al., 2018) adds the entropy to every reward, scaled by a temperature α (alpha).
The best policy for this goal gives each action a chance in proportion to e to the power Q(s, a) divided by alpha. A small alpha puts almost all the chance on the best action. A large alpha spreads it evenly.
Blue is Q over actions, with two hills. The teal area is the policy's chance of each action. Turn alpha down and up.
Toy Q over 81 actions from −1 to 1: a hill of 3.0 at 0.45 and a hill of 2.6 at −0.5. The policy is e to the Q over alpha, normalised. The read-out gives entropy as a share of the even spread's entropy.
The bonus also enters the critic's target. Draw the next action a-tilde-prime from the current stochastic policy π-θ. Minus the log of its chance is large when the action was unlikely: that is the entropy bonus for one sample.
y equals r plus gamma times, the minimum over j of Q-bar-j of s-prime and a-tilde-prime, minus alpha times log pi-theta of a-tilde-prime given s-prime; with a-tilde-prime drawn from pi-theta given s-prime.
Sample a next action a-tilde-prime from the policy. Take the smaller target critic value. Add alpha times minus the log chance. Multiply by gamma and add r.
With made-up numbers: r = 1, gamma 0.99, critics 5.0 and 4.6, log pi = −1.2 and alpha 0.2. The bonus is 0.2 × 1.2 = 0.24. So y = 1 + 0.99 × (4.6 + 0.24) = 5.79.
The actor raises the same quantity at the current state: the smaller Q minus alpha log pi. A random action blocks the gradient. So SAC writes the action as the mean plus the spread times fixed noise, then squashes it into −1 to 1 with tanh. This is the reparameterization trick. SAC also tunes alpha: it raises alpha when the entropy falls below a target, often minus the number of action dimensions.
The failure. With alpha too small, the policy collapses onto the first hill it finds. With alpha too large, it stays near random and never commits. The symptom is entropy stuck at its floor, or never falling. Measure the policy's entropy against the target. The fix is to let SAC tune alpha.
Chapter 9
Keep the targets, the numbers, a checklist and the core code on one page
On-policy methods spend each batch once. PPO reuses a batch for a few clipped passes. SAC and TD3 keep a replay buffer and learn Q, which old data can train, with fresh next actions. The actor climbs Q. Target copies calm the chase, two critics cancel the overestimate, and SAC pays for entropy.
| Piece | Problem it solves | Used in |
|---|---|---|
| Replay buffer | Each try used once | DQN, DDPG, TD3, SAC |
| Per-step ratio + clip | Trajectory weights blow up; the policy drifts | PPO |
| Q with fresh a′ | V is wrong on mixed-policy data | DDPG, TD3, SAC |
| Deterministic policy gradient | No search over continuous actions | DDPG, TD3 |
| Target network | The target moves with every update | DQN, DDPG, TD3, SAC |
| Clipped double Q | Overestimation creep | TD3, SAC |
| Entropy bonus | Early collapse onto one action | SAC |
| What | Number | Why it matters |
|---|---|---|
| Robot time to 320,000 gradient steps at 10 Hz | 2.1 years, 57 hours, 8.9 hours | Use once, PPO, SAC: reuse is the whole game |
| Uses per transition | G × B = 256 at SAC's settings | Buffer size does not change it |
| 1.04 to the power 100 | about 50 | 1,000 trajectories count as 20 |
| PPO gradient steps per batch | 320 | 10 passes of 2,048 steps in minibatches of 64 |
| Soft update half-life at tau 0.005 | 138 updates | How far the target lags |
| Best of 10 estimates at ±0.5 | +0.77; min of two −0.02 | Selection makes the bias; a second critic cancels it |
| SAC defaults | buffer 1M, batch 256, lr 0.0003, gamma 0.99, tau 0.005 | A safe start for continuous control |
| Question | PPO | SAC |
|---|---|---|
| Data | Each batch reused about 10 times, then dropped | Every transition kept in a buffer |
| Best when | Simulation is cheap and runs in parallel | Each step is expensive, as on a real robot |
| Actions | Discrete or continuous | Mainly continuous |
| Main risk | Drift after too many passes | Critic errors that the actor exploits |
| Known uses | InstructGPT's RLHF step (Ouyang et al., 2022) | Real-robot locomotion (Haarnoja et al., 2018) |
The core of SAC is two losses and a soft update. The critic regresses on the soft target. The actor raises the smaller Q minus alpha log pi, through a reparameterized action.
pythonimport torch, torch.nn.functional as F def sac_update(batch, actor, q1, q2, q1_t, q2_t, log_alpha, opts, gamma=0.99, tau=0.005, target_ent=-6.0): s, a, r, s2, done = batch # [B,obs], [B,act], [B], [B,obs], [B] alpha = log_alpha.exp().detach() with torch.no_grad(): # the target y gets no gradient a2, logp2 = actor.sample(s2) # fresh a' from the CURRENT policy q_next = torch.min(q1_t(s2, a2), q2_t(s2, a2)) # clipped double Q, target copies y = r + gamma * (1 - done) * (q_next - alpha * logp2) critic_loss = F.mse_loss(q1(s, a), y) + F.mse_loss(q2(s, a), y) opts['q'].zero_grad(); critic_loss.backward(); opts['q'].step() a_new, logp = actor.sample(s) # reparameterized: mean + std * noise, then tanh q_new = torch.min(q1(s, a_new), q2(s, a_new)) actor_loss = (alpha * logp - q_new).mean() # minimise this = raise Q - alpha log pi opts['pi'].zero_grad(); actor_loss.backward(); opts['pi'].step() alpha_loss = -(log_alpha * (logp.detach() + target_ent)).mean() # entropy below target: alpha rises opts['a'].zero_grad(); alpha_loss.backward(); opts['a'].step() with torch.no_grad(): # soft update: phi_bar = tau phi + (1 - tau) phi_bar for net, tgt in ((q1, q1_t), (q2, q2_t)): for p, pt in zip(net.parameters(), tgt.parameters()): pt.mul_(1 - tau).add_(tau * p)
Here actor.sample(s) returns a tanh-squashed action and its log chance, with the tanh correction applied. The target entropy of −6 suits a robot with 6 action dimensions.
Now press Present or Teach. Explain from memory why a buffer needs Q, how the target draws a fresh action, and why one critic overrates its own best action. Then go back to the hero, run it with one critic and with two, and say where the red gap comes from.
This lesson re-teaches the off-policy actor-critic lecture of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it follow. Silver et al. (2014), deterministic policy gradients; Lillicrap et al., DDPG (2015); Mnih et al. (2015), DQN and target networks; Munos et al., Retrace (2016); Schulman et al., PPO (2017); Fujimoto et al., TD3 (2018); Haarnoja et al., SAC (2018) and its automatic temperature (2018). The toys and numbers here are our own.