02 · Policy Gradients

What you're learning

How to differentiate an expectation you can only sample from, and how that single trick — the score function estimator — turns “maximize expected return” into a gradient you can actually compute. By the end you should be able to derive the Policy Gradient Theorem from scratch, explain exactly why a baseline is unbiased, and see why every modern RLHF/RLVR method is a REINFORCE estimator in disguise.

This lesson assumes lesson 01 — 01-mdps-and-the-rl-objective — is understood: MDPs, the trajectory distribution, the RL objective , and the value/advantage functions .


1. Learning map

graph TD
    A["RL objective<br/>J(θ)=E_τ[R(τ)]<br/>(lesson 01)"] --> B["Why not value-based?<br/>argmax over actions"]
    B --> C["Directly optimize π_θ<br/>→ need ∇_θ J"]
    C --> D["Score-function trick<br/>∇E[f]=E[f ∇log p]"]
    D --> E["Policy Gradient Theorem<br/>Σ_t ∇log π · Ψ_t"]
    E --> F["REINFORCE<br/>(MC policy gradient)"]
    F --> G["Variance problem"]
    G --> H1["Reward-to-go<br/>(causality)"]
    G --> H2["Baselines b(s)<br/>(unbiased)"]
    H2 --> I["V(s) as baseline<br/>→ Advantage Ψ_t=A(s,a)"]
    H1 --> I
    I --> J["LLM connection<br/>RLHF / RLVR / GRPO"]

    style E fill:#4a4,color:#fff
    style D fill:#44a,color:#fff
    style J fill:#a44,color:#fff

The spine: we want , we can’t differentiate through sampling naively, the score-function trick rescues us, the Policy Gradient Theorem specializes it to MDPs, REINFORCE turns it into an algorithm, and then the entire back half is fighting variance.


2. Why policy gradients at all?

In lesson 01 the objective was

where the trajectory distribution factorizes as

Value-based methods (Q-learning1, DQN2) never parameterize a policy directly. They learn and induce a policy by . That is the problem.

Where value-based methods hit a wall

The greedy requires enumerating actions. This is fine for Atari (18 buttons) but breaks for:

  • Continuous actions (robot torques): the is itself an optimization problem at every step.
  • Combinatorially large discrete spaces — e.g. a language model choosing the next token over a vocabulary of 3, or worse, choosing a whole sequence. You cannot enumerate sequences.

Policy gradients sidestep the entirely: parameterize (e.g. a softmax over logits — exactly what an LLM head is) and do gradient ascent on directly.

Key insight

Policy-based methods optimize the thing you actually care about — the policy — rather than a proxy (values) from which a policy must be extracted. They naturally produce stochastic policies, handle continuous and huge discrete action spaces, and give smooth policy improvement. The price you pay is variance, which is what the rest of this lesson is about.

The catch: is an expectation over trajectories that themselves depend on . You can’t just push inside a sampling operation. That’s the wall we break next.


3. The score-function / log-derivative trick

This is the whole game. Suppose we want the gradient of an expectation of some function under a distribution that depends on the parameters:

(We assume does not depend on ; regularity conditions let us swap and .) The integrand is not an expectation — we can’t sample it. The trick is the identity

which just rearranges . Substituting:

We turned a gradient-of-an-expectation into an expectation of a gradient — which we can estimate by Monte Carlo: sample , average .

The term is called the score function. This estimator is also called the likelihood-ratio estimator.4

Why this is remarkable

We can compute the gradient of without differentiating at all can be non-differentiable, discontinuous, even a black-box reward from a human or a unit-test harness. All the gradient flows through . This is exactly why policy gradients work with reward signals that have no gradient (a reward model, a pass/fail verifier).

Contrast with the reparameterization trick

The other way to differentiate an expectation is the pathwise / reparameterization estimator (, push through ), used in VAEs5. That requires to be differentiable and to be reparameterizable. The score-function trick needs neither — it only needs to evaluate and to have a differentiable density. That generality is why RL uses it, and the cost is higher variance.


4. The Policy Gradient Theorem

Now specialize , , . Apply the trick:

The magic happens when we expand using the factorization from §2:

Take . The initial-state term and every transition term are independent of — they’re properties of the environment. They vanish under the gradient:

The dynamics disappear

