Off-Policy Actor-Critic

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.

Reuse experience, then check the critic

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

Why On-Policy Methods Waste Data

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.

Count what a batch buys

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.

10

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.

The road

  1. The replay buffer: keep every step, draw random minibatches.
  2. Importance weights: reweight old data, and see why the weights blow up.
  3. PPO's clip: reuse a batch a few times and stay close. The hero's Reuse ×10.
  4. Learn Q from old data: the critic that any policy's data can train.
  5. The deterministic policy gradient: push the action up the critic's slope.
  6. Target networks: a slow copy that calms the chase.
  7. Overestimation and two critics: the hero's switch, explained.
  8. Entropy and soft actor-critic: pay the policy to stay flexible.
  9. The field guide: terms, numbers, code, and PPO or SAC.
Why can REINFORCE not reuse its batch after one update?

Chapter 1

The Replay Buffer

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.

Fill a buffer and draw from it

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.

60
2

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.

The minibatch has 128 transitions, the agent does 2 gradient steps per environment step, and the buffer holds 500,000. About how many times is one transition used?

Chapter 2

Importance Weights and Why They Blow Up

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.

Say it aloud

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.

ρ(τ)
rho of tau the importance weight of the whole trajectory tau.
∏t=0T−1
the product over t from zero to T minus one multiply one factor for each of the T steps.
π(at|st)
pi of a-t given s-t the target policy's chance of the action taken at step t, in state s-t.
μ(at|st)
mu of a-t given s-t the behavior policy's chance of the same action. It collected the data.
In plain words

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 numbers

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.

Weigh a thousand trajectories

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.

100
0.60

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).

The average squared weight per step is 1.04. You have 1,000 trajectories of 100 steps. About how many do they count as?

Chapter 3

Stay Close: PPO's Clip

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 + ε.

Say it aloud

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.

LCLIP(θ)
L-clip of theta PPO's objective for the batch; gradient steps raise it.
Et
the average over t the average over every step in the batch.
min
the minimum keep the smaller of the two terms, the cautious one.
rt(θ)
r-t of theta the per-step ratio: the new chance of action a-t over the old chance.
Ât
A-hat-t the advantage estimate for step t, fixed when the old policy collected the batch.
clip(r, 1−ε, 1+ε)
r clipped between one minus epsilon and one plus epsilon the ratio held inside the band.
In plain words

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 numbers

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.

Reuse one batch many times

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.

40

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.

A sample has advantage −2, epsilon is 0.2, and its ratio is 0.6. What does PPO's objective give for it?

Chapter 4

Learn Q From Off-Policy Data

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.

Say it aloud

y equals r plus gamma times Q-phi of s-prime and a-prime, with a-prime drawn from pi-theta given s-prime.

y
y the target: the value the critic moves Q-phi of s and a toward.
r
r the stored reward of the transition.
γ
gamma the discount, such as 0.99: a reward one step later counts this much.
Qφ(s′, a′)
Q-phi of s-prime and a-prime the critic's value of the next state s-prime, stored in the buffer, with the action a-prime.
a′ ~ πθ(·|s′)
a-prime drawn from pi-theta given s-prime a fresh action from the current policy, not the one stored in the buffer.
In plain words

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.

With numbers

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.

Fit V or Q on a mixed buffer

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.

50%

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.

Why can Q(s, a) learn from old transitions when V(s) cannot?

Chapter 5

The Deterministic Policy Gradient

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.

Say it aloud

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.

∇θJ
nabla-theta of J the direction to move the actor's weights theta that raises the expected return J fastest.
(1/N) Σi
one over N times the sum over i the average over N states drawn from the buffer.
∇aQ(si, a)|a=μ
nabla-a of Q, at a equals mu-theta of s-i the critic's slope: how fast Q rises as the action moves, measured at the actor's own action.
∇θμθ(si)
nabla-theta of mu-theta of s-i how the action moves when theta moves.
In plain words

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 numbers

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.

Climb the critic

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.

0.10

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.

At the actor's action the critic's slope is −2, and the action moves +0.5 per unit of θ. Which way does one gradient step move θ?

Chapter 6

Target Networks

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).

Say it aloud

Phi-bar becomes tau times phi, plus one minus tau times phi-bar.

