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

    Reinforcement Learning · Lesson 7 · Function approximation and policy optimization

    Policy gradients: the policy gradient theorem, REINFORCE and baselines

    Advanced 75 min 4 interactive figures 4 videos Colab notebook

    Before this lesson: returns, VπV^\pi, QπQ^\pi and the advantage (lesson 01); Monte Carlo returns (lesson 04); the score-function gradient estimator (calculus 12); the chain rule (calculus 04); softmax (foundations 05); stochastic gradient ascent (optimization 05). Time: about 75 minutes, plus the notebook.


    Why this matters #

    Value-based methods (lesson 05 and lesson 06) need a max over actions. That is hard when the actions are continuous (the torques of a robot arm) or very many (all next tokens of a language model). Policy gradients work in both cases, they can learn stochastic policies, and they need no derivative of the reward: the reward can come from a simulator, a game result, a unit test or a human rating.

    • Actor-critic methods and PPO (lesson 08 and lesson 09) are REINFORCE plus a learned baseline and a better estimate of the advantage.
    • RL for language models. RLHF with PPO, and the critic-free methods RLOO and GRPO, all start from the score-function gradient of this lesson. They differ in the baseline.
    • AlphaGo trained its policy network by self-play with a policy gradient (Silver et al., 2016). Neural architecture search (Zoph and Le, 2017) and sequence-level training of captioning models (self-critical sequence training, Rennie et al., 2017) use REINFORCE with a baseline.

    1. Predict first #

    2. The picture #

    Policies with parameters #

    A parameterized policy πθ(a∣s)\pi_\theta(a \mid s) gives a probability for every action, and it is differentiable in the parameters θ\theta. Two families cover most uses.

    • Softmax policy (discrete actions). A function hθ(s,a)h_\theta(s, a) gives a score, called a logit or a preference, to every action. The policy is the softmax of the logits:
    πθ(a∣s)=exp⁡hθ(s,a)∑bexp⁡hθ(s,b).\pi_\theta(a \mid s) = \frac{\exp h_\theta(s, a)}{\sum_{b} \exp h_\theta(s, b)} .

    In the tabular case hθ(s,a)=θ(s,a)h_\theta(s, a) = \theta(s, a): one number per state–action pair. With features, hθ(s,a)=θ⊤x(s,a)h_\theta(s, a) = \theta^\top x(s, a); in deep RL, a network outputs the logits.

    • Gaussian policy (continuous actions). A function μθ(s)\mu_\theta(s) gives the mean action, and the action is a∼N(μθ(s),σ2)a \sim N(\mu_\theta(s), \sigma^2). The standard deviation σ\sigma is fixed, or it is a learned parameter (usually through log⁡σ\log \sigma, so that σ>0\sigma > 0).

    The objective is the expected return from the start, J(θ)J(\theta). We do gradient ascent: θ←θ+η ∇J^\theta \leftarrow \theta + \eta \, \widehat{\nabla J}, with a learning rate η\eta and an estimate ∇J^\widehat{\nabla J} of the gradient.

    One step first: the log-derivative trick #

    Take one state and KK actions with fixed rewards rar_a (a bandit, lesson 03). The objective is the expected reward

    J(θ)=∑aπθ(a) ra.J(\theta) = \sum_a \pi_\theta(a)\, r_a .

    Its gradient is ∇J=∑a∇πθ(a) ra\nabla J = \sum_a \nabla \pi_\theta(a)\, r_a. This sum is not an expectation, so we cannot estimate it from samples of aa. The log-derivative trick fixes this. Since ∇log⁡π=∇π/π\nabla \log \pi = \nabla \pi / \pi, we have ∇π=π ∇log⁡π\nabla \pi = \pi\, \nabla \log \pi, and

    ∇J=∑aπθ(a) ∇log⁡πθ(a) ra=Ea∼πθ[∇log⁡πθ(a)  ra].\nabla J = \sum_a \pi_\theta(a)\, \nabla \log \pi_\theta(a)\, r_a = \mathbb E_{a \sim \pi_\theta}\big[\nabla \log \pi_\theta(a)\; r_a\big].

    Now the gradient is an expectation over actions from the policy itself. Sample a∼πθa \sim \pi_\theta, look at the reward, and ∇log⁡πθ(a) ra\nabla \log \pi_\theta(a)\, r_a is an unbiased estimate of ∇J\nabla J. We never need to know how rr depends on aa.

    The vector ∇θlog⁡πθ(a)\nabla_\theta \log \pi_\theta(a) is the score of action aa. It is the direction in parameter space that makes aa more likely, fastest. The reward says how much we want that.

    The softmax score. For π=softmax⁡(θ)\pi = \operatorname{softmax}(\theta), write log⁡πa=θa−log⁡∑beθb\log \pi_a = \theta_a - \log \sum_b e^{\theta_b}. Differentiate with respect to θi\theta_i:

    1. the first term gives ∂θa/∂θi=1\partial \theta_a / \partial \theta_i = 1 if i=ai = a and 0 otherwise;
    2. the second term gives eθi/∑beθb=πie^{\theta_i} / \sum_b e^{\theta_b} = \pi_i;
    3. so ∂log⁡πa/∂θi=1[i=a]−πi\partial \log \pi_a / \partial \theta_i = \mathbb 1[i = a] - \pi_i, that is,
    ∇θlog⁡πθ(a)=ea−π,\nabla_\theta \log \pi_\theta(a) = e_a - \pi ,

    the one-hot vector of aa minus the probability vector. It raises the logit of aa and lowers every logit in proportion to its probability. Its entries add up to 0.

    Interactive figure: loading…

    Drag the logits θ1,θ2,θ3\theta_1, \theta_2, \theta_3, then press Sample. The bars are the policy π and the rewards r=(1,0,2)r = (1, 0, 2). The plane shows gradient vectors (all of them have entries that add up to 0, so they lie in a plane). Each orange point ga=(ra−b)(ea−π)g_a = (r_a - b)(e_a - \pi) is one possible REINFORCE sample; its area is its probability πa\pi_a. The black arrow is the exact gradient ∇J\nabla J, and the dashed orange arrow is the mean of your samples. Move the baseline bb: the points move, the black arrow does not, and the variance in the readout changes.

    Quick check

    A softmax policy over 3 actions has π=(0.5,0.3,0.2)\pi = (0.5, 0.3, 0.2). You sample action 2. What is the score ∇θlog⁡πθ(2)\nabla_\theta \log \pi_\theta(2)?

    Continuous actions: the Gaussian score #

    For a Gaussian policy a∼N(μ,σ2)a \sim N(\mu, \sigma^2),

    log⁡π(a)=−(a−μ)22σ2−log⁡σ−12log⁡(2π),\log \pi(a) = -\frac{(a - \mu)^2}{2 \sigma^2} - \log \sigma - \tfrac12 \log(2\pi),

    so the scores of the two parameters are

    ∂log⁡π(a)∂μ=a−μσ2,∂log⁡π(a)∂σ=(a−μ)2−σ2σ3.\frac{\partial \log \pi(a)}{\partial \mu} = \frac{a - \mu}{\sigma^2}, \qquad \frac{\partial \log \pi(a)}{\partial \sigma} = \frac{(a - \mu)^2 - \sigma^2}{\sigma^3} .

    Read the first one as a picture. A sample aa to the right of μ\mu has a positive score: making it more likely means moving μ\mu to the right. The REINFORCE term a−μσ2 r(a)\frac{a - \mu}{\sigma^2}\, r(a) moves μ\mu toward samples with high reward. If μ=μθ(s)\mu = \mu_\theta(s) is the output of a network, the chain rule gives ∇θlog⁡π=a−μσ2∇θμθ(s)\nabla_\theta \log \pi = \frac{a - \mu}{\sigma^2} \nabla_\theta \mu_\theta(s), and autodiff does this for you.

    Interactive figure: loading…

    Press "Sample 20 actions". The aqua curve is the reward r(a)r(a), and the orange area is the policy N(μ,σ2)N(\mu, \sigma^2). Each orange dot is a sampled action on the reward curve. Under the axis, each violet arrow is that sample's push on μ\mu, a−μσ2(r(a)−b)\frac{a - \mu}{\sigma^2}(r(a) - b). Then press "Gradient step" a few times and watch μ\mu climb to the peak. Turn on the baseline b=J(μ,σ)b = J(\mu, \sigma): the arrows change a lot, their mean does not.

    Quick check

    A Gaussian policy has μ=1\mu = 1 and σ=0.5\sigma = 0.5. You sample a=1.5a = 1.5 and get reward r=3r = 3. What is this sample's REINFORCE term for μ\mu (no baseline)?

    3. Definitions and main results #

    Episodes and the objective #

    An episode, or trajectory, is τ=(s0,a0,r0,s1,a1,r1,… )\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \dots), where rtr_t is the reward after (st,at)(s_t, a_t) (Sutton and Barto write Rt+1R_{t+1}; see lesson 01). Under the policy πθ\pi_\theta its probability is

    pθ(τ)=p0(s0)∏tπθ(at∣st) P(st+1∣st,at),p_\theta(\tau) = p_0(s_0) \prod_{t} \pi_\theta(a_t \mid s_t)\, P(s_{t+1} \mid s_t, a_t),

    with the start-state distribution p0p_0. The objective is the expected discounted return from the start:

    J(θ)=Eτ∼pθ[∑t≥0γtrt]=∑sp0(s) Vπθ(s).J(\theta) = \mathbb E_{\tau \sim p_\theta}\Big[\sum_{t \ge 0} \gamma^t r_t\Big] = \sum_s p_0(s)\, V^{\pi_\theta}(s).

    Two more objects:

    • the reward-to-go (the return from step tt), Gt=∑k≥tγk−trkG_t = \sum_{k \ge t} \gamma^{k-t} r_k;
    • the discounted state visitation dπ(s)=∑t≥0γtPr⁡(st=s)d^\pi(s) = \sum_{t \ge 0} \gamma^t \Pr(s_t = s). It is not normalized: it adds up to E[∑tγt]\mathbb E[\sum_t \gamma^t], not to 1. The normalized version is (1−γ)dπ(1-\gamma) d^\pi when γ<1\gamma < 1 and episodes never end.

    Assumptions. Finite state and action sets, bounded rewards, and πθ(a∣s)\pi_\theta(a \mid s) differentiable in θ\theta. To keep the proof short, every episode ends after at most HH steps (HH may be huge); then all sums are finite, and we may exchange ∇\nabla and ∑\sum. A limit argument extends the result to episodes of unbounded length when γ<1\gamma < 1 or when the episode ends with probability 1 and has a finite expected length.

    The policy gradient theorem #

    Theorem (policy gradient; Sutton, McAllester, Singh and Mansour, NeurIPS 1999). Under the assumptions above,

    ∇θJ(θ)=Eτ∼pθ[∑tγt ∇θlog⁡πθ(at∣st)  Qπθ(st,at)]=∑sdπθ(s)∑a∇θπθ(a∣s)  Qπθ(s,a).\nabla_\theta J(\theta) = \mathbb E_{\tau \sim p_\theta}\Big[\sum_{t} \gamma^t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\; Q^{\pi_\theta}(s_t, a_t)\Big] = \sum_s d^{\pi_\theta}(s) \sum_a \nabla_\theta \pi_\theta(a \mid s)\; Q^{\pi_\theta}(s, a).

    Proof.

    1. Write JJ as a sum over trajectories: J=∑τpθ(τ) R(τ)J = \sum_\tau p_\theta(\tau)\, R(\tau) with R(τ)=∑tγtrtR(\tau) = \sum_t \gamma^t r_t.

    2. Likelihood ratio. R(τ)R(\tau) does not depend on θ\theta once τ\tau is fixed. Use ∇pθ=pθ∇log⁡pθ\nabla p_\theta = p_\theta \nabla \log p_\theta:

    ∇J=∑τpθ(τ) ∇log⁡pθ(τ) R(τ)=E[∇log⁡pθ(τ) R(τ)].\nabla J = \sum_\tau p_\theta(\tau)\, \nabla \log p_\theta(\tau)\, R(\tau) = \mathbb E\big[\nabla \log p_\theta(\tau)\, R(\tau)\big].

    3. The dynamics drop out. The log of the product is

    log⁡pθ(τ)=log⁡p0(s0)+∑tlog⁡πθ(at∣st)+∑tlog⁡P(st+1∣st,at).\log p_\theta(\tau) = \log p_0(s_0) + \sum_t \log \pi_\theta(a_t \mid s_t) + \sum_t \log P(s_{t+1} \mid s_t, a_t).

    Only the middle sum depends on θ\theta, so ∇log⁡pθ(τ)=∑t∇log⁡πθ(at∣st)\nabla \log p_\theta(\tau) = \sum_t \nabla \log \pi_\theta(a_t \mid s_t). No model of PP is needed. Together with step 2: ∇J=E[∑t∇log⁡πθ(at∣st)∑kγkrk]\nabla J = \mathbb E\big[\sum_t \nabla \log \pi_\theta(a_t \mid s_t) \sum_k \gamma^k r_k\big].

    4. Causality. Take a pair k<tk < t: the reward rkr_k came before the action ata_t. Condition on the history ht=(s0,a0,r0,…,st)h_t = (s_0, a_0, r_0, \dots, s_t). Given hth_t, the reward rkr_k is fixed, and

    E[∇log⁡πθ(at∣st)∣ht]=∑aπθ(a∣st) ∇πθ(a∣st)πθ(a∣st)=∇∑aπθ(a∣st)=∇1=0.\mathbb E\big[\nabla \log \pi_\theta(a_t \mid s_t) \mid h_t\big] = \sum_a \pi_\theta(a \mid s_t)\, \frac{\nabla \pi_\theta(a \mid s_t)}{\pi_\theta(a \mid s_t)} = \nabla \sum_a \pi_\theta(a \mid s_t) = \nabla 1 = 0 .

    So E[∇log⁡πθ(at∣st) rk]=E[rk E[∇log⁡πθ(at∣st)∣ht]]=0\mathbb E[\nabla \log \pi_\theta(a_t \mid s_t)\, r_k] = \mathbb E\big[r_k\, \mathbb E[\nabla \log \pi_\theta(a_t \mid s_t) \mid h_t]\big] = 0. Drop all these pairs. What remains for step tt is ∑k≥tγkrk=γtGt\sum_{k \ge t} \gamma^k r_k = \gamma^t G_t:

    ∇J=E[∑tγt ∇log⁡πθ(at∣st) Gt].\nabla J = \mathbb E\Big[\sum_t \gamma^t\, \nabla \log \pi_\theta(a_t \mid s_t)\, G_t\Big].

    5. Replace GtG_t by QπQ^\pi. Condition on hth_t and ata_t. By the Markov property, E[Gt∣ht,at]=Qπ(st,at)\mathbb E[G_t \mid h_t, a_t] = Q^\pi(s_t, a_t), and the score is fixed given ht,ath_t, a_t. The tower rule gives the first form of the theorem.

    6. The visitation form. Write the expectation at step tt as a sum over st=ss_t = s and at=aa_t = a: E[γt∇log⁡π(at∣st) Qπ(st,at)]=γt∑sPr⁡(st=s)∑aπ(a∣s)∇log⁡π(a∣s) Qπ(s,a)\mathbb E[\gamma^t \nabla \log \pi(a_t \mid s_t)\, Q^\pi(s_t, a_t)] = \gamma^t \sum_s \Pr(s_t = s) \sum_a \pi(a \mid s) \nabla \log \pi(a \mid s)\, Q^\pi(s, a). Use π∇log⁡π=∇π\pi \nabla \log \pi = \nabla \pi and sum over tt: ∑tγtPr⁡(st=s)=dπ(s)\sum_t \gamma^t \Pr(s_t = s) = d^\pi(s). ■\blacksquare

    The surprising part: changing θ\theta also changes which states the agent visits, but the gradient has no term ∇dπ\nabla d^\pi. All of that effect is inside QπQ^\pi. This is why the gradient can be estimated from episodes without a model.

    Interactive figure: loading…

    Click a step tt. The top row shows the actions ata_t of one episode, the second row the rewards. The bracket shows which rewards multiply the score of the selected step. In the "full return" mode all rewards count; in the "reward-to-go" mode the rewards before tt are dropped (step 4 of the proof: their term has mean 0). In this toy problem every step is an independent coin with π(a=1)=p\pi(a = 1) = p and reward rt=atr_t = a_t. The chart shows the exact variance of the three estimators. Their means are all equal.

    Quick check

    Which of these does REINFORCE need to compute its gradient estimate from one episode?

    REINFORCE #

    Replace the expectation in step 4 by one sampled episode. This is REINFORCE (Williams, 1992).

    The factor γt\gamma^t. It comes from the proof and is needed for an unbiased gradient of the discounted objective. Most implementations drop it and use ∑t(Gt−b(st))∇log⁡πθ(at∣st)\sum_t (G_t - b(s_t)) \nabla \log \pi_\theta(a_t \mid s_t). Then late steps count as much as early ones. This update is not the gradient of JJ; Nota and Thomas (2020) show that it is in general not the gradient of any function. It still works well in practice, and it is closer to what we usually want: good behaviour in every state, not only near the start.

    Baselines #

    Lemma (a baseline adds no bias). For any function b(s)b(s) of the state only,

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

    So Gt−b(st)G_t - b(s_t) can replace GtG_t at every step: condition on sts_t as in step 4 of the proof, and the extra term has mean 0. Only the variance changes.

    Why the variance falls. Suppose every return is about −50±2-50 \pm 2. Without a baseline, every sampled action gets the weight ≈−50\approx -50: each update pushes the sampled actions down with a big weight, and only the small differences between episodes tell good from bad. The noise in "which action happened to be sampled" is multiplied by 50. Subtract b≈−50b \approx -50, and the weights become ≈±2\approx \pm 2: an action is pushed up if it did better than usual and down if it did worse.

    The natural choice is b(s)=Vπ(s)b(s) = V^\pi(s). Then Gt−Vπ(st)G_t - V^\pi(s_t) is an estimate of the advantage Aπ(st,at)=Qπ(st,at)−Vπ(st)A^\pi(s_t, a_t) = Q^\pi(s_t, a_t) - V^\pi(s_t): how much better the action was than the policy's average in that state. Given the state, the advantage has mean 0. Learning VπV^\pi with a second model gives the actor-critic methods of lesson 08.

    A baseline must not depend on the action. With b(s,a)b(s, a) the lemma fails: ∑a∇π(a∣s) b(s,a)\sum_a \nabla \pi(a \mid s)\, b(s, a) is in general not 0, and the estimate is biased. (Methods that use action-dependent control variates add a correction term to remove this bias.)

    Quick check

    You use the baseline b(st,at)=Q(st,at)b(s_t, a_t) = Q(s_t, a_t), a learned estimate of the action value, in REINFORCE. What happens?

    The variance-optimal constant baseline

    Take the one-step problem with score sa=∇log⁡π(a)s_a = \nabla \log \pi(a) and a constant baseline bb. The total variance of g^=(ra−b)sa\hat g = (r_a - b) s_a is E[(ra−b)2∥sa∥2]−∥∇J∥2\mathbb E[(r_a - b)^2 \|s_a\|^2] - \|\nabla J\|^2, because the mean does not depend on bb. Set the derivative in bb to zero: −2 E[(ra−b)∥sa∥2]=0-2\, \mathbb E[(r_a - b) \|s_a\|^2] = 0, so

    b∗=E[∥sa∥2 ra]E[∥sa∥2].b^* = \frac{\mathbb E\big[\|s_a\|^2\, r_a\big]}{\mathbb E\big[\|s_a\|^2\big]} .

    It is a weighted average of the rewards, with weights ∥sa∥2\|s_a\|^2. It equals J=E[ra]J = \mathbb E[r_a] when every action has a score of the same length (as in the worked example below), and it differs from JJ in general. In practice b(s)≈Vπ(s)b(s) \approx V^\pi(s) is used: it is close to optimal and easy to learn. The "best constant b" button in the first figure computes b∗b^*.

    The exact gradient of a tabular softmax policy #

    Corollary. For πθ(a∣s)=softmax⁡(θ(s,⋅))a\pi_\theta(a \mid s) = \operatorname{softmax}(\theta(s, \cdot))_a,

    ∂J∂θ(s,a)=dπ(s)  π(a∣s)  Aπ(s,a).\frac{\partial J}{\partial \theta(s, a)} = d^\pi(s)\; \pi(a \mid s)\; A^\pi(s, a).

    Proof.

    1. The softmax score in state s′s' only involves the row θ(s′,⋅)\theta(s', \cdot): ∂log⁡π(a′∣s′)/∂θ(s,a)=1[s′=s] (1[a′=a]−π(a∣s))\partial \log \pi(a' \mid s') / \partial \theta(s, a) = \mathbb 1[s' = s]\,\big(\mathbb 1[a' = a] - \pi(a \mid s)\big).
    2. Insert this in the visitation form, written with ∇π=π∇log⁡π\nabla \pi = \pi \nabla \log \pi: ∂J/∂θ(s,a)=dπ(s)∑a′π(a′∣s)(1[a′=a]−π(a∣s))Qπ(s,a′)\partial J / \partial \theta(s, a) = d^\pi(s) \sum_{a'} \pi(a' \mid s) \big(\mathbb 1[a' = a] - \pi(a \mid s)\big) Q^\pi(s, a').
    3. The sum is π(a∣s)Qπ(s,a)−π(a∣s)∑a′π(a′∣s)Qπ(s,a′)=π(a∣s)(Qπ(s,a)−Vπ(s))\pi(a \mid s) Q^\pi(s, a) - \pi(a \mid s) \sum_{a'} \pi(a' \mid s) Q^\pi(s, a') = \pi(a \mid s)\big(Q^\pi(s, a) - V^\pi(s)\big). ■\blacksquare

    Read the three factors: how often (and how early) we visit ss; how likely aa is now; how much better aa is than the average action in ss. Two consequences. The gradient of row ss adds up to 0 (the advantages, weighted by π\pi, add up to 0). And when π(a∣s)\pi(a \mid s) is almost 0, the gradient for a good action aa is almost 0 too: a softmax policy that is nearly deterministic in the wrong direction escapes very slowly (Mei et al., 2020). The notebook checks this formula against finite differences.

    An entropy bonus #

    Policy gradients can make the policy deterministic too early, before it has explored. A common fix adds the entropy H(π(⋅∣s))=−∑aπ(a∣s)log⁡π(a∣s)\mathcal H(\pi(\cdot \mid s)) = -\sum_a \pi(a \mid s) \log \pi(a \mid s) (information theory 01) of the visited states to the objective, with a small weight cec_e. For a softmax, ∂H/∂θa=−πa(log⁡πa+H)\partial \mathcal H / \partial \theta_a = -\pi_a(\log \pi_a + \mathcal H): it raises the logits of rare actions and lowers those of frequent ones. A2C uses this bonus, and SAC makes entropy part of the objective itself (lesson 08).

    Why the best policy can be stochastic: the short corridor #

    In an MDP where the agent sees the state, some optimal policy is deterministic (lesson 01). With function approximation the agent may not be able to tell states apart, and then this is no longer true. The short corridor (Sutton and Barto, Example 13.1) shows it.

    • Three cells S, X, Y and a goal G on the right; the reward is −1-1 per step, γ=1\gamma = 1.
    • In S and Y, "right" moves right and "left" moves left (left in S stays in S).
    • In X the actions are switched: "right" moves to S and "left" moves to Y.
    • All three cells have the same features, so the policy is the same in every cell: right with probability pp.

    "Always right" goes S → X → S → … and never ends. "Always left" stays in S forever. Both have value −∞-\infty. A stochastic policy reaches the goal. Write the Bellman equations for the three cells (lesson 01):

    VS=−1+pVX+(1−p)VS,VX=−1+pVS+(1−p)VY,VY=−1+(1−p)VX.V_S = -1 + p V_X + (1-p) V_S, \qquad V_X = -1 + p V_S + (1-p) V_Y, \qquad V_Y = -1 + (1-p) V_X .
    1. The first gives VS=VX−1/pV_S = V_X - 1/p. Put it into the second: (1−p)VX=−2+(1−p)VY(1-p) V_X = -2 + (1-p) V_Y, so VX=VY−2/(1−p)V_X = V_Y - 2/(1-p).
    2. Put that into the third: VY=−1+(1−p)VY−2V_Y = -1 + (1-p) V_Y - 2, so pVY=−3p V_Y = -3 and VY=−3/pV_Y = -3/p.
    3. Back-substitute: VX=−3/p−2/(1−p)V_X = -3/p - 2/(1-p) and
    J(p)=VS=−4p−21−p=2p−4p(1−p).J(p) = V_S = -\frac{4}{p} - \frac{2}{1-p} = \frac{2p - 4}{p(1 - p)} .
    1. Set J′(p)=0J'(p) = 0: 2p(1−p)−(2p−4)(1−2p)=02p(1-p) - (2p - 4)(1 - 2p) = 0 simplifies to p2−4p+2=0p^2 - 4p + 2 = 0, so p∗=2−2≈0.586p^* = 2 - \sqrt 2 \approx 0.586 (the other root is larger than 1). The value is J(p∗)=−(6+42)≈−11.66J(p^*) = -(6 + 4\sqrt 2) \approx -11.66.

    A greedy method over action values cannot represent this policy, but a policy-gradient method finds it.

    Interactive figure: loading…

    Predict the best pp, then press "Run 100 episodes" a few times. The cells show the corridor; X has switched actions. The first chart is J(p)J(p); the aqua line marks p∗≈0.586p^* \approx 0.586. Each dot is the current policy of one REINFORCE run, and the second chart shows pp over episodes: orange runs use no baseline, blue runs use a learned constant baseline. All runs start at p=0.1p = 0.1. Raise the step size to see the runs without a baseline become unstable first.

    Answers to section 1. (1) No. A constant is a state-independent baseline (with b=−100b = -100), so its term has mean 0. The variance changes: here it grows, because every score is multiplied by a larger number. (2) No. The transition terms vanish from ∇log⁡pθ(τ)\nabla \log p_\theta(\tau) (step 3). We need only the sampled rewards and the scores of the sampled actions. (3) No. Both deterministic policies never reach the goal; the best policy goes right with probability 2−2≈0.5862 - \sqrt 2 \approx 0.586.

    4. Worked example #

    One step, three actions. θ=(0,0,0)\theta = (0, 0, 0), so π=(1/3,1/3,1/3)\pi = (1/3, 1/3, 1/3); the rewards are r=(1,0,2)r = (1, 0, 2).

    Step 1: the objective and the exact gradient. J=13(1+0+2)=1J = \frac13(1 + 0 + 2) = 1. From the corollary with one state (d=1d = 1, A=r−JA = r - J): ∂J/∂θa=πa(ra−J)\partial J / \partial \theta_a = \pi_a (r_a - J), so

    ∇J=13 (1−1,  0−1,  2−1)=(0,  −13,  13).\nabla J = \tfrac13\,(1 - 1,\; 0 - 1,\; 2 - 1) = \big(0,\; -\tfrac13,\; \tfrac13\big).

    Step 2: the REINFORCE samples without a baseline. The sample for action aa is ra(ea−π)r_a (e_a - \pi), drawn with probability 13\frac13:

    action ea−πe_a - \pi rar_a sample gag_a ∥ga∥2\|g_a\|^2
    1 (23,−13,−13)(\frac23, -\frac13, -\frac13) 1 (23,−13,−13)(\frac23, -\frac13, -\frac13) 69\frac69
    2 (−13,23,−13)(-\frac13, \frac23, -\frac13) 0 (0,0,0)(0, 0, 0) 00
    3 (−13,−13,23)(-\frac13, -\frac13, \frac23) 2 (−23,−23,43)(-\frac23, -\frac23, \frac43) 249\frac{24}{9}

    Mean: 13[(23,−13,−13)+(0,0,0)+(−23,−23,43)]=13(0,−1,1)=(0,−13,13)\frac13\big[(\frac23, -\frac13, -\frac13) + (0, 0, 0) + (-\frac23, -\frac23, \frac43)\big] = \frac13 (0, -1, 1) = (0, -\frac13, \frac13) ✓. The total variance (the sum of the variances of the three entries) is E∥g∥2−∥∇J∥2=13⋅309−29=109−29=89\mathbb E\|g\|^2 - \|\nabla J\|^2 = \frac13 \cdot \frac{30}{9} - \frac29 = \frac{10}{9} - \frac29 = \frac89.

    Step 3: with the baseline b=J=1b = J = 1. The samples become (ra−1)(ea−π)(r_a - 1)(e_a - \pi):

    action ra−1r_a - 1 sample gag_a ∥ga∥2\|g_a\|^2
    1 0 (0,0,0)(0, 0, 0) 0
    2 −1-1 (13,−23,13)(\frac13, -\frac23, \frac13) 69\frac69
    3 1 (−13,−13,23)(-\frac13, -\frac13, \frac23) 69\frac69

    Mean: 13(0,−1,1)\frac13 (0, -1, 1), the same ✓. Total variance: 13⋅129−29=49−29=29\frac13 \cdot \frac{12}{9} - \frac29 = \frac49 - \frac29 = \frac29. The baseline removed 75%75\% of the variance. Here every action has ∥ea−π∥2=23\|e_a - \pi\|^2 = \frac23, so the variance-optimal constant b∗b^* of the deeper box equals J=1J = 1.

    Step 4: one gradient step. With η=1\eta = 1, θ←(0,−13,13)\theta \leftarrow (0, -\frac13, \frac13), so π≈(0.321,0.230,0.448)\pi \approx (0.321, 0.230, 0.448) and J≈0.321+2⋅0.448=1.218J \approx 0.321 + 2 \cdot 0.448 = 1.218. The best action (reward 2) gained probability, and the worst lost it.

    The short corridor. From section 3, J(0.5)=1−40.25=−12J(0.5) = \frac{1 - 4}{0.25} = -12, J(0.1)=−3.80.09≈−42.2J(0.1) = \frac{-3.8}{0.09} \approx -42.2, and the best value is J(2−2)≈−11.66J(2 - \sqrt 2) \approx -11.66. A run that starts at p=0.1p = 0.1 must climb a steep slope first; near p∗p^* the curve is flat, so the noise of the estimates matters most there.

    5. In code #

    NumPy checks the one-step example: the exact gradient against finite differences, and the mean and variance of the REINFORCE samples with and without a baseline.

    import numpy as np
    
    def softmax(z):
        e = np.exp(z - z.max())
        return e / e.sum()
    
    r = np.array([1.0, 0.0, 2.0])
    theta = np.zeros(3)
    pi = softmax(theta)
    J = pi @ r
    grad = pi * (r - J)                       # exact gradient of J = sum_a pi_a r_a
    print(grad.round(4))                      # [ 0.     -0.3333  0.3333]
    
    # check with central finite differences
    fd = np.array([(softmax(theta + 1e-6 * e) @ r - softmax(theta - 1e-6 * e) @ r) / 2e-6
                   for e in np.eye(3)])
    print(np.allclose(fd, grad))              # True
    
    # REINFORCE samples g_a = (r_a - b)(e_a - pi): exact mean and total variance
    for b in (0.0, 1.0):
        g = np.array([(r[a] - b) * (np.eye(3)[a] - pi) for a in range(3)])
        mean = pi @ g
        var = pi @ (g**2).sum(axis=1) - mean @ mean
        print(b, mean.round(4), round(var, 4))
    # 0.0 [ 0.     -0.3333  0.3333] 0.8889
    # 1.0 [ 0.     -0.3333  0.3333] 0.2222
    
    # short corridor: J(p) has its maximum at p* = 2 - sqrt(2)
    p = np.linspace(0.01, 0.99, 9801)
    J_p = (2 * p - 4) / (p * (1 - p))
    print(p[J_p.argmax()].round(4), J_p.max().round(2))   # 0.5858 -11.66
    

    In PyTorch the same REINFORCE loss is one line: loss = -(gamma_t * (G - b).detach() * dist.log_prob(actions)).sum(), where dist is a Categorical(logits=...) or Normal(mu, sigma) distribution.

    6. Where it shows up #

    • Language models. A language model is a softmax policy over tokens. RLHF fine-tunes it with PPO (a policy gradient with a learned critic and a trust region); RLOO and GRPO use REINFORCE with a baseline built from other samples for the same prompt (lesson 09).
    • Robotics and control. Gaussian policies over joint torques, trained with PPO or SAC (lesson 08) in simulators such as MuJoCo.
    • Games. AlphaGo's policy network was improved by self-play with a policy gradient before it was used in tree search (lesson 10).
    • Non-differentiable objectives. Whenever a sampled discrete choice is scored by a black box: neural architecture search (a controller samples architectures, the reward is validation accuracy), caption and translation models trained on BLEU or CIDEr (self-critical training uses the greedy output's score as the baseline).
    • ML for science. Molecule generators that sample a molecule token by token and are fine-tuned with RL toward a property predictor (for example REINVENT, Olivecrona et al., 2017), and chip floor-planning with a policy network trained by PPO (Mirhoseini et al., 2021).

    7. Common mistakes #

    • Wrong sign. Optimizers minimize. The loss is −∑t(Gt−b)log⁡πθ(at∣st)-\sum_t (G_t - b)\log \pi_\theta(a_t \mid s_t); without the minus sign you make good actions less likely.
    • Gradient through the weight. Gt−b(st)G_t - b(s_t) is a number in the policy loss. If bb comes from a network, detach it, or the policy loss also trains the baseline in a wrong way.
    • Action-dependent baseline. b(s,a)b(s, a) adds bias. Only functions of the state (or constants) are safe.
    • Using the full return for every step. It is unbiased, but rewards before tt only add noise. Use the reward-to-go.
    • The log-probability of the wrong action. The score must be of the action that was actually sampled and executed, from the policy that sampled it. Recomputing it after the update, or with a different policy, is a different estimator (lesson 09 handles the ratio πθ/πold\pi_\theta / \pi_{\text{old}}).
    • Reward timing. Here rtr_t follows (st,at)(s_t, a_t). With Sutton and Barto's Rt+1R_{t+1}, the reward-to-go is Gt=Rt+1+γRt+2+…G_t = R_{t+1} + \gamma R_{t+2} + \dots; mixing the two conventions shifts every return by one step.
    • "A baseline changes the result." It changes only the variance. If an algorithm improves when you add a baseline, it is because the updates are less noisy, not because the target moved.

    8. Check yourself #

    1. Why do the transition probabilities not appear in the policy gradient?
      Answerlog⁡pθ(τ)\log p_\theta(\tau) is a sum of log⁡p0(s0)\log p_0(s_0), the log-policy terms and the log-transition terms. Only the log-policy terms depend on θ\theta, so the gradient of the other terms is 0.
    2. Prove that a state-dependent baseline adds no bias.
      AnswerCondition on sts_t. Then Eat[∇log⁡π(at∣st) b(st)]=b(st)∑aπ(a∣st)∇log⁡π(a∣st)=b(st)∇∑aπ(a∣st)=b(st)∇1=0\mathbb E_{a_t}[\nabla \log \pi(a_t \mid s_t)\, b(s_t)] = b(s_t) \sum_a \pi(a \mid s_t)\nabla \log \pi(a \mid s_t) = b(s_t)\nabla \sum_a \pi(a \mid s_t) = b(s_t) \nabla 1 = 0. The tower rule gives 0 for the unconditional expectation too.
    3. A softmax policy over 2 actions has logits (0,ln⁡3)(0, \ln 3). Give π\pi and the score of action 1.
      Answerπ=(1,3)/4=(0.25,0.75)\pi = (1, 3)/4 = (0.25, 0.75). The score of action 1 is e1−π=(0.75,−0.75)e_1 - \pi = (0.75, -0.75).
    4. Give ∂J/∂θ(s,a)\partial J / \partial \theta(s, a) for a tabular softmax policy and explain each factor.
      Answerdπ(s) π(a∣s) Aπ(s,a)d^\pi(s)\,\pi(a \mid s)\,A^\pi(s, a): how much (discounted) time the policy spends in ss, how likely aa is there, and how much better aa is than the average action in ss.
    5. Why can a stochastic policy beat every deterministic policy in the short corridor, although lesson 01 says that an optimal deterministic policy always exists?
      AnswerLesson 01 assumes that the policy can depend on the true state. In the corridor all cells look the same to the agent, so the policy must use the same action probabilities in every cell. Among such policies, randomness is the only way to sometimes go right and sometimes go left. The best one has p=2−2p = 2 - \sqrt 2.
    6. A batch of returns is (10,12,8,10)(10, 12, 8, 10). Which constant baseline would you subtract, and why is it safe?
      AnswerAbout their mean, 10 (a running average or a learned V(s)V(s) in practice). A constant does not depend on the action, so its term has mean 0; it removes the large common part of the returns, so the weights become (0,2,−2,0)(0, 2, -2, 0) and the variance falls. (Using the mean of the same batch adds a tiny bias; leave-one-out means avoid it, see lesson 09.)
    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. What is the log-derivative trick?

    2. State the policy gradient theorem (expectation form).

    3. Why does the policy gradient need no model of the transitions?

    4. Write the REINFORCE estimate from one episode, with a baseline.

    5. Why does a baseline b(s)b(s) add no bias?

    6. What is the score ∇θlog⁡π(a)\nabla_\theta \log \pi(a) of a softmax policy?

    7. What is the score of a Gaussian policy N(μ,σ2)N(\mu, \sigma^2) with respect to μ\mu?

    8. Give the exact gradient of a tabular softmax policy.

    9. Define the advantage, and give its mean under the policy.

    10. Three actions, uniform policy, rewards (1,0,2)(1, 0, 2). Total variance of the REINFORCE sample with b=0b = 0 and with b=1b = 1?

    Open the review →

    9. Interview angle #

    • "Derive the policy gradient." — Likelihood ratio on trajectories; the dynamics drop out of ∇log⁡pθ(τ)\nabla \log p_\theta(\tau); causality gives the reward-to-go; conditioning gives QπQ^\pi.
    • "Why subtract a baseline? Can it depend on the action?" — Variance. It is unbiased because the score has mean 0 in every state. An action-dependent baseline is biased unless you add a correction term.
    • "Why use policy gradients instead of Q-learning?" — Continuous or huge action spaces, stochastic policies (partial observability, games), and smooth changes of the policy. The cost: high variance, on-policy data (low sample efficiency), and only a local optimum.
    • "What does REINFORCE do in a language model?" — Sample a response, score it, and raise the log-probability of its tokens in proportion to (score − baseline).
    • "Is the usual discounted policy gradient really a gradient?" — Without the γt\gamma^t factor, no (Nota and Thomas, 2020); it still works well in practice.

    10. Practice #

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

    1. softmax_policy and score_function for a tabular softmax policy, checked with finite differences.
    2. exact_values, discounted_visitation and exact_policy_gradient on a small 3-state MDP; check dπ π Aπd^\pi\, \pi\, A^\pi against finite differences of JJ.
    3. reinforce_estimates: one estimate per sampled episode; the mean matches the exact gradient, and the baseline b=Vπb = V^\pi cuts the variance.
    4. REINFORCE on the short corridor: learn pp and compare it with 2−22 - \sqrt 2.
    5. A Gaussian policy on a one-dimensional continuous bandit: learn the mean with the score (a−μ)/σ2(a - \mu)/\sigma^2.

    11. Watch and read #

    A clear derivation of the policy gradient theorem and REINFORCE, with good pictures.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The intuition first: why policy gradients, what the score does, and why the estimates are noisy.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The likelihood-ratio derivation, baselines and the step from REINFORCE to actor-critic.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Softmax and Gaussian policies, the policy gradient theorem, REINFORCE and actor-critic.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play