This is the single most important consequence. The unknown, possibly non-differentiable environment transition drops out of the gradient. We never need a model of the world — this is why policy gradients are model-free. All that survives is the score of our own policy.

Substituting back gives the raw form of the Policy Gradient Theorem6:

The general form and the choice of

The theorem is usually written more flexibly. The gradient can be expressed as

where is a weight on the score of action — telling the update how much to push up (or down) the log-probability of that action. Several choices of all yield the same expected gradient but wildly different variance.7 In roughly increasing order of quality:

NameComment
total returnvalid but highest variance; every action credited with the whole trajectory
reward-to-godrops rewards before (they can’t be caused by )
baselined reward-to-gosubtract a state-dependent baseline (§6)
action-valueexpected reward-to-go
advantagelowest variance; “how much better than average is ?”

The one-sentence intuition

Every choice of says the same thing: increase the log-probability of actions that led to better-than-expected outcomes, decrease it for worse-than-expected ones. The differences are entirely about how tightly you estimate “better than expected” — which controls variance, not bias.

The last row is the destination of this lesson: the advantage is the ideal weight. Lesson 03 (03-actor-critic-and-gae) is about how to estimate it well.


5. REINFORCE — the Monte Carlo policy gradient

Williams (1992) gives the simplest concrete algorithm.4 Take reward-to-go, estimate the expectation with sampled trajectories:

then ascend: .

graph LR
    A["Run policy π_θ<br/>collect N trajectories"] --> B["Compute returns /<br/>rewards-to-go G_t"]
    B --> C["Ĝ = mean of<br/>Σ_t ∇log π(a_t|s_t)·G_t"]
    C --> D["θ ← θ + α·Ĝ"]
    D --> A
    style C fill:#4a4,color:#fff

The full loop:

  1. Sample trajectories by running the current in the environment.
  2. For each, compute rewards-to-go .
  3. Form the estimator above (in practice: build the surrogate loss and let autodiff produce ).
  4. Take a gradient-ascent step; repeat.

REINFORCE is on-policy and single-use

Step 1 must use the current . Once you update , the trajectories are stale — they were drawn from the old policy, so the expectation they estimate no longer matches. You must throw them away and resample. This is the root of REINFORCE’s sample inefficiency, and the reason importance-sampling / trust-region methods (PPO, later lessons) exist: to squeeze multiple update steps out of one batch of data.

The surrogate-loss view

You never hand-code . You minimize with treated as a constant (detached / stop_gradient). This is weighted maximum likelihood: it’s ordinary supervised cross-entropy on the sampled actions, but each sample is weighted by how good its outcome was. Keep this framing — it’s exactly how RLHF code looks.


6. The variance problem and baselines

REINFORCE is unbiased but notoriously high-variance. Returns can be large in magnitude and the same magnitude gets multiplied onto the score of every action; a single lucky/unlucky trajectory swings the estimate hard. High variance means noisy gradients, tiny usable step sizes, and slow learning.

Baselines: subtract a reference without adding bias

The central trick: subtract a baseline — any function of the state (not of the action) — from the weight:

This is only useful if it doesn’t change the gradient we’re estimating. It doesn’t — and here’s the proof, which is worth internalizing because the same identity underlies causality (§4) and GRPO (§8).

The workhorse identity: expected score is zero

For any distribution ,

Proof.

The score of any properly normalized density has mean zero, because the density integrates to a constant.

Now the baseline term vanishes in expectation. Condition on and pull out (it’s constant w.r.t. the action):

So subtracting any leaves unbiased. The only thing it changes is variance.

The baseline must not depend on the action

If depended on , the pull-out step fails — can’t come outside the expectation over , and in general. You’d bias the gradient. Baselines are strictly state-dependent. (This is also why the advantage keeps the action-dependent as the weight and uses the state-only as the baseline — not the other way around.)

Why it reduces variance — and the value function as the near-optimal baseline

Subtracting a constant doesn’t change the mean but does change the second moment. The variance of the per-term estimator is governed by . Choosing centers the weight around zero, shrinking and hence the variance.

The natural choice is the state-value function:

With and , the weight becomes exactly the advantage:

Advantage is the punchline

answers: “was better or worse than the policy’s average action in state ?” Its sign is the natural learning signal — push up above-average actions, push down below-average ones — and centering at makes the magnitude small, minimizing variance. Using as the baseline isn’t provably variance-optimal (the true minimum-variance baseline is a score-weighted version of ), but it’s cheap, interpretable, and nearly optimal in practice. This is why the next lesson is “actor-critic”: you learn so you can form .