φ̄
phi-bar the target copy's weights. Only y uses them; they get no gradient.
←
becomes overwrite the old value, once after each critic update.
τ
tau the mixing rate, between 0 and 1; 0.005 in SAC and TD3.
φ
phi the critic's current weights, which the gradient trains.
In plain words

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 numbers

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.

Chase the target

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.

With tau = 0.01, what share of the gap to the critic does the target copy close in one update?

Chapter 7

Overestimation and Clipped Double Q

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.

Say it aloud

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.

y
y the target that both critics regress toward.
r
r the stored reward.
γ
gamma the discount.
minj=1,2
the minimum over j equals one and two keep the smaller of the two critics' values.
Q̄j(s′, ·)
Q-bar-j of s-prime the target copy of critic j, at the next state s-prime.
ã′
a-tilde-prime the target actor's action plus noise with a standard deviation of 0.2, clipped at 0.5, in TD3.
In plain words

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 numbers

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.

Pick the best of noisy guesses

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.

10
0.50

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.

Why does critic 2's estimate at critic 1's best action have no upward bias?

Chapter 8

Entropy and Soft Actor-Critic

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.

Turn the temperature

Blue is Q over actions, with two hills. The teal area is the policy's chance of each action. Turn alpha down and up.

0.30

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.

Say it aloud

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.

y
y the soft target, for both critics. r and gamma are the reward and the discount.
minj Q̄j(s′, ã′)
the minimum over j of Q-bar-j the smaller target critic value, as in TD3.
α
alpha the temperature: how much one unit of entropy is worth in reward.
log πθ(ã′|s′)
log pi-theta of a-tilde-prime given s-prime the log of the chance the policy gave that action; a negative number for a spread policy.
ã′ ~ πθ(·|s′)
a-tilde-prime drawn from pi-theta given s-prime a fresh sample from the current policy.
In plain words

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 numbers

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.

In SAC's best policy, what happens as alpha goes to zero?

Chapter 9

The Field Guide

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.

The pieces, one fix at a time

PieceProblem it solvesUsed in
Replay bufferEach try used onceDQN, DDPG, TD3, SAC
Per-step ratio + clipTrajectory weights blow up; the policy driftsPPO
Q with fresh a′V is wrong on mixed-policy dataDDPG, TD3, SAC
Deterministic policy gradientNo search over continuous actionsDDPG, TD3
Target networkThe target moves with every updateDQN, DDPG, TD3, SAC
Clipped double QOverestimation creepTD3, SAC
Entropy bonusEarly collapse onto one actionSAC

The numbers from this page

WhatNumberWhy it matters
Robot time to 320,000 gradient steps at 10 Hz2.1 years, 57 hours, 8.9 hoursUse once, PPO, SAC: reuse is the whole game
Uses per transitionG × B = 256 at SAC's settingsBuffer size does not change it
1.04 to the power 100about 501,000 trajectories count as 20
PPO gradient steps per batch32010 passes of 2,048 steps in minibatches of 64
Soft update half-life at tau 0.005138 updatesHow far the target lags
Best of 10 estimates at ±0.5+0.77; min of two −0.02Selection makes the bias; a second critic cancels it
SAC defaultsbuffer 1M, batch 256, lr 0.0003, gamma 0.99, tau 0.005A safe start for continuous control

PPO or SAC

QuestionPPOSAC
DataEach batch reused about 10 times, then droppedEvery transition kept in a buffer
Best whenSimulation is cheap and runs in parallelEach step is expensive, as on a real robot
ActionsDiscrete or continuousMainly continuous
Main riskDrift after too many passesCritic errors that the actor exploits
Known usesInstructGPT's RLHF step (Ouyang et al., 2022)Real-robot locomotion (Haarnoja et al., 2018)

Before you trust an off-policy run

One SAC update

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.

Keep going

The takeaway. Off-policy learning reuses old experience by learning Q, which holds for any action, and drawing the next action fresh. The rest keeps that critic honest: a slow target copy, the smaller of two critics, and an entropy bonus.
A robot takes 10 seconds per attempt, and simulation is not available. Which method fits better, and why?

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.

Credit and source

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.

CS 224R: Off-Policy Actor-Critic
The course site · SAC · TD3 · Back to Gleams