Search

Search papers and lessons

Policy Gradient

Level 4 · 17 min read

A policy gradient method improves a behaviour directly by nudging its probabilities toward actions that earned above-typical returns, using the score function.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Discrete math
  • Linear algebra
  • Reinforcement learning
  • Inference
  • Sign in to see your progress

TL;DR

A policy gradient method learns a policy directly: a rule that gives the probability of each action in each state. It runs the policy, observes the returns that followed each action, and nudges the probabilities up for actions that did better than usual and down for those that did worse. The direction of that nudge is an expectation of the score weighted by the return.

Because the policy is the thing being optimised, these methods handle continuous and randomised actions naturally, which is why they are the usual tool for robot control and the fine-tuning of language models.

Where you'll see it: in REINFORCE-style training of game agents, in actor-critic systems built on value functions, and in PPO, the algorithm used to align most large language models with human feedback.

Intuition

Turn up the actions that paid off

Picture a shop that can put one of three products at the front of the window. You do not know which sells best, so you start with equal chances. Each day you pick one at random, record the takings, and then adjust. If the product you showed earned more than the usual takings, you show it a little more often next time. If it earned less, you show it less. Over weeks the window converges on the best seller without you ever writing down a model of customers.

That is the policy gradient idea. The policy is the window display, a probability for each action. The learner does not estimate the value of every option separately and then pick the best. It moves the probabilities directly, a small step at a time, in whatever direction raised the expected reward.

Why not just pick the best-looking action? Because the environment is noisy and the best action can change. A policy that is always deterministic stops exploring, and a policy that is a smooth probability can keep trying alternatives while it leans toward the good ones.

−4−3−2−10123400.20.40.60.81preference of action 1 over action 2 (logit difference)probability
  • probability of action 1
With two actions, a softmax policy gives probability one half at equal preference, and the probability of action 1 rises smoothly as its preference grows. Gradient steps move the preference, not the probability directly.

The math

Setup

A policy πθ(a∣s)\pi_\theta(a \mid s) gives the probability of action aa in state ss, with parameters θ\theta. An episode is a trajectory τ=(s0,a0,r0,s1,…,sT)\tau = (s_0, a_0, r_0, s_1, \dots, s_T) of length TT. The discounted return from time tt is

Gt=∑k=tTγ k−t rk,G_t = \sum_{k=t}^{T} \gamma^{\,k-t}\, r_k,

where the discount factor γ∈[0,1]\gamma \in [0, 1] says how much later rewards count. The goal is to maximise the expected return from the start,

J(θ)=Eτ∼πθ ⁣[∑t=0Tγtrt].J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\!\left[\sum_{t=0}^{T} \gamma^t r_t\right].

The gradient is an expected score times return

Let R(τ)=∑t=0TγtrtR(\tau) = \sum_{t=0}^{T} \gamma^t r_t be the discounted return of a whole trajectory, so J(θ)=E[R(τ)]J(\theta) = \mathbb{E}[R(\tau)]. Write the probability of a trajectory as pθ(τ)=ρ(s0)∏tπθ(at∣st) P(st+1∣st,at)p_\theta(\tau) = \rho(s_0)\prod_t \pi_\theta(a_t \mid s_t)\,P(s_{t+1} \mid s_t, a_t), where ρ\rho is the start distribution and PP the environment's transition rule. Then

∇θJ=∫∇θpθ(τ) R(τ) dτ=E ⁣[∇θlog⁡pθ(τ) R(τ)],\nabla_\theta J = \int \nabla_\theta p_\theta(\tau)\, R(\tau)\, d\tau = \mathbb{E}\!\left[\nabla_\theta \log p_\theta(\tau)\, R(\tau)\right],

using ∇p=p ∇log⁡p\nabla p = p\,\nabla \log p. This is the log-derivative trick. The logarithm turns the product into a sum, and the terms ρ(s0)\rho(s_0) and PP do not depend on θ\theta, so they vanish under the gradient:

∇θlog⁡pθ(τ)=∑t∇θlog⁡πθ(at∣st).\nabla_\theta \log p_\theta(\tau) = \sum_{t} \nabla_\theta \log \pi_\theta(a_t \mid s_t).

Notice that the environment's dynamics never appear. We never differentiate the world, only the policy. That is what makes the method model-free.

Causality and reward-to-go

An action at time tt cannot change rewards that came before it. So in the product of the two sums, only the rewards from tt onward depend on ata_t. Keeping only those gives the REINFORCE estimator:

∇θJ=E ⁣[∑tγt ∇θlog⁡πθ(at∣st) Gt].\nabla_\theta J = \mathbb{E}\!\left[\sum_{t} \gamma^t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, G_t\right].

The factor γt\gamma^t comes from the objective as written; many implementations drop it and use γ\gamma only inside GtG_t. Either is a valid gradient for the corresponding objective.

Baselines and advantages

Subtracting a baseline b(st)b(s_t) that depends only on the state leaves the expected gradient unchanged. For a fixed state,

∑aπθ(a∣s) ∇θlog⁡πθ(a∣s)=∑a∇θπθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0.\sum_a \pi_\theta(a \mid s)\, \nabla_\theta \log \pi_\theta(a \mid s) = \sum_a \nabla_\theta \pi_\theta(a \mid s) = \nabla_\theta \sum_a \pi_\theta(a \mid s) = \nabla_\theta 1 = 0.

Because b(st)b(s_t) is fixed once the state is, it can be pulled out of the sum over actions, so E[∇log⁡π(at∣st)⋅b(st)∣st]=0\mathbb{E}[\nabla \log \pi(a_t \mid s_t) \cdot b(s_t) \mid s_t] = 0 and the same holds on average over states. The baseline does not bias the gradient, but it can reduce the variance a great deal. The natural choice is the value b=vπ(st)b = v_\pi(s_t). 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), because E[Gt∣st,at]=qπ(st,at)\mathbb{E}[G_t \mid s_t, a_t] = q_\pi(s_t, a_t). The update

θ←θ+α∑t∇θlog⁡πθ(at∣st) A^t\theta \leftarrow \theta + \alpha \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, \hat{A}_t

is the usual form of the policy gradient in practice, and α\alpha is the learning rate. Methods that also learn vπv_\pi are called actor-critic: the actor is the policy, and the critic supplies the baseline.

A softmax policy

For a finite set of actions, a common choice is the softmax policy with one logit θa\theta_a per action:

πθ(a)=eθa∑beθb,∂∂θklog⁡πθ(a)=1[a=k]−πθ(k).\pi_\theta(a) = \frac{e^{\theta_a}}{\sum_b e^{\theta_b}}, \qquad \frac{\partial}{\partial \theta_k} \log \pi_\theta(a) = \mathbf{1}[a = k] - \pi_\theta(k).

Increasing the logit of the chosen action raises its probability, and the other logits move down in proportion to their probability.

Worked examples

Example
One step with three actions

Start with three actions and equal logits θ=(0,0,0)\theta = (0, 0, 0), so each has probability 1/31/3. We take action 1 and it gives return G=2G = 2. Learning rate α=0.5\alpha = 0.5, no baseline.

  1. The gradient of log⁡π(1)\log \pi(1) with respect to the logits is (1−13, −13, −13)=(23,−13,−13)(1 - \tfrac13,\ -\tfrac13,\ -\tfrac13) = (\tfrac23, -\tfrac13, -\tfrac13).
  2. Multiply by the return: 2×(23,−13,−13)=(43,−23,−23)2 \times (\tfrac23, -\tfrac13, -\tfrac13) = (\tfrac43, -\tfrac23, -\tfrac23).
  3. Update: θ←θ+0.5×(43,−23,−23)=(23,−13,−13)\theta \leftarrow \theta + 0.5 \times (\tfrac43, -\tfrac23, -\tfrac23) = (\tfrac23, -\tfrac13, -\tfrac13).
  4. New weights: e2/3≈1.948e^{2/3} \approx 1.948, e−1/3≈0.717e^{-1/3} \approx 0.717. The sum is 1.948+0.717+0.717=3.3821.948 + 0.717 + 0.717 = 3.382.
  5. New probabilities: π(1)≈0.576\pi(1) \approx 0.576, π(2)=π(3)≈0.212\pi(2) = \pi(3) \approx 0.212.
  6. Interpretation: the rewarded action went from one third to over a half in one step, and the others shrank together. Their probabilities always sum to one, so raising one must lower the rest.
Example
A baseline that removes the offset

