Chapter 15 · Section 15.4 · 55 min

Baselines, advantages, and actor-critic

The widget at the end of §15.3 showed something strange. Adding the same constant to every reward left the expected policy gradient exactly where it was, yet it made each individual estimate much noisier, and with enough of an offset the learning curves dissolved into noise. The cure in the widget was to subtract the average reward before multiplying by the score. That raises an obvious worry. If we change the weights on the scores, are we still estimating the gradient of the thing we want to maximize?

We are, and the reason is a one-line lemma that does a surprising amount of work. This section proves it, uses it to justify both baselines and reward-to-go, works out which baseline removes the most variance, and arrives at the advantage function, the quantity that every modern policy gradient method, PPO and GRPO included, multiplies its scores by. Then we learn the baseline with a second model, the critic, which gives actor-critic methods.

The expected score is zero

Fix a state ss and let πθ(⋅∣s)\pi_\theta(\cdot\mid s) be any differentiable policy. Then

Ea∼πθ(⋅∣s)[∇θlog⁡πθ(a∣s)]=∑aπθ(a∣s) ∇θπθ(a∣s)πθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0.\mathbb{E}_{a\sim\pi_\theta(\cdot\mid s)}\big[\nabla_\theta\log\pi_\theta(a\mid s)\big] = \sum_a \pi_\theta(a\mid s)\,\frac{\nabla_\theta\pi_\theta(a\mid s)}{\pi_\theta(a\mid s)} = \nabla_\theta\sum_a\pi_\theta(a\mid s) = \nabla_\theta 1 = 0 .

In plain words, probabilities always sum to one, so you cannot raise all of them at once, and on average the directions that raise each sampled action's probability cancel out. For a softmax policy you can see it directly, Ea[ea−π]=π−π=0\mathbb{E}_a[\mathbf{e}_a - \boldsymbol\pi] = \boldsymbol\pi - \boldsymbol\pi = \mathbf{0}. Spinning Up calls this the expected grad-log-prob lemma. It is the score-function analogue of the fact that a log-likelihood's gradient (the score in statistics) has mean zero under the model.

Baselines add no bias

Take the REINFORCE estimator with reward-to-go from §15.3, ∑t∇θlog⁡πθ(at∣st) Gt\sum_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,G_t, where GtG_t is the (discounted) return from step tt. (We drop the γt\gamma^t factor, as practice does. Everything below holds with it too.) Now subtract a baseline b(st)b(s_t) from each return,

g^=∑t=0T−1∇θlog⁡πθ(at∣st) (Gt−b(st)).\hat{\mathbf{g}} = \sum_{t=0}^{T-1}\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,\big(G_t - b(s_t)\big).

The change in the expected estimate is −∑tE[∇θlog⁡πθ(at∣st) b(st)]-\sum_t\mathbb{E}[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,b(s_t)]. Compute each term by first conditioning on the state sts_t (the law of iterated expectations), so that b(st)b(s_t) is a constant inside the inner expectation,

E[∇θlog⁡πθ(at∣st) b(st)]=Est[ b(st)  Eat∼πθ(⋅∣st)[∇θlog⁡πθ(at∣st)]]=Est[b(st)⋅0]=0.\mathbb{E}\big[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,b(s_t)\big] = \mathbb{E}_{s_t}\Big[\,b(s_t)\;\mathbb{E}_{a_t\sim\pi_\theta(\cdot\mid s_t)}\big[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\big]\Big] = \mathbb{E}_{s_t}\big[b(s_t)\cdot 0\big] = 0 .

So subtracting any function of the state leaves the expected gradient exactly unchanged. The same argument works if the baseline depends on anything known before ata_t is drawn, the whole history ht=(s0,a0,…,st)h_t = (s_0, a_0, \dots, s_t), the time step tt, a random number, or the parameters themselves. Condition on that information instead of on sts_t alone and the inner expectation is still zero.

The one thing a baseline must not depend on is the action ata_t (or anything after it). Then the inner expectation becomes ∑aπθ(a∣s) b(s,a)∇log⁡πθ(a∣s)=∑ab(s,a)∇πθ(a∣s)\sum_a\pi_\theta(a\mid s)\,b(s,a)\nabla\log\pi_\theta(a\mid s) = \sum_a b(s,a)\nabla\pi_\theta(a\mid s), which is not zero in general. The extreme case makes the point. If you chose b(s,a)=Gb(s, a) = G, the "perfect" baseline that equals the return, every estimate would be exactly zero and nothing would ever be learned.