7. Practical issues, at a glance

Even with baselines, vanilla policy gradients carry three chronic problems — keep these in mind, they motivate everything downstream.

  • High variance. The score-function estimator is inherently noisier than pathwise gradients. Baselines, reward-to-go, and advantage estimation (GAE, lesson 03) all fight this.
  • Sample inefficiency. On-policy: data is discarded after one update (§5). PPO’s clipped importance ratio lets you reuse a batch for several epochs — the practical fix.8
  • Credit assignment. A single scalar return must be apportioned across a long trajectory. Reward-to-go and -discounting help, but with sparse, delayed rewards (win/loss at the end of a game; a correct final answer after 500 tokens) the signal per action is faint. This is the hard problem, and it is exactly the LLM setting.

Discount factor is doing double duty

is often introduced as “we care less about the future,” but in policy gradients it also acts as a variance-reduction / credit-horizon knob: it down-weights far-future rewards that are only weakly caused by the current action. Lowering reduces variance but adds bias. This bias–variance dial is formalized by GAE’s in lesson 03.


8. The LLM connection — RLHF, RLVR, and GRPO

This is where the whole apparatus becomes the backbone of post-training.9 Map the RL vocabulary onto language modeling:

RL conceptLLM instantiation
policy the language model (its softmax over the vocabulary)
state the prompt + tokens generated so far (the context)
action the next token
the token log-probability
trajectory prompt + full generated response
reward scalar from a reward model (RLHF) or a verifier (RLVR)

The autoregressive factorization is literally the trajectory-log-prob sum from §4. So the policy gradient for an LLM is

This is just REINFORCE on token sequences. Generating a completion is rolling out a trajectory; the token head is the action distribution; huge vocabulary is exactly the “large action space” that killed value-based in §2 — which is why policy-gradient methods, not Q-learning, dominate LLM post-training.

Sequence reward → per-token credit

In RLHF/RLVR the reward is usually sequence-level: one scalar for the whole response (e.g. reward-model score, or if the answer passes the verifier else ). Through the return, that single scalar becomes the weight on every token’s score. With no intermediate reward, the reward-to-go is the same terminal scalar for all — so the model uplifts (or suppresses) the log-prob of all tokens in a good (bad) response uniformly. That’s the credit-assignment problem of §7 in its starkest form: the model must sort out which tokens actually mattered purely from statistics across many samples.

Common misconception

“RLHF uses PPO, which is totally different from REINFORCE.” No — PPO is a variance-reduced, sample-reused, trust-region wrapper around the same policy-gradient estimator. Strip away the clipped importance ratio and the learned value baseline, and PPO’s core is the advantage-weighted score sum you derived in §4–§6. Recent methods (RLOO10, GRPO11) go the other direction — back toward plain REINFORCE — arguing the PPO machinery is often unnecessary for LLMs.

GRPO teaser (lesson 09). A learned value baseline is expensive for LLMs (a second large network, and per-token value targets are hard). GRPO (Group Relative Policy Optimization) drops the learned critic entirely.11 For a prompt , it samples a group of completions , scores each with reward , and uses the group statistics as the baseline:

The group mean is a baseline in the exact sense of §6 — a quantity that depends on the state (the prompt) but not on the specific sampled action — so it’s unbiased and needs no critic network. This is the per-prompt-constant baseline from the §6 quiz, made concrete at scale. We derive GRPO fully in lesson 09.


9. Practice problems


10. Reading order

Work through these in order:

  1. Foundational text: Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.), Chapter 13 — Policy Gradient Methods. The canonical derivation of the Policy Gradient Theorem and REINFORCE with baseline. Read §13.1–13.4 first.
  2. Best intuition-builder: OpenAI Spinning Up — “Intro to Policy Optimization” (spinningup.openai.com). Rederives the gradient, the reward-to-go trick, and baselines with runnable code (vpg). The clearest single resource for the estimator-implementation mapping in §5.
  3. Primary source: Williams (1992), “Simple statistical gradient-following algorithms for connectionist reinforcement learning” — the original REINFORCE paper. Read for the score-function estimator and the baseline discussion in its original framing.
  4. Forward pointer (read after lesson 03): Schulman et al. (2015), “High-Dimensional Continuous Control Using Generalized Advantage Estimation” (arXiv:1506.02438) — GAE, the bias–variance-controlled advantage estimator that makes the choice practical. This is the bridge to actor-critic.

