Skip to content
Reinforcement learning Advanced 28 min read

Policy gradients and REINFORCE

Instead of learning values and acting greedily, parameterise the policy and climb the gradient of expected return. One identity — the log-derivative trick — turns that gradient into an average you can sample, without differentiating through the environment. REINFORCE is that estimator; almost everything since, from actor-critic to PPO to the RL that trains reasoning models, is a way to make it less noisy or to take bigger safe steps.

10,000 ft

Q-learning learns how good actions are and derives behaviour from a max. Policy-gradient methods learn the behaviour itself: a network \(\pi_\theta(a\mid s)\) whose parameters move in the direction that makes high-return trajectories more probable. That handles continuous actions (no max to compute), learns genuinely stochastic policies, changes behaviour smoothly, and works for any differentiable policy — including a language model, where an "action" is a token and an "episode" is a completion. The line runs from Williams' REINFORCE (1992) through the policy-gradient theorem (Sutton et al., 1999) and natural gradients (Kakade, 2001) to TRPO and PPO, RLHF, and the group-baseline methods (GRPO, RLOO) that trained the 2025-era reasoning models. If you understand this page, those are variations.

2,000 ft

  1. Parameterise the policy: logits → softmax for discrete actions; a Gaussian with a learned mean for continuous ones.
  2. Objective: \(J(\theta) = \mathbb E_{\tau\sim\pi_\theta}[R(\tau)]\), the expected return over trajectories the policy generates.
  3. Log-derivative trick: \(\nabla_\theta J = \mathbb E\big[R(\tau)\sum_t \nabla_\theta\log\pi_\theta(a_t\mid s_t)\big]\). The environment's dynamics drop out; you only differentiate your own log-probabilities.
  4. Reduce variance without bias: weight each step by the reward-to-go rather than the whole return, and subtract a baseline \(b(s_t)\), ideally the state value.
  5. Step: \(\theta \leftarrow \theta + \alpha\,\hat g\), then collect fresh data — the estimator is on-policy.

REINFORCE: sample, score, weight, step
REINFORCE: sample, score, weight, step. Policy π_θ(a | s), Roll out N episodes with the current policy, Reward-to-go G_t for every step, Subtract a baseline b(s_t), Score ∇_θ log π_θ(a_t | s_t), ĝ = mean over steps of (G_t − b) · score, θ ← θ + α ĝREINFORCE: sample, score, weight, step. Policy π_θ(a | s), Roll out N episodes with the current policy, Reward-to-go G_t for every step, Subtract a baseline b(s_t), Score ∇_θ log π_θ(a_t | s_t), ĝ = mean over steps of (G_t − b) · score, θ ← θ + α ĝ

Ground level

Parameterising a policy

A policy is a conditional distribution over actions. Two parameterisations cover nearly all practice.

Discrete actions: softmax over logits. A network outputs one logit \(z_a(s;\theta)\) per action and

\[ \pi_\theta(a\mid s) = \frac{e^{z_a(s;\theta)}}{\sum_{b} e^{z_b(s;\theta)}} . \]

This is exactly a classifier's output layer, and exactly a language model's next-token distribution.

Continuous actions: a Gaussian. A network outputs a mean \(\mu_\theta(s)\) (and often a log-standard-deviation, either state-dependent or a free parameter); the action is sampled as \(a = \mu_\theta(s) + \sigma\,\varepsilon\), \(\varepsilon\sim\mathcal N(0, I)\). For bounded actions, squash with \(\tanh\) and correct the log-probability for the change of variables.

The objective, and why its gradient looks impossible

Write a trajectory as \(\tau = (s_0, a_0, r_1, s_1, a_1, \dots)\). Its probability under the policy is

\[ p_\theta(\tau) = \rho_0(s_0)\prod_{t} \pi_\theta(a_t\mid s_t)\, p(s_{t+1}, r_{t+1}\mid s_t, a_t), \]

and the objective is \(J(\theta) = \mathbb E_{\tau\sim p_\theta}[R(\tau)]\) with \(R(\tau) = \sum_t \gamma^t r_{t+1}\). The parameters affect \(J\) only through which trajectories get sampled. You cannot backpropagate through the environment (the dynamics \(p\) are unknown and often not differentiable — a game emulator, a robot, a human rater, a unit-test runner), and \(R\) itself may be a step function. Yet the gradient exists.

The log-derivative trick

For any distribution \(p_\theta(x)\) and any function \(f(x)\) that does not depend on \(\theta\):

\[ \nabla_\theta\, \mathbb E_{x\sim p_\theta}[f(x)] = \sum_x f(x)\,\nabla_\theta p_\theta(x) = \sum_x f(x)\, p_\theta(x)\,\nabla_\theta \log p_\theta(x) = \mathbb E_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big], \]