Reward-to-go comes from the same lemma

In §15.3 we replaced the trajectory form, R(τ)∑t∇log⁡πθ(at∣st)R(\tau)\sum_t\nabla\log\pi_\theta(a_t\mid s_t), by the reward-to-go form, using the policy gradient theorem. The lemma gives a direct proof that needs no theorem. Expand R(τ)=∑t′γt′rt′R(\tau) = \sum_{t'}\gamma^{t'}r_{t'} and look at one cross term, the reward at step t′t' times the score at step tt, with t′<tt' < t. The reward rt′r_{t'} was earned before ata_t was chosen, so it is a function of the history hth_t, and

E[rt′ ∇log⁡πθ(at∣st)]=Eht[rt′  Eat[∇log⁡πθ(at∣st)]]=0for t′<t.\mathbb{E}\big[r_{t'}\,\nabla\log\pi_\theta(a_t\mid s_t)\big] = \mathbb{E}_{h_t}\Big[r_{t'}\;\mathbb{E}_{a_t}\big[\nabla\log\pi_\theta(a_t\mid s_t)\big]\Big] = 0 \quad\text{for } t' < t .

In plain words, an action cannot be credited or blamed for rewards that arrived before it, because on average those rewards are uncorrelated with which action was taken. Deleting all of these zero-mean terms leaves ∑t∇log⁡πθ(at∣st)∑t′≥tγt′rt′=∑tγt Gt ∇log⁡πθ(at∣st)\sum_t\nabla\log\pi_\theta(a_t\mid s_t)\sum_{t'\ge t}\gamma^{t'}r_{t'} = \sum_t\gamma^t\,G_t\,\nabla\log\pi_\theta(a_t\mid s_t), exactly the theorem's sample form. The deleted terms had zero mean but nonzero variance, so removing them can only help (in expectation, removing a zero-mean term that is uncorrelated with the rest always lowers the variance, and in practice it helps even when the terms are correlated). Reward-to-go and baselines are the same idea. Each subtracts something whose expected product with the score is zero.

Computing reward-to-go for a batch of variable-length episodes stored as a padded array is one of the most common pieces of code in RL, and in RLHF it runs over batches of token sequences of different lengths.

Interview

Reward-to-go for a padded batch, without a time loop

rewards has shape (B, T) and holds BB episodes padded to length TT, and mask has shape (B, T) with 1 at real steps and 0 at padding (each row is a run of ones followed by zeros). Padding positions may contain garbage rewards. Implement reward_to_go(rewards, mask, gamma) returning G of shape (B, T) with Gi,t=∑k≥tγk−tri,kmi,kG_{i,t} = \sum_{k\ge t}\gamma^{k-t}r_{i,k}m_{i,k} at real steps and 0 at padding. Do it without a Python loop over tt or over episodes.

Hidden tests, hints, and AI help, from $1.99 a month.

How much variance a baseline removes

Unbiasedness says a baseline is free. Variance says which baseline to pick. Look at a single decision, so that the estimator is g=(G−b) s\mathbf{g} = (G - b)\,\mathbf{s} with s=∇θlog⁡πθ(a∣s)\mathbf{s} = \nabla_\theta\log\pi_\theta(a\mid s) the score of the sampled action and GG its (random) return, and let bb be a constant. The mean of g\mathbf{g} does not depend on bb, so minimizing the total variance E∥g∥2−∥Eg∥2\mathbb{E}\lVert\mathbf{g}\rVert^2 - \lVert\mathbb{E}\mathbf{g}\rVert^2 is the same as minimizing the second moment,

E[(G−b)2∥s∥2]=E[G2∥s∥2]−2b E[G∥s∥2]+b2 E[∥s∥2],\mathbb{E}\big[(G - b)^2\lVert\mathbf{s}\rVert^2\big] = \mathbb{E}[G^2\lVert\mathbf{s}\rVert^2] - 2b\,\mathbb{E}[G\lVert\mathbf{s}\rVert^2] + b^2\,\mathbb{E}[\lVert\mathbf{s}\rVert^2],

a parabola in bb. Setting its derivative to zero gives the optimal constant baseline,

b⋆=E[G ∥s∥2]E[∥s∥2].b^\star = \frac{\mathbb{E}\big[G\,\lVert\mathbf{s}\rVert^2\big]}{\mathbb{E}\big[\lVert\mathbf{s}\rVert^2\big]} .

In plain words, the best baseline is an average of the returns, weighted by how large each sample's score is. Samples whose scores are large contribute the most variance, so the baseline should match their returns best.

If the score's size is unrelated to the return, b⋆b^\star is just E[G]\mathbb{E}[G], the expected return, which in a state ss is Vπ(s)V^\pi(s). The two usually differ a little (the weighting favors rare actions, which have larger scores, since ∥ea−π∥\lVert\mathbf{e}_a - \boldsymbol\pi\rVert grows as πa\pi_a shrinks), but almost nobody bothers with b⋆b^\star in practice. Vπ(s)V^\pi(s) captures nearly all of the gain in absolute terms, and it has a second virtue that b⋆b^\star lacks, which we will see in a moment. (Greensmith, Bartlett, and Baxter (2004) give the full analysis of optimal baselines, including state-dependent ones.)

Python · cell 1

For this bandit, whose rewards share a large offset, the expected reward as a baseline cuts the variance of a single estimate from 44 to 0.07, a factor of more than 600, and that ratio is the number of samples you save. The optimal constant shrinks what is left by another factor of about 2.4, because it leans toward the returns of the two rarer actions, whose scores are larger. In absolute terms almost all of the gain came from the first step. Drag the rewards and the policy around below and the parabola moves, but its minimum always sits close to the expected reward.

Which constant baseline makes a policy gradient estimate least noisy?
A 3-armed bandit with rewards 1, 0.5, and 0 plus an offset and Gaussian noise. The curve is the exact total variance of one estimate (r − b)(e_a − π) as a function of the baseline b, on a log scale. Its mean never depends on b.
Loading interactive figure…

The same effect shows up in a real episode. Here is the short corridor from §15.3, with the single-episode gradient estimate of ∂J/∂θ\partial J/\partial\theta (the logit of "right") sampled 3,000 times at p=0.8p = 0.8, with and without the average return as a baseline.

Python · cell 2

Both estimators are centered on the exact gradient, −7-7. (The policy goes right too often, so the gradient says to lower θ\theta.) The baseline cuts the standard deviation from about 34 to about 21, which means (34/21)2≈2.6(34/21)^2 \approx 2.6 times fewer episodes for the same precision. The gain is smaller than for the bandit because a single constant cannot follow the return as it changes along the episode. In this corridor every state looks the same to the agent, so a state-dependent baseline is the same single constant. A baseline that depends on the time step, which the lemma also allows, could follow the shrinking returns and do better.

Core

Check by sampling that a baseline adds no bias

Implement two functions for a bandit with a softmax policy.

pg_estimates(z, actions, rewards, b) takes logits z of shape (K,), sampled actions of shape (N,), their rewards of shape (N,), and a baseline b that is either a scalar or an array of shape (N,) (one baseline per sample). Return the per-sample estimates (ri−bi)(eai−π)(r_i - b_i)(\mathbf{e}_{a_i} - \boldsymbol\pi), shape (N, K).

baseline_check(z, r_mean, b, n, seed) draws, with rng = np.random.default_rng(seed), first a = rng.choice(K, size=n, p=pi) and then r = r_mean[a] + rng.normal(size=n). It returns a dict with keys "mean_b", "mean_0" (the average estimate with baseline b and with no baseline, each shape (K,)) and "var_b", "var_0" (the total variance of a single estimate, the sum over the KK coordinates of the per-coordinate variance, est.var(axis=0).sum()).

Hidden tests, hints, and AI help, from $1.99 a month.
Research

The variance-optimal constant baseline

Given per-sample scores scores of shape (N, d) (each row a ∇θlog⁡πθ(ai∣s)\nabla_\theta\log\pi_\theta(a_i\mid s) for one decision) and returns G of shape (N,), implement optimal_baseline(scores, G) returning the scalar bb that minimizes the empirical second moment 1N∑i(Gi−b)2∥si∥2\frac1N\sum_i (G_i - b)^2\lVert\mathbf{s}_i\rVert^2. Then, in a comment, say when it equals the plain mean of G.

Hidden tests, hints, and AI help, from $1.99 a month.

The advantage function

Choose the baseline b(st)=Vπ(st)b(s_t) = V^\pi(s_t). Since E[Gt∣st,at]=Qπ(st,at)\mathbb{E}[G_t\mid s_t, a_t] = Q^\pi(s_t,a_t), the expected weight on each score becomes

E[Gt−Vπ(st) ∣ st,at]=Qπ(st,at)−Vπ(st)=Aπ(st,at),\mathbb{E}\big[G_t - V^\pi(s_t)\,\big|\,s_t, a_t\big] = Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t),

