Skip to content
Reinforcement learning Advanced 36 min read

Actor-critic and PPO

An actor-critic learns two things at once: a policy that acts, and a value function that judges each action against what the policy usually achieves. That judgement, the advantage, is what makes policy gradients usable. PPO then adds one idea, never trust your own gradient far from the policy that collected the data, and turns it into a ten-line loss that has trained everything from Dota bots to ChatGPT.

10,000 ft

REINFORCE is unbiased but so noisy that a single episode's gradient estimate can have a standard deviation twenty times its mean. Q-learning is data-efficient but brittle and awkward with continuous actions. Actor-critic methods take the best of each: a policy network (actor) trained by policy gradient, weighted by a value network (critic) trained by temporal-difference learning. Around that core sit the two ideas that made deep policy optimisation reliable: generalised advantage estimation (GAE), a single knob between low-variance TD and unbiased Monte Carlo; and trust regions (TRPO, then PPO), which stop a step from wrecking the policy that generates your next data. PPO became the default on-policy algorithm from 2017, ran OpenAI Five, and was the RL step in RLHF; its critic-free descendants (RLOO, GRPO) train today's reasoning models. On the off-policy side, the same actor-plus-critic shape gives DDPG, TD3 and SAC, the workhorses of continuous control.

2,000 ft

One PPO iteration:

  1. Collect a batch: run the current policy \(\pi_{\theta_\text{old}}\) in \(N\) environments for \(T\) steps each, storing states, actions, rewards and \(\log\pi_{\theta_\text{old}}(a\mid s)\).
  2. Judge every step with the critic: TD errors \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\), summed with weights \((\gamma\lambda)^k\) into advantages \(\hat A_t\) (GAE).
  3. Improve the actor for a few epochs over the batch, maximising \(\min\big(r_t\hat A_t,\ \operatorname{clip}(r_t, 1-\epsilon, 1+\epsilon)\hat A_t\big)\), where \(r_t = \pi_\theta(a_t\mid s_t)/\pi_{\theta_\text{old}}(a_t\mid s_t)\). The clip removes any incentive to move an action's probability more than about 20% per iteration.
  4. Refit the critic by regression onto the returns \(\hat A_t + V(s_t)\).
  5. Discard the batch and repeat: the method is on-policy.

Actor-critic with PPO: collect, judge, improve within a trust region
Actor-critic with PPO: collect, judge, improve within a trust region. Environments (N parallel copies), Actor π_θ(a | s), Batch of N·T steps (s, a, r, log π_old), Critic V_φ(s), GAE: Â_t = Σ (γλ)^k δ_(t+k), Clipped surrogate min(r·Â, clip(r)·Â), Value regression (V − return)², actions, rewards, next states, states, V(s_t), rewards, advantages, K epochs of minibatch Adam, targetsActor-critic with PPO: collect, judge, improve within a trust region. Environments (N parallel copies), Actor π_θ(a | s), Batch of N·T steps (s, a, r, log π_old), Critic V_φ(s), GAE: Â_t = Σ (γλ)^k δ_(t+k), Clipped surrogate min(r·Â, clip(r)·Â), Value regression (V − return)², actions, rewards, next states, states, V(s_t), rewards, advantages, K epochs of minibatch Adam, targets

Ground level

From REINFORCE to actor-critic

The policy-gradient theorem says

\[ \nabla_\theta J = \mathbb E\Big[\sum_t \nabla_\theta\log\pi_\theta(a_t\mid s_t)\,\big(G_t - b(s_t)\big)\Big]. \]

REINFORCE plugs in the sampled return \(G_t\), which depends on every later random action and transition, and that is where the variance comes from. The expected value of \(G_t\) given \((s_t,a_t)\) is \(Q^\pi(s_t,a_t)\); with the baseline \(b = V^\pi\), the ideal weight is the advantage

\[ A^\pi(s,a) = Q^\pi(s,a) - V^\pi(s), \]

how much better this action was than the policy's average from here. We do not know \(A^\pi\), but a learned state-value function \(V_\phi \approx V^\pi\) gives a one-sample estimate that looks only one step ahead, the TD error:

\[ \delta_t = r_{t+1} + \gamma V_\phi(s_{t+1}) - V_\phi(s_t), \qquad \mathbb E[\delta_t \mid s_t, a_t] = Q^\pi(s_t,a_t) - V^\pi(s_t) \ \text{ when } V_\phi = V^\pi . \]

That gives the one-step actor-critic (Sutton and Barto, section 13.5): after every transition,

\[ \phi \leftarrow \phi + \beta\,\delta_t\,\nabla_\phi V_\phi(s_t), \qquad \theta \leftarrow \theta + \alpha\,\delta_t\,\nabla_\theta\log\pi_\theta(a_t\mid s_t). \]

The critic is doing TD(0) policy evaluation; the actor is doing policy gradient with the critic's verdict as its weight. One number, \(\delta_t\), drives both.

Worked example: one actor-critic step

The critic says \(V(s) = 2.0\). You take action \(a\), receive \(r = 1\), land in \(s'\) with \(V(s') = 1.5\); \(\gamma = 0.9\). Then \(\delta = 1 + 0.9 \times 1.5 - 2.0 = 0.35\). The outcome was 0.35 better than the critic expected, so the actor raises \(\log\pi(a\mid s)\) in proportion to 0.35 and the critic raises \(V(s)\) toward 2.35. Had the reward been 0, \(\delta = -0.65\) and both would move the other way. Compare REINFORCE, which would have waited for the end of the episode and used the whole noisy return.

The price is bias. \(\delta_t\) is an unbiased advantage estimate only if \(V_\phi = V^\pi\) exactly, and the critic is always somewhat wrong, and wrong in a way that is correlated with the actor's current behaviour. The two learners also chase each other: the critic evaluates a policy that keeps changing, and the actor follows a critic that keeps changing. Convergence proofs (Konda and Tsitsiklis, 1999) require the critic to learn on a faster time scale than the actor, which is the theoretical reason practical implementations take more or larger critic steps.

Between TD and Monte Carlo: n-step returns and GAE

One step of look-ahead is the low-variance, high-bias end of a spectrum. Look \(n\) steps ahead before trusting the critic:

\[ \hat A^{(n)}_t = r_{t+1} + \gamma r_{t+2} + \dots + \gamma^{n-1} r_{t+n} + \gamma^n V(s_{t+n}) - V(s_t) = \sum_{k=0}^{n-1}\gamma^k\delta_{t+k}. \]

The right-hand identity is a telescoping sum: the intermediate \(V\) terms cancel. At \(n = \infty\) it is \(G_t - V(s_t)\), the Monte Carlo advantage, whose bias does not depend on the critic at all. Schulman et al.'s generalised advantage estimator (2015) averages all the \(n\)-step estimators with geometric weights \((1-\lambda)\lambda^{n-1}\), which collapses to

\[ \hat A^{\text{GAE}(\gamma,\lambda)}_t = \sum_{k=0}^{\infty}(\gamma\lambda)^k\,\delta_{t+k}, \qquad \text{computed backwards as } \hat A_t = \delta_t + \gamma\lambda\,\hat A_{t+1}. \]

\(\lambda = 0\) gives the one-step TD error; \(\lambda = 1\) gives the Monte Carlo advantage. It is the same idea as TD(\(\lambda\)), applied to advantages.

Worked example: GAE on a three-step episode

Rewards \((0, 0, 1)\), then the episode ends. The critic says \(V(s_0), V(s_1), V(s_2) = 0.5, 0.6, 0.8\); \(\gamma = 0.9\). TD errors: \(\delta_0 = 0 + 0.9(0.6) - 0.5 = 0.04\), \(\delta_1 = 0 + 0.9(0.8) - 0.6 = 0.12\), \(\delta_2 = 1 - 0.8 = 0.2\). Working backwards with \(\gamma\lambda\):

\(\lambda\) \(\hat A_0\) \(\hat A_1\) \(\hat A_2\)
0 (pure TD) 0.04 0.12 0.2
0.5 0.1345 0.21 0.2
0.95 0.2888 0.291 0.2
1 (Monte Carlo) 0.31 0.30 0.2

The \(\lambda = 1\) row equals \(G_t - V(s_t)\): \(0.81 - 0.5\), \(0.9 - 0.6\), \(1 - 0.8\). With \(\lambda = 0\), step 0 is credited only with the critic's small change of mind (0.04); with \(\lambda = 1\) it is credited with the reward that actually arrived two steps later.

How much does the choice matter? Take an 11-state random walk with a deliberately noisy critic (each value off by about 0.15) and estimate, at the middle state, the gap between the advantages of going right and going left. That gap is all a policy gradient at that state sees, and its true value is 0.2. From 4,000 episodes each (Build it):

lambda  0.0: A(right) - A(left) = 0.476 (bias +0.276),  per-sample std 0.000
lambda  0.5: A(right) - A(left) = 0.357 (bias +0.157),  per-sample std 0.069
lambda  0.9: A(right) - A(left) = 0.245 (bias +0.045),  per-sample std 0.201
lambda 0.95: A(right) - A(left) = 0.213 (bias +0.013),  per-sample std 0.270
lambda  1.0: A(right) - A(left) = 0.207 (bias +0.007),  per-sample std 0.489