using \(\nabla p = p\,\nabla\log p\). The gradient of an expectation has become the expectation of something you can compute for each sample. \(\nabla_\theta \log p_\theta(x)\) is called the score.

Apply it to trajectories. Taking the log of \(p_\theta(\tau)\) turns the product into a sum, and every term that does not involve \(\theta\) — the initial state distribution, the dynamics — has zero gradient:

\[ \nabla_\theta \log p_\theta(\tau) = \sum_t \nabla_\theta \log \pi_\theta(a_t\mid s_t). \]

So

\[ \nabla_\theta J(\theta) = \mathbb E_{\tau\sim\pi_\theta}\Big[R(\tau)\sum_t \nabla_\theta\log\pi_\theta(a_t\mid s_t)\Big]. \]

That is the whole idea. Sample trajectories with the current policy, and for each one push up the log-probability of every action it took, in proportion to how good the trajectory was. Bad trajectories (negative return) get pushed down.

Worked example: the exact gradient on a three-armed bandit

Three arms with rewards \(r = (1, 2, 3)\), softmax policy with logits \(\theta = (0,0,0)\), so \(\pi = (\tfrac13, \tfrac13, \tfrac13)\) and \(J = \pi\cdot r = 2\). For a softmax, \(\nabla_\theta \log \pi(a) = \mathbf e_a - \pi\) (one-hot minus the probabilities). Then \(\nabla J = \sum_a \pi_a r_a(\mathbf e_a - \pi)\), whose \(k\)-th component simplifies to \(\pi_k (r_k - J)\): here \(\tfrac13(1-2,\ 2-2,\ 3-2) = (-0.333,\ 0,\ 0.333)\). Arms better than average get their logits raised, worse ones lowered, the average one untouched. Estimating it from 100,000 single samples (Build it):

no baseline  : mean [-0.336  0.002  0.333]  per-sample std [0.719 0.983 1.187]
baseline = J : mean [-0.332 -0.001  0.333]  per-sample std [0.272 0.272 0.273]
exact        : [-0.333  0.     0.333]

Both estimators are unbiased. The second, which subtracts the baseline \(b = J\) from the reward, has up to 4.3 times smaller standard deviation per sample — that is, it needs up to 19 times fewer samples for the same precision.

The connection to supervised learning

Look at the per-sample loss you would hand to an autodiff library:

\[ \mathcal L(\theta) = -\frac1N\sum_{i}\sum_t \hat A_{i,t}\,\log\pi_\theta(a_{i,t}\mid s_{i,t}), \]

with \(\hat A\) the weight (return, reward-to-go, or advantage), treated as a constant. If every \(\hat A\) were 1, this would be the cross-entropy loss of behaviour cloning: maximum likelihood on the agent's own actions. A policy gradient is maximum likelihood on your own samples, weighted by how good they turned out. Positive weight: imitate yourself more. Negative weight: imitate yourself less. That one sentence is the bridge to instruction tuning (weights all 1, on someone else's samples) and to RL for language models (weights from a reward model or a verifier).

Credit assignment: reward-to-go

The basic estimator multiplies every action's score by the whole return, including rewards that arrived before the action was taken. An action cannot affect the past, so those terms contribute zero in expectation but plenty of noise. Dropping them gives the reward-to-go form:

\[ \nabla_\theta J = \mathbb E\Big[\sum_t \nabla_\theta\log\pi_\theta(a_t\mid s_t)\; G_t\Big], \qquad G_t = \sum_{k\ge t}\gamma^{k-t} r_{k+1}. \]

The maths proves the dropped terms have zero mean. This is REINFORCE in the form everyone uses (Williams named it as an acronym: REward Increment = Nonnegative Factor × Offset Reinforcement × Characteristic Eligibility — the "offset reinforcement" is the baseline below).

Baselines

Subtract from \(G_t\) any function \(b(s_t)\) of the state alone:

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

The gradient is unchanged, because \(\mathbb E_{a\sim\pi}[\nabla_\theta \log\pi_\theta(a\mid s)] = \nabla_\theta \sum_a \pi_\theta(a\mid s) = \nabla_\theta 1 = 0\). But the variance can fall enormously. Intuition: without a baseline, in a game where every return is between 90 and 100, every sampled action is pushed up, and the signal that distinguishes the 100s from the 90s is a small difference between large positive pushes. With \(b \approx 95\), good actions go up and bad ones go down.