the advantage of §15.1, and the policy gradient takes the form used by every algorithm from here on,

∇θJ(θ)=Eτ[∑t=0T−1γt Aπ(st,at) ∇θlog⁡πθ(at∣st)].\nabla_\theta J(\theta) = \mathbb{E}_\tau\Big[\sum_{t=0}^{T-1}\gamma^t\, A^\pi(s_t, a_t)\,\nabla_\theta\log\pi_\theta(a_t\mid s_t)\Big].

In plain words, raise the probability of actions that did better than the policy usually does from that state, and lower the probability of actions that did worse. The size of the push is how much better or worse.

This is what makes VπV^\pi the natural baseline, beyond its near-optimal variance. The advantage is a relative judgment, and relative judgments are what a policy update needs. Three properties make it pleasant to work with.

  • It averages to zero over the policy's own actions, ∑aπ(a∣s)Aπ(s,a)=Vπ(s)−Vπ(s)=0\sum_a\pi(a\mid s)A^\pi(s,a) = V^\pi(s) - V^\pi(s) = 0, so in every state some actions are pushed up and some down, and the policy is not dragged in one direction by the overall level of reward.
  • Its sign answers the question an update needs answered, better or worse than the current behavior. A state where everything is bad (every return is −40-40) still has actions with positive advantage, the least bad ones.
  • It is the quantity that policy improvement is about. The greedy policy of §15.2 picks arg⁡max⁡aQπ(s,a)=arg⁡max⁡aAπ(s,a)\arg\max_aQ^\pi(s,a) = \arg\max_aA^\pi(s,a), and §15.6 will show that the improvement of one policy over another is exactly an average of advantages.