11. What’s next

Two threads, in order:

  1. 03-actor-critic-and-gae — you now know the advantage is the ideal weight , but you can’t compute it exactly. Actor-critic learns a value network as the baseline; GAE () tunes the bias–variance tradeoff in estimating . This is the direct sequel.
  2. Back-reference: 01-mdps-and-the-rl-objective — if the trajectory factorization, , or the objective felt shaky in §2–§4, revisit it; everything here rests on it.

Further out: PPO (trust-region / clipped surrogate for sample reuse) and lesson 09 on GRPO (group-relative baseline, critic-free RL for LLMs) both build directly on the estimator derived here.


References


Topic hub: rl-for-llms | Filed: 2026-09-02

Footnotes

  1. Watkins, C. J. C. H., & Dayan, P. (1992). “Q-learning.” Machine Learning, 8(3–4), 279–292. https://doi.org/10.1007/BF00992698

  2. Mnih, V., Kavukcuoglu, K., Silver, D., Rusu, A. A., Veness, J., Bellemare, M. G., et al. (2015). “Human-Level Control Through Deep Reinforcement Learning” (DQN). Nature, 518, 529–533. https://doi.org/10.1038/nature14236

  3. Grattafiori, A., et al. (Meta AI) (2024). “The Llama 3 Herd of Models.” arXiv:2407.21783. Llama 3 uses a tokenizer with a vocabulary of 128,256 tokens. https://arxiv.org/abs/2407.21783

  4. Williams, R. J. (1992). “Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning.” Machine Learning, 8(3–4), 229–256. Introduces REINFORCE and the score-function / likelihood-ratio estimator with baselines. https://doi.org/10.1007/BF00992696 2

  5. Kingma, D. P., & Welling, M. (2013). “Auto-Encoding Variational Bayes.” arXiv:1312.6114. Introduces the reparameterization (pathwise) gradient estimator used in VAEs. https://arxiv.org/abs/1312.6114

  6. Sutton, R. S., McAllester, D., Singh, S., & Mansour, Y. (2000). “Policy Gradient Methods for Reinforcement Learning with Function Approximation.” Advances in Neural Information Processing Systems 12 (NIPS 1999), 1057–1063. The canonical statement and proof of the Policy Gradient Theorem. https://papers.nips.cc/paper/1713-policy-gradient-methods-for-reinforcement-learning-with-function-approximation

  7. Schulman, J., Moritz, P., Levine, S., Jordan, M., & Abbeel, P. (2015). “High-Dimensional Continuous Control Using Generalized Advantage Estimation” (GAE). arXiv:1506.02438. Frames the choice of weight (return, reward-to-go, , advantage) and the bias–variance tradeoff. https://arxiv.org/abs/1506.02438

  8. Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). “Proximal Policy Optimization Algorithms.” arXiv:1707.06347. Clipped surrogate objective enabling multiple update epochs per batch. https://arxiv.org/abs/1707.06347

  9. Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C. L., Mishkin, P., Zhang, C., Agarwal, S., Slama, K., Ray, A., et al. (2022). “Training Language Models to Follow Instructions with Human Feedback” (InstructGPT). arXiv:2203.02155. The canonical RLHF-with-PPO post-training recipe. https://arxiv.org/abs/2203.02155

  10. Ahmadian, A., Cremer, C., Gallé, M., Fadaee, M., Kreutzer, J., Pietquin, O., Üstün, A., & Hooker, S. (2024). “Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs” (RLOO). arXiv:2402.14740. Argues PPO’s machinery is often unnecessary for RLHF and that REINFORCE/RLOO variants match or exceed it. https://arxiv.org/abs/2402.14740

  11. Shao, Z., Wang, P., Zhu, Q., Xu, R., Song, J., Bi, X., Zhang, H., Zhang, M., Li, Y. K., Wu, Y., & Guo, D. (2024). “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.” arXiv:2402.03300. Introduces Group Relative Policy Optimization (GRPO), which replaces the learned critic with a group-relative (per-prompt) baseline. https://arxiv.org/abs/2402.03300 2