The natural choice is the state value \(b(s) = V^\pi(s)\), so the weight becomes an estimate of the advantage \(A^\pi(s,a) = Q^\pi(s,a) - V^\pi(s)\): was this action better or worse than what I usually do here? Learning \(V\) with a second network — a critic — is the step to actor-critic methods. Not quite the variance-minimising choice, though: The maths derives the optimal baseline, and a question in Check yourself computes it for the bandit above.

Why a stochastic policy: the short corridor

Value-based methods derive a deterministic greedy policy (plus exploration noise). Sometimes the best policy is stochastic. Sutton and Barto's short corridor (Example 13.1): three non-terminal states in a row and a goal; reward \(-1\) per step; in the middle state the actions are swapped. The agent sees the same features in every state, so whatever it does, it does everywhere: its policy is a single probability \(p\) of pressing "right".

0-25-50-75-10000.250.50.751p = probability of "right" (same in every state)J(p)best stochastic policy: p = 0.586, J = -11.7ε-greedy right: J = -44ε-greedy left: J = -82
The short corridor's expected return as a function of the policy's single probability, solved exactly. The optimum is an interior, stochastic policy. An ε-greedy agent (ε = 0.1) can only sit at p = 0.05 or p = 0.95; a policy-gradient agent climbs the curve to the top.

The best policy presses right with probability \(p = 2 - \sqrt2 \approx 0.586\) and takes 11.66 steps on average. An ε-greedy policy with ε = 0.1 is stuck at \(p = 0.95\) (44.2 steps) or \(p = 0.05\) (82.1 steps). Policy-gradient REINFORCE, run from \(p = 0.18\) and averaged over 100 runs:

REINFORCE without baseline: mean J after 50 eps = -22.7, 200 eps = -19.3, 1000 eps = -13.4
REINFORCE with    baseline: mean J after 50 eps = -14.5, 200 eps = -11.9, 1000 eps = -11.8

With a learned state-value baseline, the same algorithm tolerates a step size 16 times larger and reaches the optimum in about 200 episodes; without it, 1,000 episodes are not enough. Partial observability (identical-looking states) and adversarial games (rock–paper–scissors) are the classic cases where only a stochastic policy is optimal.

How noisy is the estimator, really?

At \(p = 0.5\) the true gradient \(dJ/d\theta\) is exactly 2.000. Three single-episode estimators, 20,000 episodes each:

  total return x all scores  mean   1.607   std   42.49
  reward-to-go               mean   1.955   std   25.89
  reward-to-go - v(s)        mean   2.067   std   16.03

All three are unbiased (their standard errors are 0.30, 0.18 and 0.11, so every mean is within 1.3 standard errors of 2). But a single episode's estimate has standard deviation 8–21 times its mean. This is the central fact of policy-gradient RL: the signal is real and the noise is huge. A batch of \(N\) episodes divides the standard deviation by \(\sqrt N\); you need hundreds of episodes per step for a reliably signed gradient on even this toy, and every remedy you will meet — baselines, critics, GAE, large batches, many parallel actors — exists to fight this ratio.

The step-size problem, and natural gradients

Supervised learning forgives a bad step: the data stay the same and the next gradient corrects it. Policy gradients do not. A step that collapses the policy (say, to "always left") changes the data you collect next, and from a collapsed policy the gradient may carry almost no information about how to get back. Performance can fall off a cliff and never return.

The deeper issue is geometry. A step of size \(\alpha\) in parameter space can be a tiny or an enormous change in behaviour depending on the parameterisation: moving a logit from 0 to 1 changes the action probability by 0.23, but from 10 to 11 by almost nothing. Natural policy gradient (Kakade, 2001) measures step size by the change in the distribution, the KL divergence between old and new policy, whose local quadratic form is the Fisher information matrix \(F\). The steepest-ascent direction under that metric is

\[ \tilde\nabla J = F^{-1}\nabla_\theta J, \qquad F = \mathbb E\big[\nabla_\theta\log\pi_\theta(a\mid s)\,\nabla_\theta\log\pi_\theta(a\mid s)^\top\big]. \]

It is invariant to how you parameterise the policy. TRPO (Schulman et al., 2015) turned this into a constraint — maximise the improvement subject to average KL \(\le\delta\) — and PPO approximated the constraint with a clipped ratio that needs only first-order optimisation. Both are on the next page.

Continuous actions

For a Gaussian policy with mean \(\mu_\theta(s)\) and fixed standard deviation \(\sigma\),

\[ \nabla_\theta \log \pi_\theta(a\mid s) = \frac{a - \mu_\theta(s)}{\sigma^2}\,\nabla_\theta\mu_\theta(s). \]