The rest of this chapter is mostly about estimating Aπ(st,at)A^\pi(s_t, a_t) well. Sampling Gt−V(st)G_t - V(s_t) is one estimate. The next two sections give better ones.

Learning the baseline, the critic

We do not know VπV^\pi, so we learn it. A value network (or a table) Vψ(s)V_\psi(s) with parameters ψ\psi is trained by regression on the returns the policy actually produces,

LV(ψ)=1N∑i,t(Vψ(st(i))−Gt(i))2.\mathcal{L}^V(\psi) = \frac{1}{N}\sum_{i,t}\big(V_\psi(s^{(i)}_t) - G^{(i)}_t\big)^2 .

The minimizer of the expected squared error is the conditional mean, E[Gt∣st]=Vπ(st)\mathbb{E}[G_t\mid s_t] = V^\pi(s_t), so with enough capacity and data the regression recovers the right baseline. Two facts keep this safe. First, if the targets are Monte Carlo returns, an inaccurate VψV_\psi only costs variance, never bias, because the unbiasedness proof above worked for any function of the state. Second, the policy changes after every update, so VψV_\psi is always chasing a moving target, and in practice it is updated a few gradient steps per batch, alongside the policy.

The value model is called the critic and the policy the actor. In RLHF the critic is a whole second language model, usually initialized from the reward model, that outputs a value for every prefix of a response (§16.4). It is one of the four models that make RLHF with PPO expensive, and dropping it in favor of a baseline computed from a group of sampled responses is GRPO's main saving (§18.4).

Actor-critic methods

Once we have a critic, we can use it for more than a baseline. Replace the sampled return GtG_t, which needs the whole rest of the episode, with a one-step bootstrapped estimate, as TD(0) did in §15.2,

A^t=δt=rt+γVψ(st+1)−Vψ(st),\hat A_t = \delta_t = r_t + \gamma V_\psi(s_{t+1}) - V_\psi(s_t),

the TD error, with Vψ(st+1)=0V_\psi(s_{t+1}) = 0 if st+1s_{t+1} is terminal. Is that a reasonable estimate of the advantage? If the critic is exact, Vψ=VπV_\psi = V^\pi, then yes, exactly, because