The trade-off is exactly as advertised. At \(\lambda = 0\) the estimate has zero variance (this walk's rewards are deterministic one step out) but is 2.4 times too large, because it trusts a wrong critic completely. At \(\lambda = 1\) the bias is within noise but the per-sample standard deviation is 0.49, 2.4 times the signal. \(\lambda\) between 0.9 and 0.95 removes most of the bias at about half the standard deviation, which is why PPO's defaults use 0.95 and a 250,000-agent study (Andrychowicz et al., 2020) recommends 0.9. Note what \(\gamma\) and \(\lambda\) do differently: \(\gamma < 1\) changes the objective (it discounts the future, a bias even with a perfect critic), while \(\lambda < 1\) only changes how much you trust the critic. Schulman et al. found the best \(\lambda\) is typically well below the best \(\gamma\).

A2C and A3C: many actors, one loss

Deep actor-critic agents share one network torso between actor and critic (or use two networks) and minimise a single combined loss over a batch:

\[ \mathcal L(\theta,\phi) = \underbrace{-\hat{\mathbb E}_t\big[\hat A_t\log\pi_\theta(a_t\mid s_t)\big]}_{\text{actor}} + c_1\,\underbrace{\hat{\mathbb E}_t\big[(V_\phi(s_t) - \hat R_t)^2\big]}_{\text{critic}} - c_2\,\underbrace{\hat{\mathbb E}_t\big[\mathcal H(\pi_\theta(\cdot\mid s_t))\big]}_{\text{entropy bonus}}, \]

with \(\hat R_t = \hat A_t + V(s_t)\) the critic's regression target and \(\hat A_t\) treated as a constant. The entropy bonus pushes against premature determinism: policy gradients self-reinforce (likely actions get sampled, then made likelier), and once a policy is deterministic it stops exploring and its gradient stops carrying information about alternatives.

Mnih et al.'s A3C (2016) ran many actor-learners in parallel CPU threads, each with its own copy of the environment, applying gradients asynchronously to shared parameters. Parallel actors decorrelate the data in a batch, the job experience replay did for DQN, but without replay, so on-policy methods could use it. The paper reports beating the then state of the art on Atari "while training for half the time on a single multi-core CPU instead of a GPU". The synchronous version, A2C, steps all environments in lockstep and makes one batched update; it is simpler, uses a GPU well, and is the usual form today. IMPALA (Espeholt et al., 2018) decouples many actors from one central learner and corrects for the actors' slightly stale policies with truncated importance weights (V-trace), the template for large distributed RL systems.

The real problem is step size

Here is the failure mode that dominates on-policy RL. A policy-gradient step is estimated from data collected by the current policy. If the step is too large, the new policy behaves differently in ways the batch said nothing about. Performance can collapse, and because the collapsed policy collects the next batch, it may never recover. In supervised learning the dataset does not change when you make a bad step; in RL it does.

To see what a safe step is, ask exactly how much better a new policy \(\pi'\) is than the old \(\pi\). The performance difference lemma (Kakade and Langford, 2002) answers exactly:

\[ J(\pi') - J(\pi) = \frac{1}{1-\gamma}\;\mathbb E_{s\sim d^{\pi'},\ a\sim\pi'(\cdot\mid s)}\big[A^\pi(s,a)\big]. \]

The improvement is the old policy's advantages, averaged over the states and actions of the new policy. The actions are easy: reweight samples from \(\pi\) by the ratio \(\pi'(a\mid s)/\pi(a\mid s)\). The states are the problem, since we have no samples from \(d^{\pi'}\). Replacing \(d^{\pi'}\) by \(d^\pi\) gives the surrogate objective

\[ L_\pi(\pi') = \frac{1}{1-\gamma}\;\mathbb E_{s\sim d^{\pi},\ a\sim\pi}\Big[\frac{\pi'(a\mid s)}{\pi(a\mid s)}\,A^\pi(s,a)\Big], \]

which matches \(J(\pi') - J(\pi)\) to first order at \(\pi' = \pi\) (its gradient there is exactly the policy gradient) and drifts away from it as the policies separate. Schulman et al.'s TRPO (2015) bounded the drift: with \(\epsilon = \max_{s,a}|A^\pi(s,a)|\),

\[ J(\pi') - J(\pi) \;\ge\; L_\pi(\pi') - \frac{4\epsilon\gamma}{(1-\gamma)^2}\,\max_s D_{\mathrm{KL}}\big(\pi(\cdot\mid s)\,\|\,\pi'(\cdot\mid s)\big). \]

Maximise the right-hand side and you can never get worse: at \(\pi' = \pi\) it equals zero, so its maximum is \(\ge 0\). That is a minorise–maximise algorithm with a monotonic-improvement guarantee. The penalty coefficient is hopelessly conservative in practice (with \(\gamma = 0.99\) it is \(40{,}000\,\epsilon\)), so TRPO instead solves

\[ \max_{\theta}\ L_{\theta_\text{old}}(\theta) \quad\text{subject to}\quad \hat{\mathbb E}_s\big[D_{\mathrm{KL}}(\pi_{\theta_\text{old}}(\cdot\mid s)\,\|\,\pi_\theta(\cdot\mid s))\big] \le \delta , \]

with \(\delta = 0.01\) in all the paper's experiments. Linearising the objective and taking a quadratic approximation of the KL gives the natural gradient direction \(F^{-1}g\); TRPO computes it with conjugate gradient (never forming the Fisher matrix \(F\)), then backtracks along it until the KL constraint holds and the surrogate actually improves.

PPO: a trust region you can implement in ten lines

TRPO works but is complicated: second-order machinery, a line search, awkward with shared actor–critic networks or dropout. Schulman et al.'s Proximal Policy Optimization (2017) asked for the same effect with plain first-order SGD. Write \(r_t(\theta) = \pi_\theta(a_t\mid s_t)/\pi_{\theta_\text{old}}(a_t\mid s_t)\), so the surrogate is \(\hat{\mathbb E}_t[r_t\hat A_t]\). PPO's clipped objective is

\[ L^{\text{CLIP}}(\theta) = \hat{\mathbb E}_t\Big[\min\big(r_t(\theta)\hat A_t,\ \operatorname{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon)\,\hat A_t\big)\Big], \qquad \epsilon = 0.2 . \]
1−ε11+ε2advantage A > 0rflat: no gradientr·A1−ε11+ε2advantage A < 0rflat: no gradientr·A, unclipped
One term of PPO's objective, min(r·A, clip(r, 1−ε, 1+ε)·A), against the probability ratio r (solid), with the unclipped surrogate r·A (dashed). The dot is where every update starts, r = 1. Once a good action is already 20% more likely than under the old policy, or a bad one 20% less likely, the term goes flat and stops pulling. In the direction that makes the objective worse, it is never clipped: the min keeps the pessimistic branch.

Read it case by case. For a good action (\(\hat A > 0\)) the objective rewards raising its probability until \(r = 1+\epsilon\), then goes flat: no gradient, so no incentive to push further on this batch. For a bad action (\(\hat A < 0\)) it rewards lowering the probability until \(r = 1-\epsilon\), then goes flat. The \(\min\) means the clip only ever removes optimism. If an update has accidentally made a bad action more likely (\(\hat A < 0\), \(r > 1+\epsilon\)), the unclipped term is the smaller one, so it stays, with its gradient pushing the probability back down.

Worked example: four terms of the clipped objective, ε = 0.2

  • \(\hat A = +2\), \(r = 1.1\): \(\min(2.2,\ 2.2) = 2.2\). Inside the range; gradient \(2\,\nabla r\).
  • \(\hat A = +2\), \(r = 1.3\): \(\min(2.6,\ 1.2 \times 2 = 2.4) = 2.4\). Clipped; gradient zero.
  • \(\hat A = -1\), \(r = 0.7\): \(\min(-0.7,\ 0.8 \times (-1) = -0.8) = -0.8\). Clipped; gradient zero.
  • \(\hat A = -1\), \(r = 1.5\): \(\min(-1.5,\ -1.2) = -1.5\). Not clipped: the term still pulls \(r\) back down.

The fraction of terms whose gradient is zero is the clip fraction, the first number to watch in a PPO training log.

What the clip buys is data reuse. Vanilla policy gradient takes one step per batch, because after one step the batch is off-policy. PPO takes \(K\) epochs of minibatch steps on the same batch, and the clip stops those steps from over-fitting it. The experiment in Build it shows this directly on a 5-armed bandit, with 16 samples per batch and 25 iterations, averaged over 500 runs:

epochs | method   | final J (best 1.0) | P(best arm is argmax) | max prob | KL per update
     1 | no clip  |      0.890         |        92.4%          |  0.72    |  0.005
     1 | clip 0.2 |      0.890         |        92.4%          |  0.72    |  0.005
     5 | no clip  |      0.952         |        86.4%          |  0.92    |  0.062
     5 | clip 0.2 |      0.935         |        89.0%          |  0.84    |  0.015
    20 | no clip  |      0.785         |        43.4%          |  0.99    |  0.472
    20 | clip 0.2 |      0.946         |        90.2%          |  0.87    |  0.020
    80 | no clip  |      0.769         |        39.0%          |  1.00    |  0.463
    80 | clip 0.2 |      0.953         |        88.2%          |  0.88    |  0.028

Five epochs per batch beat one (final \(J\) 0.95 against 0.89): reuse helps. Without clipping, 20 or more epochs over-fit each noisy batch: the policy becomes nearly deterministic after the first iteration (max probability 0.99, KL 0.47 per update) on whatever arm that batch happened to favour, and picks the best arm in only 43% of runs. With the clip, the same 20 or 80 epochs keep KL near 0.02 per update, and the final policy is both better and still exploring.

The full PPO loop:

  1. Run \(N\) actors for \(T\) steps each with \(\pi_{\theta_\text{old}}\); store \(\log\pi_{\theta_\text{old}}\).
  2. Compute \(\hat A_t\) with GAE and returns \(\hat R_t = \hat A_t + V(s_t)\).
  3. For \(K\) epochs, shuffle the \(NT\) steps into minibatches; on each, take an Adam step on \(-L^{\text{CLIP}} + c_1 L^{\text{VF}} - c_2\,\mathcal H\).
  4. Set \(\theta_\text{old} \leftarrow \theta\) and repeat.

The paper's settings, from its appendix tables:

MuJoCo (1M steps) Atari
Horizon \(T\) (steps per actor per iteration) 2048 128, with 8 actors
Epochs \(K\) 10 3
Minibatch 64 32 × 8
Adam learning rate \(3\times10^{-4}\) \(2.5\times10^{-4}\), annealed linearly to 0
Clip \(\epsilon\) 0.2 0.1, annealed linearly to 0
\(\gamma\), \(\lambda\) 0.99, 0.95 0.99, 0.95
Value / entropy coefficients separate networks, no entropy bonus \(c_1 = 1\), \(c_2 = 0.01\)

And its ablation on seven MuJoCo tasks (normalised score, 1 = best run, 0 = random policy): no clipping or penalty −0.39 (worse than random, because one task diverged); clipping with \(\epsilon\) = 0.1, 0.2, 0.3: 0.76, 0.82, 0.70; the best adaptive-KL-penalty setting 0.74; the best fixed-KL-penalty setting 0.72 (Schulman et al., 2017, Table 1).

Two different KLs

PPO's paper also proposes a KL-penalty variant: maximise \(r_t\hat A_t - \beta\, D_{\mathrm{KL}}(\pi_{\theta_\text{old}}\|\pi_\theta)\), halving \(\beta\) when the measured KL falls below \(d_\text{targ}/1.5\) and doubling it above \(1.5\,d_\text{targ}\). That KL is to the previous iterate: a step-size control. The KL penalty in RLHF is to a frozen reference model (the SFT model), added to the reward to stop the policy drifting into reward-model exploits. Same formula, different job; RLHF with PPO uses both.

What the paper does not tell you

PPO's reputation for robustness comes partly from details that live in the code, not the paper. Engstrom et al. (Implementation Matters in Deep Policy Gradients, 2020) listed the "code-level optimisations" in OpenAI's reference implementation: value-function clipping, reward scaling by a running estimate of the discounted return's standard deviation, orthogonal initialisation with per-layer scales, learning-rate annealing, reward clipping, observation normalisation and clipping, tanh activations, and global gradient-norm clipping at 0.5. Their ablations found these responsible for most of PPO's gain in reward over TRPO. They also showed that the clip does not, on its own, enforce a trust region. The first gradient step of each iteration starts at \(r = 1\), where the clipped and unclipped objectives are identical, so how far the policy moves depends on the learning rate and number of steps, not on \(\epsilon\). Huang et al.'s blog post The 37 Implementation Details of PPO (ICLR blog track, 2022) reproduces the reference implementation line by line.

Andrychowicz et al. (What Matters in On-Policy RL?, 2020) trained over 250,000 agents across more than 50 design choices on continuous control. Their recommendations: use the PPO loss and start with \(\epsilon = 0.25\); initialise the policy's last layer with 100× smaller weights, so the initial action distribution is centred and narrow; always normalise observations; GAE with \(\lambda = 0.9\); neither Huber loss nor PPO-style value clipping; separate policy and value networks; treat \(\gamma\) as one of the most important hyperparameters (start at 0.99); Adam with learning rate \(3\times10^{-4}\) as a safe default.

What to watch in a PPO run

Approximate KL between old and new policy per iteration; clip fraction; policy entropy; the critic's explained variance \(1 - \operatorname{Var}[\hat R - V]/\operatorname{Var}[\hat R]\) (near 0 or negative means the critic is useless and your advantages are mostly noise); and returns. A rising KL or clip fraction means steps are too big; entropy collapsing early means the policy stopped exploring. Many implementations stop the epochs early once the KL passes a target.

Off-policy actor-critic: DDPG, TD3 and SAC

PPO throws every batch away after a few epochs. For continuous control, where interaction is expensive (a robot, a slow simulator), the alternative is to keep a replay buffer, as DQN does, and learn a Q-function critic off-policy. The actor's job is then to do the \(\max_a Q(s,a)\) that Q-learning cannot do over a continuous action.

  • DDPG (Lillicrap et al., 2015): a deterministic actor \(\mu_\theta(s)\) trained by the deterministic policy gradient \(\nabla_\theta J = \mathbb E[\nabla_a Q(s,a)\rvert_{a=\mu(s)} \nabla_\theta\mu_\theta(s)]\) (Silver et al., 2014). It backpropagates through the critic into the action, a pathwise gradient rather than a score-function one. The critic is DQN's: replay, target networks (updated slowly by Polyak averaging), exploration by adding noise to actions. It is sample-efficient and notoriously brittle.
  • TD3 (Fujimoto, van Hoof and Meger, 2018) fixes DDPG's overestimation, the same maximisation bias as in Q-learning, now produced by an actor that hunts for the critic's errors. Three changes: clipped double Q (two critics, use the minimum in the target); delayed policy updates (actor and targets updated every \(d = 2\) critic steps); and target policy smoothing (add \(\mathcal N(0, 0.2)\) noise, clipped to \(\pm0.5\), to the target action, so the critic cannot exploit a sharp peak).
  • SAC (Haarnoja et al., 2018) optimises a maximum-entropy objective, \(\mathbb E\big[\sum_t r_t + \alpha\,\mathcal H(\pi(\cdot\mid s_t))\big]\): be rewarded, and stay as random as you can while doing so. The actor is a squashed Gaussian trained by reparameterisation; the critics are twin soft Q-functions with the minimum trick. The follow-up paper tunes the temperature \(\alpha\) automatically, to hold the policy's entropy near a target, \(-\dim(\mathcal A)\) by default. SAC is a common first choice for continuous control from low-dimensional states.
The actor-critic family: on-policy with a V critic, off-policy with a Q critic
The actor-critic family: on-policy with a V critic, off-policy with a Q critic. Actor-critic (Barto, Sutton, Anderson 1983), A3C / A2C 2016 parallel actors, GAE 2015 λ-weighted advantages, TRPO 2015 KL trust region, PPO 2017 clipped ratio, IMPALA 2018 V-trace, distributed, DPG 2014 / DDPG 2015 actor maximises Q, TD3 2018 twin critics, delays, SAC 2018 maximum entropy, PPO in RLHF 2019–22 then RLOOThe actor-critic family: on-policy with a V critic, off-policy with a Q critic. Actor-critic (Barto, Sutton, Anderson 1983), A3C / A2C 2016 parallel actors, GAE 2015 λ-weighted advantages, TRPO 2015 KL trust region, PPO 2017 clipped ratio, IMPALA 2018 V-trace, distributed, DPG 2014 / DDPG 2015 actor maximises Q, TD3 2018 twin critics, delays, SAC 2018 maximum entropy, PPO in RLHF 2019–22 then RLOO

The trade-off between the two branches is fundamental, not incidental. On-policy methods estimate the gradient of the objective you care about from the right distribution, so they are stable and simple, and waste data. Off-policy methods reuse every transition many times, so they are sample-efficient, and inherit the deadly triad: a bootstrapped Q-function, learned off-policy with a network, can diverge, which is why TD3 and SAC carry so many stabilisers.

Where PPO went

Games. OpenAI Five, a Dota 2 team trained by PPO through self-play on batches of about 2 million frames every 2 seconds, trained continually for 10 months and on 13 April 2019 beat the reigning world champions, Team OG (OpenAI et al., 2019). Language models. InstructGPT and the original ChatGPT used PPO against a learned reward model, with the actor, critic, reward model and frozen reference model all held in memory: four copies of a large network (RLHF with PPO). The critic is the expensive part. With a single reward at the end of a completion, a token-level value network is hard to learn well, and the group baselines of RLOO and GRPO replace it by comparing several samples of the same prompt (RL with verifiable rewards). They keep PPO's clipped ratio. The trust region outlived the critic.

History

The actor-critic architecture predates deep learning by three decades: Barto, Sutton and Anderson's 1983 pole-balancer had an "associative search element" (the actor) and an "adaptive critic element" whose TD error trained both. Konda and Tsitsiklis (1999) proved convergence for actor-critic with linear critics on two time scales. Kakade and Langford (2002) introduced conservative policy iteration and the performance difference lemma, and Kakade's natural gradient (2001) supplied the geometry; Peters and Schaal combined them in the natural actor-critic (2008). John Schulman's Berkeley PhD work turned this into TRPO and GAE (both 2015) and, at OpenAI, PPO (2017). The same years produced A3C (2016), DDPG (2015), TD3 and SAC (2018), and by 2018 the landscape on this page was in place. What changed after was scale and application: OpenAI Five, robot hands, and from 2019 the fine-tuning of language models from human feedback.

First principles

Why a critic reduces variance. \(G_t\) is a sample of a random variable whose mean, given \((s_t, a_t)\), is \(Q^\pi(s_t,a_t)\). Replacing a random variable by its conditional expectation can only lower variance (the law of total variance), and subtracting \(V^\pi(s_t)\) removes the part that is the same for every action. The critic is an attempt to compute those conditional expectations by learning, instead of averaging over many rollouts.

Why a critic adds bias, and why λ controls it. In \(\hat A^{(n)}_t\) the critic enters only through \(\gamma^n V(s_{t+n}) - V(s_t)\). The \(-V(s_t)\) term is a state-dependent baseline and costs nothing in expectation; the \(\gamma^nV(s_{t+n})\) term substitutes a guess for the real future. Its error is multiplied by \(\gamma^n\) (\((\gamma\lambda)^k\) weights in GAE), so a larger \(\lambda\) leans less on the critic's guesses about the far future. That is why the random-walk experiment's bias falls from +0.276 to +0.007 as \(\lambda\) goes from 0 to 1, while the variance, which comes from summing more random rewards, rises.

Why you need a trust region at all. The policy gradient is a local, first-order statement: it is the slope of \(J\) at \(\theta\), estimated from samples at \(\theta\). The performance difference lemma says the true improvement depends on the new policy's state distribution. The surrogate pretends it is the old one, and the TRPO bound says the error of that pretence grows with the KL between the policies. Any method that takes steps of fixed size in parameter space ignores this; methods that bound the step in distribution space respect it.

Why the minimum. \(L^{\text{CLIP}} \le L^{\text{CPI}}\) term by term, with equality near \(r = 1\): the clipped objective is a pessimistic bound on the surrogate. Pessimism is the right bias when the surrogate is least trustworthy far from \(\theta_\text{old}\). Where moving further would look better on the batch, PPO ignores it; where it would look worse, PPO listens.

Why entropy, in both branches. A policy gradient on a softmax policy makes the sampled actions more likely, and more likely actions get sampled more: a rich-get-richer dynamic that collapses entropy unless something opposes it. PPO adds an entropy bonus; SAC builds entropy into the objective. The soft-optimal policy of SAC's objective is a Boltzmann distribution, \(\pi(a\mid s) \propto \exp(Q_\text{soft}(s,a)/\alpha)\); the KL-regularised objective of RLHF has the same shape, with the reference model in place of the uniform distribution (offline RL and LLMs derives it).

The maths

Notation. \(\pi_\theta\) actor, \(V_\phi\) critic, \(\gamma\) discount, \(\lambda\) GAE parameter, \(d^\pi(s) = (1-\gamma)\sum_t\gamma^t\Pr(s_t = s\mid\pi)\) the normalised discounted state-visitation distribution, \(A^\pi = Q^\pi - V^\pi\).

Actor-critic gradient. \(\nabla_\theta J = \frac{1}{1-\gamma}\,\mathbb E_{s\sim d^\pi,\,a\sim\pi} \big[A^\pi(s,a)\,\nabla_\theta\log\pi_\theta(a\mid s)\big]\), the policy-gradient theorem with the baseline \(V^\pi\).

Derivation: GAE is the λ-average of n-step advantages

With \(\delta_k = r_{k+1} + \gamma V(s_{k+1}) - V(s_k)\), the \(n\)-step advantage telescopes:

\[ \sum_{k=0}^{n-1}\gamma^k\delta_{t+k} = \sum_{k=0}^{n-1}\gamma^k r_{t+k+1} + \sum_{k=0}^{n-1}\big(\gamma^{k+1}V(s_{t+k+1}) - \gamma^kV(s_{t+k})\big) = \sum_{k=0}^{n-1}\gamma^k r_{t+k+1} + \gamma^nV(s_{t+n}) - V(s_t) = \hat A^{(n)}_t . \]

Now average with weights \((1-\lambda)\lambda^{n-1}\), which sum to 1:

\[ (1-\lambda)\sum_{n\ge1}\lambda^{n-1}\sum_{k=0}^{n-1}\gamma^k\delta_{t+k} = (1-\lambda)\sum_{k\ge0}\gamma^k\delta_{t+k}\sum_{n\ge k+1}\lambda^{n-1} = (1-\lambda)\sum_{k\ge0}\gamma^k\delta_{t+k}\,\frac{\lambda^k}{1-\lambda} = \sum_{k\ge0}(\gamma\lambda)^k\delta_{t+k}. \]

For a finite episode, \(V(s_T) = 0\) at a terminal state and the sum stops at \(T-1\); for a truncated rollout, you bootstrap from \(V(s_T)\) of the last observed state.

Derivation: the performance difference lemma

For any two policies, telescoping along a trajectory of \(\pi'\):

\[ \mathbb E_{\tau\sim\pi'}\Big[\sum_t\gamma^t A^\pi(s_t,a_t)\Big] = \mathbb E_{\tau\sim\pi'}\Big[\sum_t\gamma^t\big(r_{t+1} + \gamma V^\pi(s_{t+1}) - V^\pi(s_t)\big)\Big] = \mathbb E_{\tau\sim\pi'}\Big[\sum_t\gamma^t r_{t+1}\Big] - \mathbb E_{s_0}\big[V^\pi(s_0)\big] = J(\pi') - J(\pi). \]

The first equality uses \(\mathbb E[r_{t+1} + \gamma V^\pi(s_{t+1})\mid s_t,a_t] = Q^\pi(s_t,a_t)\) (the transitions are the environment's, whichever policy chose \(a_t\)); the second cancels the \(V^\pi\) terms pairwise, leaving \(-V^\pi(s_0)\). Writing the expectation over time as one over the discounted visitation distribution gives the \(\frac{1}{1-\gamma}\mathbb E_{s\sim d^{\pi'}}\) form.

TRPO. Maximise \(L_{\theta_\text{old}}(\theta) = \hat{\mathbb E}_t[r_t(\theta)\hat A_t]\) subject to \(\hat{\mathbb E}_s[D_\mathrm{KL}(\pi_{\theta_\text{old}}\|\pi_\theta)] \le \delta\). With \(g = \nabla L\) and the Fisher matrix \(F\) (the KL's Hessian at \(\theta_\text{old}\)), the approximate solution is \(\Delta\theta = \sqrt{2\delta/(g^\top F^{-1}g)}\,F^{-1}g\), found by conjugate gradient using only Fisher-vector products, then shrunk by a backtracking line search.

PPO, with shapes. For a batch of \(B\) steps: log-probabilities under the current and old policy \(\boldsymbol\ell, \boldsymbol\ell^\text{old} \in \mathbb R^B\); advantages \(\hat{\mathbf A} \in \mathbb R^B\) (normalised to zero mean and unit variance per minibatch in most implementations, held constant); returns \(\hat{\mathbf R} \in \mathbb R^B\); values \(\mathbf v \in \mathbb R^B\); entropies \(\mathbf h \in \mathbb R^B\).

\[ \mathbf r = \exp(\boldsymbol\ell - \boldsymbol\ell^\text{old}),\qquad \mathcal L = -\frac1B\sum_i\min\big(r_i\hat A_i,\ \operatorname{clip}(r_i,1-\epsilon,1+\epsilon)\hat A_i\big) + \frac{c_1}{B}\sum_i (v_i - \hat R_i)^2 - \frac{c_2}{B}\sum_i h_i . \]

The gradient of one clipped term is \(\hat A_i\,r_i\,\nabla_\theta\log\pi_\theta(a_i\mid s_i)\) if the term is unclipped, and 0 if \(\hat A_i > 0,\ r_i > 1+\epsilon\) or \(\hat A_i < 0,\ r_i < 1-\epsilon\). Note the ratio \(r_i\) multiplying the score: it is the importance weight that corrects for the batch coming from \(\pi_{\theta_\text{old}}\).

DDPG/TD3 critic target. \(y = r + \gamma(1-d)\min_{j=1,2} Q_{\phi_j^-}\big(s',\ \operatorname{clip}(\mu_{\theta^-}(s') + \operatorname{clip}(\varepsilon,-c,c), a_\text{low}, a_\text{high})\big)\), \(\varepsilon\sim\mathcal N(0,\sigma^2)\); DDPG is the special case with one critic and no noise.

SAC. Soft Bellman target \(y = r + \gamma(1-d)\big(\min_j Q_{\phi_j^-}(s',\tilde a') - \alpha\log\pi_\theta(\tilde a'\mid s')\big)\) with \(\tilde a'\sim\pi_\theta(\cdot\mid s')\). Actor loss \(\mathbb E_{s,\ \varepsilon}\big[\alpha\log\pi_\theta(\tilde a\mid s) - \min_j Q_{\phi_j}(s,\tilde a)\big]\) with \(\tilde a = \tanh(\mu_\theta(s) + \sigma_\theta(s)\odot\varepsilon)\), differentiated through \(\tilde a\) (reparameterisation). Temperature loss \(\mathbb E\big[-\alpha\,(\log\pi_\theta(\tilde a\mid s) + \bar{\mathcal H})\big]\), with target entropy \(\bar{\mathcal H} = -\dim(\mathcal A)\): if the policy's entropy falls below the target, \(\alpha\) rises.

Common misconceptions

  • "PPO enforces a KL trust region." It removes the incentive to move far, for each sampled action; it does not bound the KL. The step size still depends on learning rate, epochs and minibatch count, which is why implementations also monitor the KL and stop early.
  • "The critic must be accurate for the policy gradient to be right." Only the part of \(\hat A\) that comes from bootstrapping (\(\gamma^nV(s_{t+n})\) terms) introduces bias. The \(V(s_t)\) baseline term never does; with \(\lambda = 1\) the gradient is unbiased whatever the critic.
  • "Off-policy means more sample-efficient, so always better." Better per sample, often worse per hour and less stable. With a fast simulator, PPO with thousands of parallel environments is frequently the faster path to a good policy.

Build it

NumPy. Part 1 implements GAE, checks the worked example, and measures bias and variance across \(\lambda\) with a deliberately wrong critic. Part 2 isolates PPO's clip: the same noisy batches, reused for \(K\) epochs, with and without clipping.

import numpy as np
def gae(rewards, values, gamma, lam):
    """rewards r_1..r_T; values V(s_0)..V(s_T) with V(s_T) = 0 if the episode ended."""
    T, adv, run = len(rewards), np.zeros(len(rewards)), 0.0
    for t in reversed(range(T)):
        delta = rewards[t] + gamma * values[t + 1] - values[t]   # one-step TD error
        run = delta + gamma * lam * run                          # A_t = delta_t + gamma*lam*A_{t+1}
        adv[t] = run
    return adv

r = np.array([0.0, 0.0, 1.0]); V = np.array([0.5, 0.6, 0.8, 0.0]); gamma = 0.9
for lam in (0.0, 0.5, 0.95, 1.0):
    print(f"lambda = {lam:4}: advantages {gae(r, V, gamma, lam).round(4)}")
G = np.array([gamma ** 2, gamma, 1.0])                            # Monte Carlo returns from each step
print("Monte Carlo G_t - V(s_t):      ", (G - V[:3]).round(4))

# Bias and variance across lambda: an 11-state random walk (+1 at the right end) and a wrong critic.
rng = np.random.default_rng(0)
true_v = np.linspace(0, 1, 11)                                   # v(s) = s/10 under the random policy
critic = true_v + rng.normal(0, 0.15, 11); critic[[0, 10]] = 0   # noisy critic; terminals worth 0
def walk(first):                                                 # take `first` (+1/-1) at s=5, then random
    s, S, R = 5, [], []
    while 0 < s < 10:
        S.append(s); s += first if len(S) == 1 else rng.choice((-1, 1)); R.append(1.0 * (s == 10))
    return np.array(S), np.array(R)
# A policy gradient at s=5 only sees A(right) - A(left); true value 0.6 - 0.4 = 0.2.
for lam in (0.0, 0.5, 0.9, 0.95, 1.0):
    est = {d: np.array([gae(R, np.append(critic[S], 0.0), 1.0, lam)[0]
                        for S, R in (walk(d) for _ in range(4000))]) for d in (1, -1)}
    gap = est[1].mean() - est[-1].mean()
    print(f"lambda {lam:4}: A(right) - A(left) = {gap:.3f} (bias {gap - 0.2:+.3f}),"
          f"  per-sample std {np.sqrt((est[1].var() + est[-1].var()) / 2):.3f}")
lambda =  0.0: advantages [0.04 0.12 0.2 ]
lambda =  0.5: advantages [0.1345 0.21   0.2   ]
lambda = 0.95: advantages [0.2888 0.291  0.2   ]
lambda =  1.0: advantages [0.31 0.3  0.2 ]
Monte Carlo G_t - V(s_t):       [0.31 0.3  0.2 ]
lambda  0.0: A(right) - A(left) = 0.476 (bias +0.276),  per-sample std 0.000
lambda  0.5: A(right) - A(left) = 0.357 (bias +0.157),  per-sample std 0.069
lambda  0.9: A(right) - A(left) = 0.245 (bias +0.045),  per-sample std 0.201
lambda 0.95: A(right) - A(left) = 0.213 (bias +0.013),  per-sample std 0.270
lambda  1.0: A(right) - A(left) = 0.207 (bias +0.007),  per-sample std 0.489
import numpy as np
# Reusing one batch for many epochs. 5-armed bandit, rewards ~ N(mu, 1), softmax policy.
mu = np.array([1.0, 0.8, 0.6, 0.4, 0.2])
def run(epochs, clip, iters=25, batch=16, lr=1.0, seed=0):
    rng = np.random.default_rng(seed); z = np.zeros(5); kls = []
    for _ in range(iters):
        p_old = np.exp(z - z.max()); p_old /= p_old.sum()
        a = rng.choice(5, size=batch, p=p_old); r = rng.normal(mu[a], 1.0)
        adv = (r - r.mean()) / (r.std() + 1e-8)
        for _ in range(epochs):
            p = np.exp(z - z.max()); p /= p.sum(); ratio = p[a] / p_old[a]
            live = ~(((ratio > 1 + clip) & (adv > 0)) | ((ratio < 1 - clip) & (adv < 0)))
            z += lr * ((live * ratio * adv)[:, None] * (np.eye(5)[a] - p)).mean(0)
        p = np.exp(z - z.max()); p /= p.sum(); kls.append(np.sum(p_old * np.log(p_old / p)))
    return p @ mu, p.max(), np.argmax(p) == 0, np.mean(kls)
print("epochs | method   | final J (best 1.0) | P(best arm is argmax) | max prob | KL per update")
for K in (1, 5, 20, 80):
    for name, eps in (("no clip", np.inf), ("clip 0.2", 0.2)):
        R = np.array([run(K, eps, seed=s) for s in range(500)])
        print(f"{K:6d} | {name:8s} |      {R[:,0].mean():.3f}         |        {R[:,2].mean():5.1%}          |  {R[:,1].mean():.2f}    |  {R[:,3].mean():.3f}")
epochs | method   | final J (best 1.0) | P(best arm is argmax) | max prob | KL per update
     1 | no clip  |      0.890         |        92.4%          |  0.72    |  0.005
     1 | clip 0.2 |      0.890         |        92.4%          |  0.72    |  0.005
     5 | no clip  |      0.952         |        86.4%          |  0.92    |  0.062
     5 | clip 0.2 |      0.935         |        89.0%          |  0.84    |  0.015
    20 | no clip  |      0.785         |        43.4%          |  0.99    |  0.472
    20 | clip 0.2 |      0.946         |        90.2%          |  0.87    |  0.020
    80 | no clip  |      0.769         |        39.0%          |  1.00    |  0.463
    80 | clip 0.2 |      0.953         |        88.2%          |  0.88    |  0.028

The PPO loss in PyTorch (standard code, not run here). A complete agent adds vectorised environments, the rollout buffer and GAE above; CleanRL's single-file ppo.py is the reference.

import torch

def ppo_loss(dist, value, actions, logp_old, adv, returns, clip=0.2, c1=0.5, c2=0.01):
    """dist: torch.distributions over actions for B states; value: (B,); others: (B,) tensors."""
    logp = dist.log_prob(actions)                                   # (B,)
    ratio = torch.exp(logp - logp_old)                              # importance ratio r_t
    adv = (adv - adv.mean()) / (adv.std() + 1e-8)                   # per-minibatch normalisation
    pg = -torch.min(ratio * adv, torch.clamp(ratio, 1 - clip, 1 + clip) * adv).mean()
    vf = (value - returns).pow(2).mean()
    ent = dist.entropy().mean()
    with torch.no_grad():                                           # diagnostics
        approx_kl = ((ratio - 1) - (logp - logp_old)).mean()        # low-variance KL(old||new) estimate
        clipfrac = ((ratio - 1).abs() > clip).float().mean()
    return pg + c1 * vf - c2 * ent, approx_kl, clipfrac

Things to try

  • Part 1: replace the noisy critic by the true values true_v. Show that every \(\lambda\) is now unbiased, and only the variance differs.
  • Part 2: add a KL-penalty variant (maximise \(r\hat A - \beta\,\mathrm{KL}\) with the adaptive \(\beta\) rule) and compare it with clipping at matched KL.
  • Part 2: raise the learning rate to 20 with 10 clipped epochs. The first step is unclipped, so a large enough step jumps straight past \(1 \pm \epsilon\). Measure how often the clip fails to contain it: Engstrom et al.'s point, in miniature.
  • Write one-step actor-critic for the short corridor and compare its learning curve with REINFORCE-with-baseline.
  • With Gymnasium and the loss above, train PPO on CartPole-v1, then remove advantage normalisation, then the value-function loss, and log the explained variance each time.

Check yourself

Why is the TD error an estimate of the advantage, and when is it unbiased?

\(\mathbb E[r_{t+1} + \gamma V^\pi(s_{t+1})\mid s_t,a_t] = Q^\pi(s_t,a_t)\), so \(\mathbb E[\delta_t\mid s_t,a_t] = Q^\pi(s_t,a_t) - V^\pi(s_t) = A^\pi(s_t,a_t)\). It is unbiased only if the critic equals \(V^\pi\) at \(s_{t+1}\); the error at \(s_t\) is a baseline and does not bias the gradient.

What do λ = 0 and λ = 1 give in GAE, and which way do bias and variance move between them?

\(\lambda = 0\): \(\hat A_t = \delta_t\), one-step TD; lowest variance, most dependent on the critic (biased if it is wrong). \(\lambda = 1\): \(\hat A_t = G_t - V(s_t)\), Monte Carlo; unbiased for the gradient, highest variance. Increasing \(\lambda\) trades bias for variance.

In the clipped objective, for which combinations of advantage sign and ratio is the gradient zero, and why is the other side never clipped?

Zero when \(\hat A > 0\) and \(r > 1+\epsilon\), or \(\hat A < 0\) and \(r < 1-\epsilon\): the update has already moved far enough in the direction the advantage wanted. On the other side (a good action made less likely, or a bad one more likely) the \(\min\) picks the unclipped term, whose gradient corrects the mistake. Clipping only removes optimism.

Why can PPO take several epochs on a batch when vanilla policy gradient takes one step?

After one step the batch is off-policy. The ratio \(r_t\) in the surrogate corrects for that to first order, and clipping stops the optimiser from exploiting the surrogate where it is no longer accurate. Without the clip, multiple epochs over-fit the batch and collapse the policy, as the bandit experiment shows (best arm found in 43% of runs instead of 90%).

State the performance difference lemma and say which term TRPO's surrogate approximates.

\(J(\pi') - J(\pi) = \frac{1}{1-\gamma}\mathbb E_{s\sim d^{\pi'},a\sim\pi'}[A^\pi(s,a)]\). The surrogate keeps the actions exact (by importance weighting) but replaces the new policy's state distribution \(d^{\pi'}\) by the old one, \(d^\pi\), which is accurate only when the policies are close.

What problem does each of TD3's three changes address?

Clipped double Q: overestimation from maximising over a noisy critic. Delayed policy updates: the actor chasing a critic that has not yet settled. Target policy smoothing: the actor exploiting narrow, spurious peaks in the critic. All three are forms of not trusting the critic too much.

Hard: why did RLHF with PPO need four large models in memory, and which one did GRPO remove?

The policy (actor) being trained; the value network (critic) for advantages; the reward model to score completions; and the frozen reference model for the KL penalty. GRPO removes the critic by using the mean reward of several completions of the same prompt as the baseline.

Hard: SAC's optimal policy is a Boltzmann distribution over soft Q-values. What happens as α → 0 and α → ∞?

As \(\alpha\to0\) the entropy term vanishes and the policy becomes greedy in \(Q\): ordinary RL. As \(\alpha\to\infty\) reward stops mattering and the policy becomes uniform (maximum entropy). Automatic temperature tuning chooses \(\alpha\) so the entropy sits near a target, instead of fixing the trade-off by hand.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

Where this leads