Read it: if the sampled action was above the mean and the advantage was positive, move the mean up; if the advantage was negative, move it down. Example: \(\mu = 0\), \(\sigma = 1\), sampled \(a = 0.5\), advantage \(+2\): the update to the mean is \(\alpha \times 2 \times 0.5 = \alpha\). Exploration comes from \(\sigma\); learning \(\log\sigma\) too lets the policy decide how much to explore.

When you can differentiate the critic with respect to the action, a lower-variance alternative is the pathwise (reparameterisation) gradient: the deterministic policy gradient \(\nabla_\theta J = \mathbb E[\nabla_a Q(s,a)\rvert_{a=\mu_\theta(s)}\nabla_\theta\mu_\theta(s)]\) (Silver et al., 2014), the basis of DDPG and TD3. The score-function estimator needs only the reward; the pathwise one needs a differentiable model of it. That trade-off — generality against variance — recurs across machine learning, from VAEs to diffusion (Mohamed et al., 2020, survey both).

Policy gradients for language models

A language model is already a softmax policy: state = prompt plus tokens so far, action = next token. A completion \(y = (y_1,\dots,y_T)\) for prompt \(x\) is an episode, typically with a single reward \(r(x,y)\) at the end from a reward model or a verifier (does the answer match? do the tests pass?). REINFORCE reads:

\[ \nabla_\theta\, \mathbb E_{y\sim\pi_\theta(\cdot\mid x)}[r(x,y)] = \mathbb E\Big[\big(r(x,y) - b(x)\big)\sum_{t=1}^{T}\nabla_\theta\log\pi_\theta(y_t\mid x, y_{<t})\Big]. \]

What is a good baseline for a prompt? Sample \(k\) completions of the same prompt and use the others' mean: the leave-one-out baseline \(b_i = \frac1{k-1}\sum_{j\ne i} r_j\), which keeps the estimator unbiased because \(b_i\) does not depend on sample \(i\). Ahmadian et al. (2024) showed that this REINFORCE-leave-one-out (RLOO) matched or beat PPO for RLHF while dropping its value network, and GRPO (Shao et al., 2024), used to train DeepSeek-R1, uses the group mean and standard deviation in the same role. The full story — KL penalties, length bias, verifiable rewards — is on Offline RL and RL for language models.

The policy-gradient lineage: from REINFORCE to RL for language models
The policy-gradient lineage: from REINFORCE to RL for language models. REINFORCE 1992 score-function gradient, PG theorem 1999 gradient via Q^π, Baselines variance reduction, Actor-critic learned baseline/critic, Natural PG 2001 Fisher geometry, TRPO 2015 KL trust region, PPO 2017 clipped ratio, RLHF 2017–22 PPO on LMs, RLOO / GRPO 2024 group baselines, no critic, back to basicsThe policy-gradient lineage: from REINFORCE to RL for language models. REINFORCE 1992 score-function gradient, PG theorem 1999 gradient via Q^π, Baselines variance reduction, Actor-critic learned baseline/critic, Natural PG 2001 Fisher geometry, TRPO 2015 KL trust region, PPO 2017 clipped ratio, RLHF 2017–22 PPO on LMs, RLOO / GRPO 2024 group baselines, no critic, back to basics

History

Ronald Williams published REINFORCE in Machine Learning in 1992, framed for "connectionist" networks of stochastic units, including the baseline. In 1999 Sutton, McAllester, Singh and Mansour proved the policy-gradient theorem with function approximation, showing the gradient can be written with \(Q^\pi\) and needs no derivative of the state distribution, and gave the condition ("compatible features") under which an approximate critic leaves it unbiased. Kakade's natural gradient (2001) and Peters and Schaal's natural actor-critic (2008) brought information geometry; Schulman's TRPO and GAE (2015) and PPO (2017) made policy gradients work with deep networks. Andrej Karpathy's 2016 post Pong from Pixels taught a generation the method with 130 lines of NumPy. In 2017 Salimans et al. showed that evolution strategies, which perturb parameters instead of actions, were a competitive, embarrassingly parallel alternative — a reminder that the score-function trick can be applied in parameter space too. Since 2022 policy gradients have become the main way frontier language models are trained after pre-training.

First principles

Why not just differentiate the return? The return depends on \(\theta\) only through sampling, a discrete, non-differentiable operation, and through an environment you cannot differentiate. The score-function identity is the general escape: it needs only that you can evaluate \(\log\pi_\theta(a\mid s)\) and its gradient for actions you actually took. No model, no differentiable reward. That generality is exactly why it is noisy: it uses nothing but whether a sample was good.

Why the dynamics drop out. In \(\log p_\theta(\tau)\) the policy and the dynamics appear as separate factors, so they become separate sum terms, and the dynamics terms have no \(\theta\). This is the precise sense in which policy gradients are model-free. (It also means that the gradient only tells you how to change your choices; it cannot exploit knowledge of how the world would respond — which is what model-based methods add.)