E[δt ∣ st,at]=r(st,at)+γ∑s′P(s′∣st,at)Vπ(s′)−Vπ(st)=Qπ(st,at)−Vπ(st)=Aπ(st,at),\mathbb{E}\big[\delta_t\,\big|\,s_t, a_t\big] = r(s_t, a_t) + \gamma\sum_{s'}P(s'\mid s_t, a_t)V^\pi(s') - V^\pi(s_t) = Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t),

using the one-step relation Qπ(s,a)=r(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)Q^\pi(s,a) = r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)V^\pi(s') from §15.1. In plain words, the TD error is a one-sample advantage. It says how much better this step turned out than the critic expected, measured with the critic's own estimate of where it landed.

If the critic is wrong, δt\delta_t is biased, and unlike the baseline case the bias now reaches the gradient, because the error in γVψ(st+1)\gamma V_\psi(s_{t+1}) depends on where the action led. In exchange, its variance is far lower than Gt−Vψ(st)G_t - V_\psi(s_t), since it involves one reward and one transition instead of a whole future. This is the Monte Carlo versus TD trade-off of §15.2 again, now for advantages, and §15.5 turns it into a dial.

An actor-critic algorithm runs both updates side by side. After each transition (st,at,rt,st+1)(s_t, a_t, r_t, s_{t+1}),

ψ←ψ+αc δt ∇ψVψ(st),θ←θ+αa δt ∇θlog⁡πθ(at∣st),\psi \leftarrow \psi + \alpha_c\,\delta_t\,\nabla_\psi V_\psi(s_t), \qquad \theta \leftarrow \theta + \alpha_a\,\delta_t\,\nabla_\theta\log\pi_\theta(a_t\mid s_t),

where αc\alpha_c and αa\alpha_a are the critic's and actor's step sizes. (The critic update is a semi-gradient step on 12δt2\frac12\delta_t^2 that treats the target rt+γVψ(st+1)r_t + \gamma V_\psi(s_{t+1}) as a constant, exactly TD(0).) It is generalized policy iteration from §15.2 run continuously, a critic evaluating the current policy and an actor improving against the critic. A2C and A3C (Mnih et al. 2016) are this algorithm with many environments running in parallel, nn-step returns instead of one-step ones, and an entropy bonus, and they were the standard deep RL baselines before PPO.

Core

One step of tabular actor-critic

Implement actor_critic_step(theta, v, s, a, r, s_next, terminated, lr_actor, lr_critic, gamma) for a tabular softmax actor with logits theta of shape (S, A) and a tabular critic v of shape (S,). Compute the TD error δ\delta with the old critic (no bootstrap if terminated), update the critic, v(s)+=αcδv(s) \mathrel{+}= \alpha_c\delta, and update the actor's logits for state s, θs+=αaδ(ea−π(⋅∣s))\theta_s \mathrel{+}= \alpha_a\delta(\mathbf{e}_a - \boldsymbol\pi(\cdot\mid s)), using the policy before the update. Return (theta_new, v_new, delta) without modifying the inputs.

Hidden tests, hints, and AI help, from $1.99 a month.

Here is actor-critic on the gridworld, in the synchronous style of A2C. Sixteen copies of the world run side by side, and after every single step of all sixteen, the critic and the actor each take one averaged update. Episodes are cut off after 50 steps, and a cut-off is not a terminal state, so the critic still bootstraps from where the agent was. We track the exact value of the start cell under the current policy, which value iteration told us is at most V⋆=0.351V^\star = 0.351.

Python · cell 3

Actor-critic reaches 0.333 after 8,000 transitions and 0.340 after 16,000, against the optimal 0.351, learning from every single step without waiting for any episode to finish. On this small world REINFORCE with a batch of complete episodes does about as well for the same number of transitions, because its returns are short and well scaled. Actor-critic's real advantages appear when episodes are long or never end, where waiting for the full return is slow or impossible, and when the reward scale makes raw returns noisy. Its real weakness is the critic's bias early in training, which you can see in the first numbers, when the critic still knows nothing.

Normalizing advantages

Almost every implementation standardizes the advantages within each batch before using them, replacing A^i\hat A_i by (A^i−Aˉ)/(std⁡(A^)+ϵ)(\hat A_i - \bar A)/(\operatorname{std}(\hat A) + \epsilon). Subtracting the batch mean is one more baseline (with the small batch-dependence bias discussed above). Dividing by the standard deviation rescales the whole gradient by one positive number per batch, which does not change its direction, only its length, and acts as an automatic learning-rate adjustment that makes the step size insensitive to the reward scale. It is one of the "implementation details" that turns out to matter in practice (§15.6).

In PyTorch

The A2C loss in production code combines the actor's surrogate (with advantages detached, so the policy gradient does not flow into the critic), the critic's regression loss, and usually an entropy bonus. Here it is for one batch of gridworld transitions, with separate actor and critic networks.

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 CS 285: Lecture 6, Part 1 · RAILThe start of Sergey Levine's actor-critic lecture, on critics, baselines, and bootstrapped advantage estimates.
🎬 L3 Policy Gradients and Advantage Estimation (Foundations of Deep RL Series) · Pieter AbbeelBaselines, value function estimation, and advantage estimation in one lecture.