Type at least 2 letters. Enter opens the first result, Esc closes.

    Reinforcement Learning · Lesson 8 · Function approximation and policy optimization

    Actor-critic methods: advantages, GAE, A2C and soft actor-critic

    Advanced 85 min 4 interactive figures 3 videos Colab notebook

    Before this lesson: the policy gradient theorem, baselines and the advantage (lesson 07); TD errors, nn-step returns and the λ-return (lesson 04); DQN, target networks and replay buffers (lesson 06); the maximization bias (lesson 05); entropy (information theory 01); the reparameterization trick (calculus 12). Time: about 85 minutes, plus the notebook.


    Why this matters #

    Almost every deep RL algorithm used today is an actor-critic method.

    • PPO (lesson 09) is an actor-critic method with GAE (usually λ=0.95\lambda = 0.95). It trains robots in simulation, game agents such as OpenAI Five, and language models in RLHF, where the critic is a "value head" on the language model.
    • SAC and TD3 are standard for continuous control from raw experience: robot locomotion and manipulation in MuJoCo and on real robots, where data is expensive and reuse matters.
    • AlphaGo and AlphaZero (lesson 10) have a policy head and a value head, the same two parts.
    • The maximum-entropy view of SAC returns in RL for language models: the KL-regularized objective of RLHF has the same soft-greedy optimum, π∝πrefexp⁡(r/β)\pi \propto \pi_{\text{ref}} \exp(r/\beta) (lesson 09).

    1. Predict first #

    2. The picture #

    The actor and the critic #

    From lesson 07, the policy gradient is E[∑tγt∇θlog⁡πθ(at∣st) Aπ(st,at)]\mathbb E[\sum_t \gamma^t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, A^\pi(s_t, a_t)], and REINFORCE estimates the advantage by Gt−b(st)G_t - b(s_t). An actor-critic method learns a value function Vϕ(s)V_\phi(s) with parameters ϕ\phi (the critic) and uses it in two ways: as the baseline, and to replace most of the sampled return by a prediction.

    The simplest estimate uses one real reward and then the critic. This is the TD error of lesson 04:

    δt=rt+γVϕ(st+1)−Vϕ(st),Vϕ(st+1)=0 if st+1 is terminal.\delta_t = r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t), \qquad V_\phi(s_{t+1}) = 0 \text{ if } s_{t+1} \text{ is terminal}.

    If the critic were exact (Vϕ=VπV_\phi = V^\pi), then E[δt∣st,at]=r+γE[Vπ(st+1)]−Vπ(st)=Qπ(st,at)−Vπ(st)=Aπ(st,at)\mathbb E[\delta_t \mid s_t, a_t] = r + \gamma \mathbb E[V^\pi(s_{t+1})] - V^\pi(s_t) = Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t). So δt\delta_t is an advantage estimate that uses only one random reward and one random next state.

    The two parts help each other. The critic gives the actor a low-variance signal after every step, without waiting for the episode to end. The actor changes the policy, and the critic follows it. But a wrong critic gives the actor a wrong signal: this is the bias of actor-critic methods.

    Interactive figure: loading…

    Press "1 step (slow)" a few times, then "100 steps". The robot vacuum of lesson 01: the boxes show the actor's policy (orange bars) and the critic's values (blue bars) in the states H and L. The slow step shows the five phases of one update. The charts show V(H)V(H) and V(L)V(L) against the optimal values V∗V^* (dashed), and the probabilities of the optimal actions. Watch π(charge∣L)\pi(\text{charge} \mid L) in the first 100 steps: the critic starts at V=0V = 0, so "clean" (reward 1 now) looks better than "charge" (reward 0 now) until the critic learns that V(H)V(H) is large.

    Short or long: k-step advantage estimators #

    Between δt\delta_t (one real reward) and Gt−V(st)G_t - V(s_t) (all real rewards) there is a family. The kk-step advantage estimator uses kk real rewards and then the critic:

    A^t(k)=rt+γrt+1+⋯+γk−1rt+k−1+γkV(st+k)−V(st).\hat A_t^{(k)} = r_t + \gamma r_{t+1} + \dots + \gamma^{k-1} r_{t+k-1} + \gamma^k V(s_{t+k}) - V(s_t).
    • k=1k = 1: A^t(1)=δt\hat A_t^{(1)} = \delta_t. Low variance (one random reward), but biased when V≠VπV \ne V^\pi.
    • k=∞k = \infty (to the end of the episode): A^t(∞)=Gt−V(st)\hat A_t^{(\infty)} = G_t - V(s_t). This is REINFORCE with the baseline VV: no bias in the policy gradient for any VV, but high variance.

    Where does the bias come from? Write the critic as V=Vπ+eV = V^\pi + e, with an error e(s)e(s). Then

    E[A^t(k)∣st,at]=Aπ(st,at)+γk E[e(st+k)∣st,at]−e(st).\mathbb E\big[\hat A_t^{(k)} \mid s_t, a_t\big] = A^\pi(s_t, a_t) + \gamma^k\, \mathbb E\big[e(s_{t+k}) \mid s_t, a_t\big] - e(s_t).

    The last term, −e(st)-e(s_t), depends only on the state, so it acts like a baseline and does not bias the policy gradient (lesson 07). The middle term is the real bias: the critic's error at the state where we bootstrap, discounted by γk\gamma^k. More real rewards push the bootstrap point further away and shrink this term, but each real reward adds noise.

    Interactive figure: loading…

    Move the critic error cc and the reward noise σ\sigma, then find the best λ\lambda. A chain of 20 steps, each with a reward r∼N(1,σ2)r \sim N(1, \sigma^2), γ=0.95\gamma = 0.95. The critic is wrong by cc in every state. The top chart shows the error of 40 sampled estimates (the orange dots are at the current setting) and their mean, the bias. The bottom chart shows bias², variance and their sum, the mean squared error, for every λ\lambda. Switch to "k-step" to see the same trade-off for kk. A perfect critic favours small λ\lambda; a bad critic and quiet rewards favour λ\lambda near 1.

    The figure measures the error of A^t+V(st)\hat A_t + V(s_t) as an estimate of Qπ(st,at)Q^\pi(s_t, a_t). This removes the harmless baseline term −e(st)-e(s_t), and it is the same quantity as the error of the value target that trains the critic.

    Quick check

    A critic gives V(s0)=1.0V(s_0) = 1.0 and V(s1)=0.5V(s_1) = 0.5. At step 0 the reward is r0=1r_0 = 1, γ=0.9\gamma = 0.9, and the episode does not end. What is δ0\delta_0?

    3. Definitions and main results #

    Generalized advantage estimation #

    The λ-return of lesson 04 averages nn-step returns with weights (1−λ)λn−1(1-\lambda)\lambda^{n-1}. GAE (Schulman et al., 2016) does the same with the kk-step advantage estimators.

    Theorem (GAE). For 0≤λ≤10 \le \lambda \le 1 and a critic VV,

    A^tGAE(γ,λ):=(1−λ)(A^t(1)+λA^t(2)+λ2A^t(3)+…)=∑l≥0(γλ)l δt+l.\hat A_t^{\text{GAE}(\gamma, \lambda)} := (1 - \lambda)\big(\hat A_t^{(1)} + \lambda \hat A_t^{(2)} + \lambda^2 \hat A_t^{(3)} + \dots\big) = \sum_{l \ge 0} (\gamma\lambda)^l\, \delta_{t+l} .

    In particular, λ=0\lambda = 0 gives δt\delta_t, and λ=1\lambda = 1 gives Gt−V(st)G_t - V(s_t).

    Proof.

    1. Telescoping. For every k≥1k \ge 1,

    ∑l=0k−1γlδt+l=∑l=0k−1γlrt+l+∑l=0k−1(γl+1V(st+l+1)−γlV(st+l))=A^t(k).\sum_{l=0}^{k-1} \gamma^l \delta_{t+l} = \sum_{l=0}^{k-1} \gamma^l r_{t+l} + \sum_{l=0}^{k-1} \big(\gamma^{l+1} V(s_{t+l+1}) - \gamma^l V(s_{t+l})\big) = \hat A_t^{(k)} .

    In the second sum, each γl+1V(st+l+1)\gamma^{l+1} V(s_{t+l+1}) cancels the next term's −γl+1V(st+l+1)-\gamma^{l+1} V(s_{t+l+1}); only γkV(st+k)−V(st)\gamma^k V(s_{t+k}) - V(s_t) is left.

    2. Insert step 1 into the definition: A^tGAE=(1−λ)∑k≥1λk−1∑l=0k−1γlδt+l\hat A_t^{\text{GAE}} = (1 - \lambda) \sum_{k \ge 1} \lambda^{k-1} \sum_{l=0}^{k-1} \gamma^l \delta_{t+l}.

    3. Swap the two sums. The term γlδt+l\gamma^l \delta_{t+l} appears for every k≥l+1k \ge l + 1. Its total weight is

    (1−λ)∑k≥l+1λk−1=(1−λ) λl (1+λ+λ2+… )=(1−λ) λl1−λ=λl(1 - \lambda) \sum_{k \ge l+1} \lambda^{k-1} = (1 - \lambda)\, \lambda^l \,(1 + \lambda + \lambda^2 + \dots) = (1-\lambda)\, \frac{\lambda^l}{1 - \lambda} = \lambda^l

    for λ<1\lambda < 1. So A^tGAE=∑l≥0λlγlδt+l=∑l≥0(γλ)lδt+l\hat A_t^{\text{GAE}} = \sum_{l \ge 0} \lambda^l \gamma^l \delta_{t+l} = \sum_{l \ge 0} (\gamma\lambda)^l \delta_{t+l}.

    4. λ=0\lambda = 0: only l=0l = 0 is left (with 00=10^0 = 1), so A^t=δt\hat A_t = \delta_t.

    5. λ=1\lambda = 1 (defined by the right-hand side, the limit of the left): ∑lγlδt+l\sum_l \gamma^l \delta_{t+l} is the telescoping sum of step 1 with k→∞k \to \infty. The boundary term γkV(st+k)\gamma^k V(s_{t+k}) is 0 after the episode ends (and tends to 0 when γ<1\gamma < 1 and VV is bounded), so the sum is Gt−V(st)G_t - V(s_t). ■\blacksquare

    If the episode ends NN steps after tt, every A^t(k)\hat A_t^{(k)} with k≥Nk \ge N is the same full estimate Gt−V(st)G_t - V(s_t), so all the remaining weight λN−1\lambda^{N-1} lands on it, exactly as for the λ-return. And A^tGAE+V(st)\hat A_t^{\text{GAE}} + V(s_t) is the λ-return with the critic VV as the bootstrap: the usual value target for the critic.

    With an exact critic every λ\lambda is unbiased. If V=VπV = V^\pi, then E[δt∣st,at]=Aπ(st,at)\mathbb E[\delta_t \mid s_t, a_t] = A^\pi(s_t, a_t), and E[δt+l∣st+l]=0\mathbb E[\delta_{t+l} \mid s_{t+l}] = 0 for l≥1l \ge 1, because later actions also follow π\pi. So E[A^t∣st,at]=Aπ(st,at)\mathbb E[\hat A_t \mid s_t, a_t] = A^\pi(s_t, a_t) for every λ\lambda. With an imperfect critic, a smaller λ\lambda means more bias and less variance.

    Quick check

    In GAE, what are the estimates for λ=0\lambda = 0 and for λ=1\lambda = 1?

    Computing GAE: the backward recursion #

    The sum ∑l(γλ)lδt+l\sum_l (\gamma\lambda)^l \delta_{t+l} satisfies A^t=δt+γλ A^t+1\hat A_t = \delta_t + \gamma\lambda\, \hat A_{t+1}. So one backward pass over a rollout computes all advantages. A rollout of TT steps (it may contain several episodes) has:

    • rewards r0,…,rT−1r_0, \dots, r_{T-1} and critic values V(s0),…,V(sT−1)V(s_0), \dots, V(s_{T-1});
    • done flags dt∈{0,1}d_t \in \{0, 1\}: dt=1d_t = 1 means the episode ended with step tt (st+1s_{t+1} is terminal);
    • the bootstrap value V(sT)V(s_T), the critic's value of the state after the last step.
    δt=rt+γ(1−dt) V(st+1)−V(st),A^t=δt+γλ (1−dt) A^t+1,A^T=0,\delta_t = r_t + \gamma (1 - d_t)\, V(s_{t+1}) - V(s_t), \qquad \hat A_t = \delta_t + \gamma\lambda\, (1 - d_t)\, \hat A_{t+1}, \qquad \hat A_T = 0 ,

    for t=T−1,…,0t = T-1, \dots, 0. The value targets are A^t+V(st)\hat A_t + V(s_t). The factor (1−dt)(1 - d_t) does two jobs: no bootstrapping from a terminal state, and no advantage flows back across the end of an episode into the previous one.

    Termination or truncation. An episode can stop for two different reasons.

    • Termination: the task really ended (the robot fell, the game was won). The value after it is 0. Set dt=1d_t = 1.
    • Truncation: we stopped collecting data (a time limit, or the end of the rollout buffer). The next state is a normal state with a nonzero value. Do not cut the return to 0: bootstrap with V(st+1)V(s_{t+1}) of the real next state.

    The end of every rollout buffer is a truncation; that is what the bootstrap value V(sT)V(s_T) is for. Gymnasium reports the two cases separately (terminated and truncated); only terminated should become dt=1d_t = 1.

    Interactive figure: loading…

    Press "Step back" until all steps are computed. The data is the worked example below: rewards, values, done flags, and the bootstrap value V(sT)V(s_T) on the right. Each step shows δt\delta_t and A^t\hat A_t in violet; the violet arrow carries γλA^t+1\gamma\lambda \hat A_{t+1} back, and it is cut at a dashed line where an episode ends. Click a done flag to toggle it. Make the last step terminal: V(sT)V(s_T) is no longer used.

    Quick check

    Your rollout buffer has 128 steps, and the episode is still running at the last step. How should GAE treat step 127?

    γ\gamma and λ\lambda have different jobs. γ\gamma is part of the objective: it decides how much the agent cares about later rewards (an effective horizon of about 1/(1−γ)1/(1-\gamma) steps). Even with a perfect critic, a smaller γ\gamma changes which policy is best. λ\lambda is only part of the estimator: with a perfect critic, every λ\lambda gives an unbiased advantage for the same objective. With an imperfect critic, λ\lambda trades its bias against the variance of the rewards. Common choices are γ=0.99\gamma = 0.99 and λ=0.95\lambda = 0.95.

    A2C and A3C #

    A3C (asynchronous advantage actor-critic, Mnih et al., 2016) runs many actor-learners in parallel threads. Each one collects a few steps, computes nn-step advantages and sends gradients to shared parameters. A2C is the synchronous version: NN copies of the environment step together, the rollout has T×NT \times N transitions, and one batched update follows. A2C uses the GPU better and works as well as A3C.

    The policy and the critic often share a network body with two heads. A2C minimizes one loss over the batch:

    L(θ,ϕ)=−1B∑ilog⁡πθ(ai∣si) A^i⏟policy term  +  cv1B∑i(Vϕ(si)−G^i)2⏟value loss  −  ce1B∑iH(πθ(⋅∣si))⏟entropy bonus,\mathcal L(\theta, \phi) = \underbrace{-\frac{1}{B}\sum_i \log \pi_\theta(a_i \mid s_i)\, \hat A_i}_{\text{policy term}} \; + \; c_v \underbrace{\frac{1}{B}\sum_i \big(V_\phi(s_i) - \hat G_i\big)^2}_{\text{value loss}} \; - \; c_e \underbrace{\frac{1}{B}\sum_i \mathcal H\big(\pi_\theta(\cdot \mid s_i)\big)}_{\text{entropy bonus}} ,

    where A^i\hat A_i is an nn-step or GAE advantage, treated as a constant, and G^i=A^i+V(si)\hat G_i = \hat A_i + V(s_i) is the value target. Typical weights are cv=0.5c_v = 0.5 and ce=0.01c_e = 0.01. The entropy bonus keeps the policy from becoming deterministic too early. Many implementations also normalize the advantages in each batch (subtract the mean, divide by the standard deviation); a constant shift is a baseline, and the scaling only changes the step size.

    A2C is on-policy: the policy gradient needs data from the current policy, so each batch is used once and then thrown away. PPO (lesson 09) reuses each batch for a few epochs, carefully.

    Continuous actions and off-policy learning: DDPG and TD3 #

    A replay buffer (lesson 06) reuses every transition many times. For continuous actions the max over actions of Q-learning is a hard optimization problem, so DDPG (Lillicrap et al., 2016) learns a deterministic actor a=μθ(s)a = \mu_\theta(s) that does the max: it moves the action uphill on the critic. By the deterministic policy gradient theorem (Silver et al., 2014),

    ∇θJ≈Es∼buffer[∇aQϕ(s,a)∣a=μθ(s) ∇θμθ(s)],\nabla_\theta J \approx \mathbb E_{s \sim \text{buffer}}\big[\nabla_a Q_\phi(s, a)\big|_{a = \mu_\theta(s)}\, \nabla_\theta \mu_\theta(s)\big],

    the chain rule through the critic. The critic learns with the target y=r+γ(1−d) Qϕ−(s′,μθ−(s′))y = r + \gamma (1 - d)\, Q_{\phi^-}(s', \mu_{\theta^-}(s')) and target networks; exploration comes from noise added to the action.

    DDPG overestimates QQ, for the same reason as Q-learning (the actor finds the errors of the critic, a maximization bias, lesson 05). TD3 (Fujimoto et al., 2018) adds three fixes:

    1. Clipped double Q-learning. Learn two critics and use the smaller target: y=r+γ(1−d)min⁡j=1,2Qϕj−(s′,a~′)y = r + \gamma (1 - d) \min_{j=1,2} Q_{\phi_j^-}(s', \tilde a'). The min fights the overestimation.
    2. Delayed policy updates. Update the actor (and the target networks) once every 2 critic updates, so the actor follows a critic that has settled.
    3. Target policy smoothing. a~′=μθ−(s′)+clip⁡(ϵ,−c,c)\tilde a' = \mu_{\theta^-}(s') + \operatorname{clip}(\epsilon, -c, c) with ϵ∼N(0,σ~2)\epsilon \sim N(0, \tilde\sigma^2): the target averages QQ over a small region, so the actor cannot exploit a narrow, wrong peak of the critic.
    Quick check

    TD3 and SAC compute the critic target with min⁡(Qϕ1−,Qϕ2−)\min(Q_{\phi_1^-}, Q_{\phi_2^-}) of two critics. What problem does this fight?

    Soft actor-critic: maximum-entropy RL #

    SAC (Haarnoja et al., 2018) changes the objective. Besides the reward, the agent is paid for the entropy of its policy in every state it visits:

    J(π)=Eτ∼π[∑tγt(rt+α H(π(⋅∣st)))],H(π(⋅∣s))=−Ea∼π(⋅∣s)[log⁡π(a∣s)].J(\pi) = \mathbb E_{\tau \sim \pi}\Big[\sum_t \gamma^t \big(r_t + \alpha\, \mathcal H(\pi(\cdot \mid s_t))\big)\Big], \qquad \mathcal H(\pi(\cdot \mid s)) = -\mathbb E_{a \sim \pi(\cdot \mid s)}\big[\log \pi(a \mid s)\big].

    Here α>0\alpha > 0 is the temperature (in this section α\alpha is not a step size). With α=0\alpha = 0 this is the usual objective. The entropy bonus makes the policy explore, makes it robust (it learns several good ways to act, not one), and makes training more stable.

    Soft value functions. With the bonus, the Bellman equations of lesson 01 become

    Q(s,a)=r(s,a)+γ Es′[V(s′)],V(s)=Ea∼π(⋅∣s)[Q(s,a)−αlog⁡π(a∣s)].Q(s, a) = r(s, a) + \gamma\, \mathbb E_{s'}\big[V(s')\big], \qquad V(s) = \mathbb E_{a \sim \pi(\cdot \mid s)}\big[Q(s, a) - \alpha \log \pi(a \mid s)\big].

    The second equation says: the soft value is the expected QQ plus α\alpha times the entropy.

    The soft-greedy policy. In a state with action values Q(s,⋅)Q(s, \cdot), which policy maximizes Ea∼π[Q(s,a)]+αH(π)\mathbb E_{a \sim \pi}[Q(s, a)] + \alpha \mathcal H(\pi)? For discrete actions:

    Theorem (Gibbs policy). Let Z=∑aeQ(s,a)/αZ = \sum_a e^{Q(s, a)/\alpha} and π∗(a∣s)=eQ(s,a)/α/Z\pi^*(a \mid s) = e^{Q(s, a)/\alpha} / Z. For every distribution π\pi over the actions,

    ∑aπ(a) Q(s,a)+α H(π)=αlog⁡Z−α KL(π ∥ π∗)≤αlog⁡Z,\sum_a \pi(a)\, Q(s, a) + \alpha\, \mathcal H(\pi) = \alpha \log Z - \alpha\, \mathrm{KL}(\pi \,\|\, \pi^*) \le \alpha \log Z ,

    with equality exactly when π=π∗\pi = \pi^*. So the best policy is π∗∝exp⁡(Q/α)\pi^* \propto \exp(Q/\alpha), and the soft value is V(s)=αlog⁡∑aeQ(s,a)/αV(s) = \alpha \log \sum_a e^{Q(s, a)/\alpha}.

    Proof.

    1. From the definition of π∗\pi^*: log⁡π∗(a)=Q(s,a)/α−log⁡Z\log \pi^*(a) = Q(s, a)/\alpha - \log Z, so Q(s,a)=αlog⁡π∗(a)+αlog⁡ZQ(s, a) = \alpha \log \pi^*(a) + \alpha \log Z.
    2. Insert this into the left side: ∑aπ(a)(αlog⁡π∗(a)+αlog⁡Z)−α∑aπ(a)log⁡π(a)\sum_a \pi(a)\big(\alpha \log \pi^*(a) + \alpha \log Z\big) - \alpha \sum_a \pi(a) \log \pi(a).
    3. Since ∑aπ(a)=1\sum_a \pi(a) = 1, this is αlog⁡Z−α∑aπ(a)log⁡π(a)π∗(a)=αlog⁡Z−α KL(π ∥ π∗)\alpha \log Z - \alpha \sum_a \pi(a) \log \frac{\pi(a)}{\pi^*(a)} = \alpha \log Z - \alpha\, \mathrm{KL}(\pi \,\|\, \pi^*).
    4. KL≥0\mathrm{KL} \ge 0, with equality only for π=π∗\pi = \pi^* (information theory 03). ■\blacksquare

    The soft value αlog⁡∑aeQ/α\alpha \log \sum_a e^{Q/\alpha} is a smooth maximum ("log-sum-exp"). As α→0\alpha \to 0 it tends to max⁡aQ(s,a)\max_a Q(s, a) and π∗\pi^* becomes greedy; as α→∞\alpha \to \infty, π∗\pi^* becomes uniform.

    Interactive figure: loading…

    Move the temperature α\alpha. The blue bars are the action values QQ, the orange bars the soft-greedy policy π∝exp⁡(Q/α)\pi \propto \exp(Q/\alpha). The violet line is the soft value VV, the dashed line is max⁡aQ\max_a Q. The chart shows the entropy of π\pi (it rises to log⁡K\log K) and how far VV is above max⁡aQ\max_a Q. The readout checks V=π⊤Q+αH(π)V = \pi^\top Q + \alpha \mathcal H(\pi). Edit the QQ values to see that only their differences, divided by α\alpha, shape π\pi.

    SAC in practice (continuous actions). SAC is an off-policy actor-critic method with a replay buffer.

    • Critics: two soft Q-networks with target networks (Polyak averaging) and the clipped double-Q target y=r+γ(1−d)(min⁡jQϕj−(s′,a~′)−αlog⁡πθ(a~′∣s′))y = r + \gamma (1 - d)\big(\min_{j} Q_{\phi_j^-}(s', \tilde a') - \alpha \log \pi_\theta(\tilde a' \mid s')\big) with a fresh a~′∼πθ(⋅∣s′)\tilde a' \sim \pi_\theta(\cdot \mid s').
    • Actor: a Gaussian whose sample is squashed by tanh⁡\tanh into the action range. It minimizes Es[Ea∼πθ[αlog⁡πθ(a∣s)−min⁡jQϕj(s,a)]]\mathbb E_{s}\big[\mathbb E_{a \sim \pi_\theta}[\alpha \log \pi_\theta(a \mid s) - \min_j Q_{\phi_j}(s, a)]\big], a KL projection of π\pi onto exp⁡(Q/α)\exp(Q/\alpha). The gradient uses the reparameterization trick (calculus 12): a=tanh⁡(μθ(s)+σθ(s)⊙ε)a = \tanh(\mu_\theta(s) + \sigma_\theta(s) \odot \varepsilon) with ε∼N(0,I)\varepsilon \sim N(0, I), so the gradient flows through the critic into θ\theta, with much lower variance than the score function.
    • Temperature: a good α\alpha depends on the scale of the rewards. The second SAC paper (Haarnoja et al., 2018b) tunes it automatically: keep the entropy near a target Hˉ\bar{\mathcal H} (often −dim⁡A-\dim \mathcal A) by minimizing Ea∼π[−α(log⁡π(a∣s)+Hˉ)]\mathbb E_{a \sim \pi}[-\alpha(\log \pi(a \mid s) + \bar{\mathcal H})]. When the entropy is below the target, this raises α\alpha; when it is above, it lowers α\alpha.
    The tanh correction in the log-probability

    The actor samples u=μ+σ⊙εu = \mu + \sigma \odot \varepsilon from a Gaussian and outputs a=tanh⁡(u)a = \tanh(u). By the change-of-variables formula (calculus 10), the density of aa is the density of uu divided by ∣det⁡∂a/∂u∣=∏i(1−tanh⁡2ui)|\det \partial a / \partial u| = \prod_i (1 - \tanh^2 u_i):

    log⁡π(a∣s)=log⁡N(u;μ,diag⁡σ2)−∑ilog⁡(1−tanh⁡2(ui)).\log \pi(a \mid s) = \log N(u; \mu, \operatorname{diag}\sigma^2) - \sum_i \log\big(1 - \tanh^2(u_i)\big).

    Forgetting the second term makes the entropy estimate wrong, and the temperature tuning then fails. Code uses the stable form log⁡(1−tanh⁡2u)=2(log⁡2−u−softplus⁡(−2u))\log(1 - \tanh^2 u) = 2(\log 2 - u - \operatorname{softplus}(-2u)).

    On-policy or off-policy?

    A2C, PPO (on-policy) DDPG, TD3, SAC (off-policy)
    Data fresh rollouts of the current policy a replay buffer of old transitions
    Policy stochastic (softmax or Gaussian) deterministic (DDPG, TD3) or stochastic (SAC)
    Critic Vϕ(s)V_\phi(s), targets from GAE Qϕ(s,a)Q_\phi(s, a) (two in TD3 and SAC), TD targets
    Actor gradient score function × advantage through the critic: ∇aQ\nabla_a Q (TD3) or reparameterization (SAC)
    Actions discrete or continuous mainly continuous (SAC also has a discrete version)
    Sample efficiency lower higher (each transition is reused)
    Typical use parallel simulators, RLHF for language models robots and expensive simulators

    Answers to section 1. (1) Bootstrap with VV of the next state: the episode did not end, only the data did. Using 0 treats a truncation as a termination and biases the targets. (2) No. λ\lambda only changes how we estimate the advantage; with an exact critic every λ\lambda is unbiased. γ\gamma is part of the objective. (3) α→0\alpha \to 0 gives the usual objective and a greedy policy π→arg⁡max⁡aQ\pi \to \arg\max_a Q. A very large α\alpha makes the entropy dominate: the policy becomes almost uniform, whatever the rewards.

    4. Worked example #

    (a) GAE with an episode end. Three steps, γ=0.9\gamma = 0.9, λ=0.8\lambda = 0.8, so γλ=0.72\gamma\lambda = 0.72.

    tt rtr_t dtd_t V(st)V(s_t)
    0 1 0 1.0
    1 1 1 0.5
    2 0 0 1.0

    The episode ends with step 1; step 2 is the first step of a new episode. The rollout stops after step 2 while that episode is still running, so we bootstrap with V(s3)=2.0V(s_3) = 2.0. Go backward:

    • t=2t = 2: d2=0d_2 = 0, so bootstrap. δ2=0+0.9⋅2.0−1.0=0.8\delta_2 = 0 + 0.9 \cdot 2.0 - 1.0 = 0.8. There is nothing after it in the rollout (A^3=0\hat A_3 = 0), so A^2=0.8\hat A_2 = 0.8.
    • t=1t = 1: d1=1d_1 = 1, so no bootstrap and no carry. δ1=1+0.9⋅0⋅V(s2)−0.5=0.5\delta_1 = 1 + 0.9 \cdot 0 \cdot V(s_2) - 0.5 = 0.5, and A^1=0.5+0.72⋅0⋅A^2=0.5\hat A_1 = 0.5 + 0.72 \cdot 0 \cdot \hat A_2 = 0.5.
    • t=0t = 0: d0=0d_0 = 0. δ0=1+0.9⋅0.5−1.0=0.45\delta_0 = 1 + 0.9 \cdot 0.5 - 1.0 = 0.45, and A^0=0.45+0.72⋅0.5=0.81\hat A_0 = 0.45 + 0.72 \cdot 0.5 = 0.81.

    Advantages (0.81,0.5,0.8)(0.81, 0.5, 0.8); value targets A^t+V(st)=(1.81,1.0,1.8)\hat A_t + V(s_t) = (1.81, 1.0, 1.8).

    Check A^0\hat A_0 with the theorem. The episode of step 0 ends after two steps, so A^0(1)=δ0=0.45\hat A_0^{(1)} = \delta_0 = 0.45 and every longer estimator equals A^0(2)=1+0.9⋅1−1.0=0.9\hat A_0^{(2)} = 1 + 0.9 \cdot 1 - 1.0 = 0.9 (that is, G0−V(s0)G_0 - V(s_0)). The weights are 1−λ=0.21 - \lambda = 0.2 on A^0(1)\hat A_0^{(1)} and the rest, λ=0.8\lambda = 0.8, on the full estimate: 0.2⋅0.45+0.8⋅0.9=0.09+0.72=0.810.2 \cdot 0.45 + 0.8 \cdot 0.9 = 0.09 + 0.72 = 0.81 ✓.

    What if step 1 were not an episode end? Then δ1=1+0.9⋅1.0−0.5=1.4\delta_1 = 1 + 0.9 \cdot 1.0 - 0.5 = 1.4 and A^1=1.4+0.72⋅0.8=1.976\hat A_1 = 1.4 + 0.72 \cdot 0.8 = 1.976: the advantage of step 2 now flows back.

    (b) The soft-greedy policy. One state, three actions with Q=(1,2,0)Q = (1, 2, 0).

    • α=1\alpha = 1: eQ=(2.718,7.389,1)e^{Q} = (2.718, 7.389, 1), sum Z=11.107Z = 11.107. So π=(0.245,0.665,0.090)\pi = (0.245, 0.665, 0.090) and V=1⋅ln⁡11.107=2.4076V = 1 \cdot \ln 11.107 = 2.4076. Check: π⊤Q=0.245+1.330=1.575\pi^\top Q = 0.245 + 1.330 = 1.575 and H(π)=0.832\mathcal H(\pi) = 0.832, so π⊤Q+αH=1.575+0.832=2.408\pi^\top Q + \alpha \mathcal H = 1.575 + 0.832 = 2.408 ✓. The soft value is above max⁡Q=2\max Q = 2 because of the entropy bonus.
    • α=0.1\alpha = 0.1: Q/α=(10,20,0)Q/\alpha = (10, 20, 0); the policy is almost greedy, π≈(0.00005,0.99995,0)\pi \approx (0.00005, 0.99995, 0), and V=2+0.1ln⁡(1+e−10+e−20)≈2.000005V = 2 + 0.1 \ln(1 + e^{-10} + e^{-20}) \approx 2.000005.
    • α=10\alpha = 10: Q/α=(0.1,0.2,0)Q/\alpha = (0.1, 0.2, 0); π=(0.332,0.367,0.301)\pi = (0.332, 0.367, 0.301), almost uniform, and V=10ln⁡(e0.1+e0.2+1)=10ln⁡3.327=12.019V = 10 \ln(e^{0.1} + e^{0.2} + 1) = 10 \ln 3.327 = 12.019. Now αH=10⋅1.095=10.95\alpha \mathcal H = 10 \cdot 1.095 = 10.95 is most of the value.

    5. In code #

    NumPy checks both parts of the worked example. The GAE function works for one environment; the notebook extends it to many parallel environments.

    import numpy as np
    
    def gae(rewards, values, dones, last_value, gamma, lam):
        T = len(rewards)
        adv = np.zeros(T)
        next_adv, next_value = 0.0, last_value
        for t in reversed(range(T)):
            nonterminal = 1.0 - dones[t]
            delta = rewards[t] + gamma * nonterminal * next_value - values[t]
            next_adv = delta + gamma * lam * nonterminal * next_adv
            adv[t] = next_adv
            next_value = values[t]
        return adv, adv + values
    
    r = np.array([1.0, 1.0, 0.0]); d = np.array([0, 1, 0]); v = np.array([1.0, 0.5, 1.0])
    adv, targets = gae(r, v, d, last_value=2.0, gamma=0.9, lam=0.8)
    print(adv.round(4), targets.round(4))        # [0.81 0.5  0.8 ] [1.81 1.   1.8 ]
    print(gae(r, v, d, 2.0, 0.9, 0.0)[0].round(4))   # lambda = 0: the TD errors [0.45 0.5  0.8 ]
    print(gae(r, v, d, 2.0, 0.9, 1.0)[0].round(4))   # lambda = 1: G_t - V(s_t) [0.9 0.5 0.8]
    
    # soft-greedy policy and soft value for Q = (1, 2, 0)
    Q = np.array([1.0, 2.0, 0.0])
    for alpha in (0.1, 1.0, 10.0):
        z = Q / alpha
        pi = np.exp(z - z.max()); pi /= pi.sum()
        V = alpha * (z.max() + np.log(np.exp(z - z.max()).sum()))
        H = -(pi * np.log(pi + 1e-300)).sum()
        print(alpha, pi.round(3), round(V, 4), np.isclose(V, pi @ Q + alpha * H))
    # 0.1 [0. 1. 0.] 2.0 True
    # 1.0 [0.245 0.665 0.09 ] 2.4076 True
    # 10.0 [0.332 0.367 0.301] 12.0194 True
    

    CleanRL's ppo.py contains the same GAE loop (note that its dones array is shifted by one step: there, dones[t] says whether sts_t is the first state of a new episode). The log-sum-exp form of VV subtracts the maximum first, so it does not overflow for small α\alpha.

    6. Where it shows up #

    • PPO for robots, games and language models. GAE with λ≈0.95\lambda \approx 0.95, the critic fitted to A^+V\hat A + V, advantage normalization and an entropy bonus are the defaults of PPO (lesson 09). In RLHF the critic is a value head on a copy of the language model; critic-free methods such as GRPO replace it with the mean score of several answers to the same prompt.
    • Continuous control. SAC and TD3 are standard baselines on MuJoCo and DeepMind Control tasks, and SAC has learned locomotion and grasping directly on real robots, where its sample efficiency matters.
    • Game agents at scale. A3C showed that strong Atari agents can be trained on one multi-core CPU; IMPALA (Espeholt et al., 2018) scales the actor-critic idea to many machines with an off-policy correction (V-trace).
    • ML for science and engineering. An actor-critic agent controls the shape of the plasma in a tokamak fusion reactor (Degrave et al., 2022; trained with the actor-critic method MPO in a simulator). Similar agents are studied for chemical process control and particle accelerator tuning, where actions are continuous and simulators are expensive.

    7. Common mistakes #

    • Truncation treated as termination. A time limit is not an end of the task. Set dt=1d_t = 1 only for real terminations; at a time limit, bootstrap with VV of the real next state. With auto-resetting vector environments, the returned observation is already the first state of the next episode; use the final observation that the environment reports separately.
    • No reset at episode ends. Without the factor (1−dt)(1 - d_t), GAE leaks advantages from one episode into the previous one.
    • Gradient through the advantage or the target. A^t\hat A_t and A^t+V(st)\hat A_t + V(s_t) are constants in the losses. Detach them; otherwise the policy loss also changes the critic, and the value loss chases a moving target.
    • "λ is a second discount." γ\gamma changes the objective; λ\lambda only changes the estimator.
    • One critic, no target network, off-policy. Off-policy actor-critic methods overestimate without clipped double Q and target networks; this is the deadly triad of lesson 06 with an actor that exploits it.
    • Forgetting the entropy term in SAC's targets. The soft target contains −αlog⁡π(a~′∣s′)-\alpha \log \pi(\tilde a' \mid s'); without it the critic learns ordinary QQ values, and the actor's objective no longer matches.
    • A fixed temperature across tasks. The right α\alpha depends on the reward scale. Tune it automatically or scale the rewards.

    8. Check yourself #

    1. Write the actor and critic updates of one-step actor-critic.
      Answerδ=r+γ(1−d)Vϕ(s′)−Vϕ(s)\delta = r + \gamma(1 - d) V_\phi(s') - V_\phi(s); critic ϕ←ϕ+ηϕδ∇ϕVϕ(s)\phi \leftarrow \phi + \eta_\phi \delta \nabla_\phi V_\phi(s); actor θ←θ+ηθδ∇θlog⁡πθ(a∣s)\theta \leftarrow \theta + \eta_\theta \delta \nabla_\theta \log \pi_\theta(a \mid s).
    2. The critic is wrong by e(s)e(s). Which part of the error of A^t(k)\hat A_t^{(k)} biases the policy gradient, and which part does not?
      AnswerThe error γke(st+k)\gamma^k e(s_{t+k}) at the bootstrap state biases it. The term −e(st)-e(s_t) depends only on the current state, so it acts like a baseline and adds no bias.
    3. Show in one line that A^t(2)=δt+γδt+1\hat A_t^{(2)} = \delta_t + \gamma \delta_{t+1}.
      Answerδt+γδt+1=rt+γV(st+1)−V(st)+γrt+1+γ2V(st+2)−γV(st+1)=rt+γrt+1+γ2V(st+2)−V(st)\delta_t + \gamma\delta_{t+1} = r_t + \gamma V(s_{t+1}) - V(s_t) + \gamma r_{t+1} + \gamma^2 V(s_{t+2}) - \gamma V(s_{t+1}) = r_t + \gamma r_{t+1} + \gamma^2 V(s_{t+2}) - V(s_t).
    4. Compute GAE for one step with r=2r = 2, V(s0)=1V(s_0) = 1, γ=0.9\gamma = 0.9, λ=0.95\lambda = 0.95, when (a) the episode terminates after the step, (b) the rollout is truncated and V(s1)=3V(s_1) = 3.
      Answer(a) A^0=δ0=2−1=1\hat A_0 = \delta_0 = 2 - 1 = 1. (b) A^0=δ0=2+0.9⋅3−1=3.7\hat A_0 = \delta_0 = 2 + 0.9 \cdot 3 - 1 = 3.7. With one step, λ\lambda plays no role.
    5. Two actions with Q=(0,ln⁡3)Q = (0, \ln 3) and α=1\alpha = 1. Give the soft-greedy policy and the soft value.
      AnswereQ=(1,3)e^Q = (1, 3), so π=(0.25,0.75)\pi = (0.25, 0.75) and V=ln⁡4≈1.386V = \ln 4 \approx 1.386. Check: π⊤Q=0.75ln⁡3=0.824\pi^\top Q = 0.75 \ln 3 = 0.824 and H=0.562\mathcal H = 0.562, sum 1.3861.386.
    6. Name TD3's three changes to DDPG and the problem each one solves.
      AnswerClipped double Q (the min of two critics) against overestimation; delayed actor updates so the actor follows a settled critic; target policy smoothing (clipped noise on the target action) so the actor cannot exploit narrow errors of the critic.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write the TD error used by the critic and the actor.

    2. Write the one-step actor-critic updates.

    3. Write GAE as a sum of TD errors.

    4. Write the backward recursion of GAE with done flags.

    5. What do λ=0\lambda = 0 and λ=1\lambda = 1 give in GAE?

    6. What is the difference between the roles of γ\gamma and λ\lambda?

    7. A rollout stops at a time limit. What value follows the last step in GAE?

    8. Name the three terms of the A2C loss.

    9. Write SAC's maximum-entropy objective.

    10. Give the soft-greedy policy and the soft value for discrete actions.

    Open the review →

    9. Interview angle #

    • "Explain GAE and λ\lambda." — An exponentially weighted average of kk-step advantage estimators, equal to ∑l(γλ)lδt+l\sum_l (\gamma\lambda)^l \delta_{t+l}; λ\lambda trades the critic's bias against Monte Carlo variance. Give the two ends.
    • "How do you handle time limits?" — Bootstrap at truncation, not at termination; keep terminated and truncated apart, and use the final observation, not the reset one.
    • "Why two critics in TD3 and SAC?" — The actor exploits overestimation; the min of two critics is a pessimistic target (clipped double Q), like double Q-learning.
    • "SAC or PPO?" — SAC: off-policy, sample efficient, continuous actions, needs a replay buffer and careful critics. PPO: on-policy, simple and stable, works for discrete and continuous actions and with many parallel simulators, the standard for RLHF.
    • "Why the entropy bonus?" — It keeps exploration, avoids early collapse to a deterministic policy, and in SAC gives a smooth (soft) Bellman equation with a Boltzmann policy.
    • "Which should learn faster, the actor or the critic?" — Usually the critic. It must track the current policy (the two-timescale analysis of actor-critic methods); a fast actor follows the critic's errors.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. gae(rewards, values, dones, last_value, gamma, lam) for one or many parallel environments, with done flags and a bootstrap value; checked against the worked example, the two ends λ=0,1\lambda = 0, 1, and a direct sum.
    2. normalize_advantages: zero mean and unit standard deviation over the whole batch.
    3. Bias and variance of GAE with an imperfect critic on a chain, by simulation, for several λ\lambda; compare with the exact formulas.
    4. One-step actor-critic (tabular softmax actor, tabular critic) on the 4×4 gridworld; the learned greedy policy takes the shortest path from every cell.
    5. Soft value iteration on the 4×4 gridworld for several temperatures α\alpha: the soft values approach V∗V^* as α→0\alpha \to 0 and grow with α\alpha, and the policy's entropy grows.

    11. Watch and read #

    Advantage estimation: from baselines to k-step estimates and GAE.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The deterministic policy gradient, DDPG and the maximum-entropy idea behind SAC.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A careful lecture from the policy gradient theorem to actor-critic methods and their variants.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play