A state's actions all pay close to a large background value. Suppose an action taken there returns G=102G = 102, while the state's value is v=100v = 100. Compare the two learning signals for the same sampled action.

  1. Without a baseline, the weight on the score is G=102G = 102.
  2. With the baseline, the weight is G−v=2G - v = 2.
  3. Both have the same expected gradient, because the baseline term has zero mean.
  4. The raw signal is fifty-one times larger, yet only 22 of it says anything about this action. Most of the 102102 is the shared background that every action receives.
  5. Interpretation: the baseline reduces noise by removing a common offset. Estimates with the baseline need far fewer episodes to reach the same accuracy.

Tradeoffs and failure modes

The method is simple and general, but its estimates are noisy, and the update size is easy to get wrong.

SituationProblemBetter choice
Plain REINFORCE on long episodesReturns vary wildly, so the gradient is high varianceAdd a learned baseline (actor-critic), or use [[generalized-advantage-estimation
Step too largeOne update can push the policy far from the data it was measured on, and performance collapsesTrust-region or clipped updates, as in [[trust-region-policy-optimization
Few samples per updateThe gradient is inaccurate, and each sample is used only onceReuse data with importance weights, or batch more episodes
Sparse rewardAlmost every return is zero, so there is no signalShaped rewards, or methods that learn from a reward model
Deterministic policy wantedPlain policy gradients keep some randomness, and the policy may converge too earlyEntropy bonus, or deterministic policy gradients for continuous control
Rewards from a learned modelThe policy can exploit mistakes in the modelConstrain the policy to stay near a reference, as in RLHF

A common mistake is to use the raw return at every step without the reward-to-go structure. That is unbiased but much noisier, and it can hide bugs because the training curve still moves.

History

Ronald Williams described the REINFORCE family of algorithms in 1992, for networks whose outputs are stochastic. The core identity, that the gradient of an expected reward is an expected score times reward, was known in statistics and control earlier. Williams's contribution was to turn it into a practical learning rule for neural networks.

Policy gradients were not the main line of reinforcement learning for a long time. Q-learning and temporal difference methods dominated, and gradient methods were thought to be noisy and slow. Richard Sutton and colleagues gave the first general policy-gradient theorem with function approximation in 2000, and actor-critic methods followed. The breakthrough for deep networks came from trust regions. Schulman and colleagues proposed TRPO in 2015 to stop updates from being too large, and in 2017 introduced PPO, which replaced the hard constraint with a simpler clipped objective. PPO was easy to implement and robust, which made it the standard choice for training agents, and later for fine-tuning language models with human feedback.

Check yourself

QuestionWhy does subtracting a state-dependent baseline from the return not change the expected policy gradient?Show answer

For a fixed state, the expected score over actions is ∑aπ(a∣s) ∇log⁡π(a∣s)=∇∑aπ(a∣s)=∇1=0\sum_a \pi(a \mid s)\,\nabla \log \pi(a \mid s) = \nabla \sum_a \pi(a \mid s) = \nabla 1 = 0. The baseline depends only on the state, so it factors out of the sum over actions and contributes zero on average. It can still change the variance of each sampled gradient, which is why it helps.

QuestionA softmax policy has logits (0,0)(0, 0) for two actions, so each has probability 1/21/2. You take action 1 and receive return G=4G = 4, with learning rate α=1\alpha = 1. What are the new logits, and the new probability of action 1?Show answer

The score for action 1 is (1−12,−12)=(12,−12)(1 - \tfrac12, -\tfrac12) = (\tfrac12, -\tfrac12). Multiplied by the return, the update is (2,−2)(2, -2), so the new logits are (2,−2)(2, -2). The probability of action 1 is e2/(e2+e−2)=1/(1+e−4)≈0.982e^2 / (e^2 + e^{-2}) = 1/(1 + e^{-4}) \approx 0.982.

QuestionWhy does the policy gradient never need a model of the environment's transition probabilities?Show answer

Taking the logarithm of the trajectory probability turns the product of transition probabilities into a sum. Those terms do not depend on the policy parameters, so their gradient is zero. Only the policy terms remain, and they are known to the agent because it chose the actions itself.

QuestionYou are training an agent whose returns range from −1000-1000 to +1000+1000 across episodes, and the training curve is very noisy. Name two changes that reduce the variance of the gradient estimate without changing its expectation, and explain why each one works.Show answer

A learned baseline, such as the state value, removes the part of the return that every action shares, so the update responds to how much better an action was than usual. Reward-to-go replaces the whole-episode return with the sum of rewards from the current step onward, because actions cannot affect earlier rewards. Both leave the expected gradient unchanged while cutting the noise.

Sources