Why it must be on-policy. The expectation is over trajectories from \(\pi_\theta\) itself. Data from an older policy \(\pi_{\text{old}}\) estimate a different expectation; correcting needs importance weights \(\prod_t \pi_\theta(a_t\mid s_t)/\pi_{\text{old}}(a_t\mid s_t)\), a product whose variance explodes with horizon. PPO reuses each batch for a few epochs by using only per-step ratios, and keeps them close to 1 by clipping — a controlled, slightly biased cheat.

Why a baseline cannot bias the gradient, and why an action-dependent one can. The score has zero mean under the policy at every state. Anything multiplied by it that is constant with respect to the sampled action therefore contributes zero in expectation. A baseline that depends on the action (say, \(Q(s,a)\) itself) breaks this unless you add back a correction term — which is what "action- dependent control variates" such as Q-Prop do.

Why gradient ascent finds good policies at all. \(J(\theta)\) is not concave in \(\theta\). Yet Agarwal et al. (2019) proved that for tabular softmax policies, exact policy gradient converges to the global optimum (local optima do not exist in that parameterisation, though plateaux do), and natural policy gradient converges at a rate independent of the number of states and actions. With function approximation, the guarantees weaken to "as good as the best policy in the class, up to how well the class can represent advantages" — a precise version of "you need a good enough network".

The maths

Setting. Episodic MDP; trajectory \(\tau = (s_0,a_0,r_1,\dots,s_{T})\); \(R(\tau) = \sum_{t=0}^{T-1}\gamma^t r_{t+1}\); \(J(\theta) = \mathbb E_{\tau\sim p_\theta}[R(\tau)]\).

Derivation: the policy-gradient theorem (trajectory form, with reward-to-go)

Start from \(J = \sum_\tau p_\theta(\tau)R(\tau)\) and use \(\nabla p = p\nabla\log p\):

\[ \nabla J = \mathbb E_\tau\big[R(\tau)\nabla\log p_\theta(\tau)\big] = \mathbb E_\tau\Big[\sum_{t'}\gamma^{t'}r_{t'+1}\sum_{t}\nabla\log\pi_\theta(a_t\mid s_t)\Big]. \]

Fix a pair \(t > t'\) (an action after the reward). Condition on the history \(h_t\) up to \(s_t\), which determines \(r_{t'+1}\):

\[ \mathbb E\big[r_{t'+1}\nabla\log\pi_\theta(a_t\mid s_t)\big] = \mathbb E\Big[r_{t'+1}\,\underbrace{\mathbb E_{a_t\sim\pi_\theta(\cdot\mid s_t)}\big[\nabla\log\pi_\theta(a_t\mid s_t)\big]}_{=\ \nabla\sum_a\pi_\theta(a\mid s_t)\ =\ 0}\Big] = 0 . \]

So only rewards at or after step \(t\) survive next to action \(t\):

\[ \nabla J = \mathbb E_\tau\Big[\sum_t \nabla\log\pi_\theta(a_t\mid s_t)\sum_{t'\ge t}\gamma^{t'}r_{t'+1}\Big] = \mathbb E_\tau\Big[\sum_t \gamma^t\,\nabla\log\pi_\theta(a_t\mid s_t)\,G_t\Big]. \]

Since \(\mathbb E[G_t\mid s_t,a_t] = Q^\pi(s_t,a_t)\), the same argument gives the state-visitation form of Sutton et al. (1999):

\[ \nabla J = \sum_t \gamma^t\,\mathbb E_{s_t,a_t}\big[Q^\pi(s_t,a_t)\nabla\log\pi_\theta(a_t\mid s_t)\big] \;\propto\; \mathbb E_{s\sim d^\pi,\,a\sim\pi}\big[Q^\pi(s,a)\nabla\log\pi_\theta(a\mid s)\big], \]

where \(d^\pi\) is the discounted state-visitation distribution. Crucially, no derivative of \(d^\pi\) appears, even though changing \(\theta\) changes which states are visited.

Practitioners usually drop the \(\gamma^t\) factor. The result is no longer the gradient of the discounted objective (Nota and Thomas, 2019, show it is not the gradient of any function), but it weights late states as much as early ones, which is what you want when \(\gamma\) is a variance-reduction device rather than part of the goal.

Baseline unbiasedness. For any \(b(s)\): \(\mathbb E_{a\sim\pi(\cdot\mid s)}\big[b(s)\nabla\log\pi_\theta(a\mid s)\big] = b(s)\sum_a\nabla\pi_\theta(a\mid s) = b(s)\nabla 1 = 0.\)

Derivation: the variance-minimising baseline

Consider one component \(g = \partial_{\theta_k}\log\pi_\theta(a\mid s)\) and a scalar return \(R\) (single step, for clarity). The estimator is \(X = g(R - b)\), with mean \(\mathbb E[gR]\) independent of \(b\). Its variance is

\[ \operatorname{Var}[X] = \mathbb E[g^2(R-b)^2] - (\mathbb E[gR])^2 . \]

Differentiate with respect to \(b\) and set to zero: \(-2\,\mathbb E[g^2(R-b)] = 0\), so

\[ b^*_k = \frac{\mathbb E[g_k^2 R]}{\mathbb E[g_k^2]}, \]

the expected return weighted by the squared score. It differs per parameter and is rarely used exactly; \(V^\pi(s) = \mathbb E[R\mid s]\) is the special case where \(g^2\) is independent of \(R\), and is close enough in practice (Greensmith, Bartlett and Baxter, 2004, analyse the gap).

Softmax score. For \(\pi = \operatorname{softmax}(\mathbf z)\) and logits \(\mathbf z\): \(\partial \log\pi_a/\partial z_b = \mathbb 1[a=b] - \pi_b\), i.e. \(\nabla_{\mathbf z}\log\pi_a = \mathbf e_a - \pi\). In a network, backpropagate this vector from the logits.

Gaussian score. For \(a\sim\mathcal N(\mu,\sigma^2)\): \(\partial_\mu\log\pi = (a-\mu)/\sigma^2\) and \(\partial_{\log\sigma}\log\pi = (a-\mu)^2/\sigma^2 - 1\). The second says: if an unusually far sample turned out well, widen the distribution.

Fisher information and the natural gradient. The KL divergence between nearby policies is locally quadratic:

\[ \mathbb E_s\Big[D_{\mathrm{KL}}\big(\pi_\theta(\cdot\mid s)\,\|\,\pi_{\theta+\Delta}(\cdot\mid s)\big)\Big] = \tfrac12\,\Delta^\top F(\theta)\,\Delta + O(\|\Delta\|^3), \qquad F = \mathbb E\big[\nabla\log\pi\,\nabla\log\pi^\top\big]. \]

Maximising the linearised gain \(\nabla J^\top\Delta\) subject to \(\tfrac12\Delta^\top F\Delta\le\delta\) (Lagrangian, set the gradient to zero) gives \(\Delta\propto F^{-1}\nabla J\), scaled to \(\Delta = \sqrt{2\delta / (\nabla J^\top F^{-1}\nabla J)}\;F^{-1}\nabla J\). That is the natural gradient step, and TRPO's step before its line search.

Shapes in a batch implementation. For \(N\) episodes padded to length \(T\) with \(|\mathcal A|\) discrete actions: logits \(N\times T\times|\mathcal A|\); chosen-action log-probabilities \(N\times T\); weights \(\hat A\), \(N\times T\) (no gradient); a mask \(N\times T\) for padding. Loss \(= -\sum(\text{mask}\odot\hat A\odot\log\pi)/\sum\text{mask}\).

Build it

NumPy. Part 1 checks the score-function estimator against the exact gradient on a bandit. Part 2 solves the short corridor exactly, measures the variance of three estimators, and runs REINFORCE with and without a baseline.

import numpy as np
rng = np.random.default_rng(0)
# Part 1. The score-function (log-derivative) estimator on a 3-armed bandit with a softmax policy.
r = np.array([1.0, 2.0, 3.0])                       # deterministic reward of each arm
theta = np.array([0.0, 0.0, 0.0])
pi = np.exp(theta) / np.exp(theta).sum()
exact = pi * (r - pi @ r)                            # dJ/dtheta_k = pi_k (r_k - J)
a = rng.choice(3, size=100_000, p=pi)
score = np.eye(3)[a] - pi                            # grad log softmax = onehot(a) - pi
for name, b in (("no baseline", 0.0), ("baseline = J", pi @ r)):
    g = score * (r[a] - b)[:, None]                  # one-sample gradient estimates
    print(f"{name:13s}: mean {g.mean(0).round(3)}  per-sample std {g.std(0).round(3)}")
print(f"{'exact':13s}: {exact.round(3)}")
no baseline  : mean [-0.336  0.002  0.333]  per-sample std [0.719 0.983 1.187]
baseline = J : mean [-0.332 -0.001  0.333]  per-sample std [0.272 0.272 0.273]
exact        : [-0.333  0.     0.333]
import numpy as np
rng = np.random.default_rng(0)
# Part 2. Short corridor (Sutton & Barto, Example 13.1). States 0,1,2 then the goal; reward -1 per step.
# In state 1 the actions are swapped. The agent cannot tell the states apart, so its policy is one
# number: p = sigmoid(theta) = probability of pressing "right" everywhere.
def env_step(s, right):
    move = 1 if right else -1
    if s == 1: move = -move                          # the swapped state
    return max(0, s + move)

def exact_values(p):                                 # solve v = -1 + P v for the three states
    P = np.array([[1 - p, p, 0], [p, 0, 1 - p], [0, 1 - p, 0]])
    return np.linalg.solve(np.eye(3) - P, -np.ones(3))

ps = np.linspace(0.01, 0.99, 981); J = np.array([exact_values(p)[0] for p in ps])
print(f"best p = {ps[J.argmax()]:.3f}, J = {J.max():.2f};  p=0.05 (eps-greedy left): J = {exact_values(0.05)[0]:.1f};"
      f"  p=0.95: J = {exact_values(0.95)[0]:.1f}")

def episode(theta, cap=1000):
    p, s, traj = 1 / (1 + np.exp(-theta)), 0, []
    while s != 3 and len(traj) < cap:
        right = rng.random() < p
        traj.append((s, (1 - p) if right else -p))   # d/dtheta log pi(a) for a sigmoid policy
        s = env_step(s, right)
    G = -np.arange(len(traj), 0, -1.0)               # reward-to-go: -(steps remaining)
    return traj, G

theta0 = 0.0; v = exact_values(0.5)                  # evaluate estimators at p = 0.5
est = {"total return x all scores": [], "reward-to-go": [], "reward-to-go - v(s)": []}
for _ in range(20_000):
    traj, G = episode(theta0)
    sc = np.array([g for _, g in traj]); st = np.array([s for s, _ in traj])
    est["total return x all scores"].append(G[0] * sc.sum())
    est["reward-to-go"].append((G * sc).sum())
    est["reward-to-go - v(s)"].append(((G - v[st]) * sc).sum())
h = 1e-4; true_grad = (exact_values(1/(1+np.exp(-h)))[0] - exact_values(1/(1+np.exp(h)))[0]) / (2*h)
print(f"true dJ/dtheta at p=0.5: {true_grad:.3f}")
for k, g in est.items():
    print(f"  {k:26s} mean {np.mean(g):7.3f}   std {np.std(g):7.2f}")

checkpoints = (50, 200, 1000)
for use_baseline, lr in ((False, 2**-13), (True, 2**-9)):    # step sizes from Sutton & Barto, Fig. 13.2
    curve = np.zeros(len(checkpoints))
    for run in range(100):
        theta, w = -1.5, np.zeros(3)                 # start at p = 0.18
        for ep in range(1, 1001):
            traj, G = episode(theta)
            for (s, sc), g in zip(traj, G):
                delta = g - (w[s] if use_baseline else 0.0)
                w[s] += 2**-6 * delta                # tabular state-value baseline
                theta += lr * delta * sc
            if ep in checkpoints:
                curve[checkpoints.index(ep)] += exact_values(1 / (1 + np.exp(-theta)))[0] / 100
    print(f"REINFORCE {'with' if use_baseline else 'without':7s} baseline: mean J after "
          + ", ".join(f"{c} eps = {j:.1f}" for c, j in zip(checkpoints, curve)))
best p = 0.586, J = -11.66;  p=0.05 (eps-greedy left): J = -82.1;  p=0.95: J = -44.2
true dJ/dtheta at p=0.5: 2.000
  total return x all scores  mean   1.607   std   42.49
  reward-to-go               mean   1.955   std   25.89
  reward-to-go - v(s)        mean   2.067   std   16.03
REINFORCE without baseline: mean J after 50 eps = -22.7, 200 eps = -19.3, 1000 eps = -13.4
REINFORCE with    baseline: mean J after 50 eps = -14.5, 200 eps = -11.9, 1000 eps = -11.8

The same algorithm in PyTorch (standard code, not run here), for any Gymnasium environment with discrete actions:

import torch, torch.nn as nn

policy = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(), nn.Linear(64, n_actions))
value = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(), nn.Linear(64, 1))
opt = torch.optim.Adam([*policy.parameters(), *value.parameters()], lr=3e-3)

def reinforce_step(obs, actions, rewards, gamma=0.99):
    """One episode: obs (T, obs_dim) float, actions (T,) long, rewards (T,) float."""
    G = torch.zeros_like(rewards); running = 0.0
    for t in reversed(range(len(rewards))):             # reward-to-go
        running = rewards[t] + gamma * running; G[t] = running
    v = value(obs).squeeze(-1)                           # baseline b(s_t), shape (T,)
    adv = (G - v).detach()                               # weights are constants
    logp = torch.distributions.Categorical(logits=policy(obs)).log_prob(actions)
    loss = -(adv * logp).mean() + 0.5 * ((G - v) ** 2).mean()   # policy loss + baseline regression
    opt.zero_grad(); loss.backward(); opt.step()

Things to try

  • Part 1: compute the variance-minimising baseline for each component (answer in Check yourself) and confirm numerically that it beats \(b = J\).
  • Part 2: replace the learned baseline by the true \(v_\pi\) (from exact_values) and by a constant equal to the average return. Which matters more: the baseline's accuracy or its state dependence?
  • Part 2: add an entropy bonus \(\beta\,\mathcal H(\pi)\) to the objective and start from \(p = 0.01\). Without it, how often does REINFORCE get stuck?
  • Implement Karpathy's Pong from Pixels or REINFORCE on CartPole-v1; plot the gradient's signal-to-noise ratio (norm of the batch mean over the mean per-episode norm) as the batch size grows.
  • Estimate the Fisher matrix on the bandit, take a natural gradient step and an ordinary step of equal KL, and compare the improvement in \(J\).

Check yourself

State the log-derivative trick and say why it lets you ignore the environment's dynamics.

\(\nabla_\theta\mathbb E_{p_\theta}[f] = \mathbb E_{p_\theta}[f\,\nabla_\theta\log p_\theta]\). For trajectories, \(\log p_\theta(\tau)\) is a sum of policy log-probabilities and dynamics log-probabilities; only the former depend on \(\theta\), so only they appear in the gradient.

Why is subtracting a state-dependent baseline unbiased?

Because \(\mathbb E_{a\sim\pi(\cdot\mid s)}[\nabla\log\pi(a\mid s)] = \nabla\sum_a\pi(a\mid s) = 0\), so \(b(s)\) times the score has zero mean at every state.

In what sense is a policy gradient 'weighted maximum likelihood'?

The surrogate loss \(-\sum \hat A_t\log\pi_\theta(a_t\mid s_t)\) is the log-likelihood of the agent's own actions, each weighted by its advantage. With all weights equal to 1 it is behaviour cloning; the advantage decides whether each sample is imitated or anti-imitated.

Why can the short-corridor optimum not be found by Q-learning with ε-greedy?

The agent cannot distinguish the states, so any deterministic policy does the same thing everywhere and gets stuck (always right never passes the swapped state; always left never leaves the start). The optimum is a stochastic policy with \(p\approx0.586\); ε-greedy can only represent \(p\in\{0.05, 0.95\}\).

For the three-armed bandit with uniform policy, what is the variance-minimising baseline for the third logit's gradient?

\(g_3 = \mathbb 1[a=3] - \tfrac13\), so \(g_3^2 = \tfrac49\) if \(a = 3\) (reward 3) and \(\tfrac19\) otherwise. \(\mathbb E[g_3^2R] = \tfrac13(\tfrac49\cdot3 + \tfrac19\cdot1 + \tfrac19\cdot2) = \tfrac{15}{27}\), \(\mathbb E[g_3^2] = \tfrac{6}{27}\), so \(b^* = 2.5\), not \(J = 2\). It halves the per-sample standard deviation again (from 0.272 to 0.136).

Why does a bad policy-gradient step hurt more than a bad supervised step?

In supervised learning the data distribution is fixed; the next gradient corrects the mistake. In RL the policy generates its own data: a step that collapses the policy changes what is observed, and from a degenerate policy the gradient may carry no useful signal, so performance can collapse permanently. This motivates trust regions (TRPO) and clipping (PPO).

Hard: why does the leave-one-out baseline keep REINFORCE unbiased, while using the group mean including sample i does not (exactly)?

Unbiasedness needs the baseline to be independent of the action — here, of completion \(i\). The leave-one-out mean uses only the other \(k-1\) samples, which are independent of \(y_i\) given \(x\). The full group mean includes \(r_i\), so it is correlated with \(y_i\); the estimator is biased by a factor of \((k-1)/k\) — it equals \(\tfrac{k-1}{k}\) times the leave-one-out estimator, so for fixed \(k\) this is just a rescaled step size, which is why group-mean methods work in practice.

Hard: the natural gradient is parameterisation-invariant. What does that mean concretely?

If you reparameterise the policy \(\theta = h(\phi)\) with an invertible smooth \(h\), a natural-gradient step in \(\phi\) produces (to first order) the same change in the policy as a natural-gradient step in \(\theta\), because both are defined by the KL between distributions, not by Euclidean distance between parameters. An ordinary gradient step does not have this property: rescaling one parameter by 10 changes the direction of steepest ascent.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Books

Where this leads