Level 3 In-Depth AI · Reinforcement Learning
Policy Gradients
Instead of learning values and acting greedily, adjust the policy itself by gradient ascent. Make actions that led to high returns more likely. REINFORCE derived and coded, and why baselines tame its noise.
- Level
- ●●●●● Advanced
- Reading
- 14 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 16 concepts →
- Quiz
- 5 questions ↓
This leads to
Actor-Critic MethodsThe full path from zero — 16 concepts before this one
- What Is AI?
- Probability Basics
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Reinforcement Learning: The Basics
- Linear Regression
- The Perceptron
- Markov Decision Processes
- Logistic Regression
- Neural Networks
- Policy Gradients
Read them roughly in this order. See it on the concept map →
Why it matters
The methods so far (Q-Learning, Deep Q-Networks) learn values and then act greedily on them. That works well for games with a few buttons, but it has blind spots:
- Continuous actions. A robot arm chooses real-valued torques. "Take the action with the highest Q-value" means solving an optimisation problem at every single step.
- Stochastic policies. Sometimes the best behaviour is genuinely random. Think of rock–paper–scissors, bluffing in poker, or a robot that can't tell two places apart. A greedy policy is always deterministic, so it can't represent these.
- Smoothness. A tiny change in a Q-value can flip the argmax and change behaviour abruptly.
Policy-gradient methods sidestep all three. They put the policy itself in a neural network that outputs action probabilities, and they adjust its parameters by gradient ascent on the expected return. This family includes Actor-Critic Methods methods and Proximal Policy Optimization, the algorithm OpenAI used to train Dota 2 agents and, in RLHF and Preference Optimization, to train ChatGPT-style models. When a language model is fine-tuned with RL, it is a policy-gradient method: the model is the policy, each token is an action, and the reward score says how good the whole answer was (Reasoning Models and Test-Time Compute).
The intuition
Here is the whole idea in one sentence: try things, and make whatever you did more likely if it turned out better than usual, and less likely if it turned out worse.
Imagine learning to throw darts with your eyes closed. A coach only tells you your score after each throw. You can't compute the "right" throw, but you can adjust. If a throw scored well, do more of whatever you just did. If it scored badly, do less of it. Each throw is a small random experiment, and the score tells you which way to lean.
A policy network does exactly that with probabilities. It plays a whole episode by sampling actions from its current probabilities. At the end, every action in the episode gets nudged: up if the return was above average, down if below.
No single episode proves that an action was good. The return depends on every other action and on luck. But averaged over many episodes, actions that genuinely help get pushed up more often than they get pushed down. That average push is exactly the gradient of the expected return.
Key idea Policy gradients do gradient ascent on the expected return . The update is "return × gradient of log-probability of the action taken": . Good outcomes reinforce the actions that led to them.
How it works
The objective
Let be a trajectory, and let be its total (discounted) return. A policy with parameters makes some trajectories more likely than others. Its quality is the expected return:
We want , the direction in parameter space that increases fastest (Partial Derivatives and Gradients). Then we step uphill: . The difficulty is that affects only through which trajectories happen, and the environment that turns actions into trajectories is a black box we can't differentiate.
The log-derivative trick
The way round this is a one-line identity. For any probability , the chain rule gives . Rearranged:
Apply it inside the expectation. The expectation is a sum over trajectories, , so
The gradient is now an expectation, so we can estimate it by sampling trajectories and averaging. That is something we can actually do. The quantity is called the score function, and this is also known as the likelihood-ratio method.
What is ? The probability of a trajectory is a product of the start-state probability, the policy's choices and the environment's transitions:
Taking the log turns the product into a sum, and only the policy terms depend on . The environment's dynamics drop out of the gradient entirely:
This is why policy gradients are model-free. You never need to know how the environment works, only how your own policy assigns probabilities.
Reward-to-go and REINFORCE
One more refinement. An action at time can't affect rewards that came before it. So instead of weighting each action by the whole episode's return, weight it by the reward-to-go, the return from that step onward, . The expectation is unchanged and the noise drops. This gives the REINFORCE algorithm (Williams, 1992). In Sutton and Barto's notation, after each episode, for every step :
The factor comes from the discounted objective. Many implementations drop it in practice.
The general result behind this, the policy gradient theorem (Sutton, McAllester, Singh and Mansour, 2000), says the gradient can be written in terms of action values: , where is how often the policy visits state . REINFORCE uses the sampled return as an unbiased estimate of .
A softmax policy, worked by hand
For discrete actions, a policy network outputs one score (logit) per action and turns them into probabilities with a softmax:
The gradient of with respect to the logits is beautifully simple: 1 for the action taken, minus the probability of each action. That is, , where is a one-hot vector.
Worked example (the figure above). Three actions, all logits 0, so . The agent took → and the return was 2 above average. With :
- Gradient of :
- Update:
- New probabilities: softmax of is .
The chosen action gained probability and the others lost it. Had the return been 2 below average, the signs would flip.
Why a stochastic policy can beat every deterministic one
Sutton and Barto's short corridor makes this vivid. There are three squares and a goal, and every step costs −1. In the middle square the controls are secretly reversed, so "right" moves left. The agent's observation is the same in every square, so its policy is a single number: the probability of choosing "right". Always-right gets stuck bouncing in the reversed square forever, and always-left never leaves the start. Both have return −∞. The best policy is random, with and expected return .
Baselines: same direction, less noise
REINFORCE is unbiased: on average it points exactly uphill. But it is very noisy, because the return of a single episode swings wildly with luck. In the corridor every return is negative, so plain REINFORCE pushes down every action it ever takes. It only makes progress because bad actions get pushed down harder.
The fix is to subtract a baseline from the return:
Any baseline that does not depend on the action leaves the expected gradient unchanged. That is because . But a good baseline can cut the variance a lot. Now an action is pushed up only if it did better than expected. The natural choice is the state value . Learning that value with a second network is exactly what Actor-Critic Methods methods do, and is called the advantage.
In code
REINFORCE in NumPy on the short corridor. The policy is one parameter with (the sigmoid), so and . It starts at a poor policy, .
import numpy as np
def step(s, a):
"""Short corridor (Sutton & Barto, Example 13.1). a = 1 is 'right', 0 is 'left'.
In state 1 the controls are reversed. Every step costs -1; leaving state 2 rightwards ends it."""
move = (1 if a == 1 else -1) * (-1 if s == 1 else 1)
s2 = max(0, s + move)
return s2, -1.0, s2 == 3
def episode(theta, rng):
p_right = 1 / (1 + np.exp(-theta)) # policy: pi(right) = sigmoid(theta)
s, done, actions, rewards = 0, False, [], []
while not done and len(rewards) < 1000:
a = int(rng.random() < p_right)
s, r, done = step(s, a)
actions.append(a); rewards.append(r)
G = np.cumsum(rewards[::-1])[::-1] # return from each step onward (gamma = 1)
grad_log_pi = np.where(np.array(actions) == 1, 1 - p_right, -p_right) # d/dθ log π(a)
return G, grad_log_pi
def reinforce(alpha=2**-10, episodes=1000, seed=0):
rng, theta, returns = np.random.default_rng(seed), -2.2, [] # start: π(right) ≈ 0.1
for _ in range(episodes):
G, grad_log_pi = episode(theta, rng)
theta += alpha * np.sum(G * grad_log_pi) # REINFORCE update
returns.append(G[0])
return np.array(returns), 1 / (1 + np.exp(-theta))
runs = [reinforce(seed=k) for k in range(50)]
curve = np.mean([r for r, _ in runs], axis=0)
for i in range(0, 1000, 200):
print(f"episodes {i+1:4d}-{i+200:4d}: average return {curve[i:i+200].mean():6.1f}")
print(f"learned pi(right) = {np.mean([p for _, p in runs]):.2f} (best possible: 0.59, return -11.66)")
# episodes 1- 200: average return -18.3
# episodes 201- 400: average return -12.2
# episodes 401- 600: average return -11.8
# episodes 601- 800: average return -11.9
# episodes 801-1000: average return -11.7
# learned pi(right) = 0.58 (best possible: 0.59, return -11.66)
Averaged over 50 runs, REINFORCE climbs from a return of about −42 to −11.7, within a whisker of the optimum, and finds the random policy no greedy method could express.
To see what a baseline buys, freeze the policy at and compare 20,000 single-episode gradient estimates with and without one (append this to the code above):
rng = np.random.default_rng(1)
samples = [episode(-2.2, rng) for _ in range(20_000)] # fixed policy, π(right) ≈ 0.1
b = np.mean([G.mean() for G, _ in samples]) # baseline: a typical return
plain = [np.sum(G * g) for G, g in samples]
based = [np.sum((G - b) * g) for G, g in samples]
print(f"baseline b = {b:.1f}")
print(f"without baseline: mean gradient {np.mean(plain):6.2f}, std {np.std(plain):6.1f}")
print(f"with baseline: mean gradient {np.mean(based):6.2f}, std {np.std(based):6.1f}")
# baseline b = -21.5
# without baseline: mean gradient 35.11, std 111.8
# with baseline: mean gradient 35.22, std 84.6
Both estimates average about 35. The exact gradient, from differentiating the curve in the figure, is 35.9. But the baseline cuts the spread by a quarter, even though it is just one constant. A state-dependent baseline learned by a critic does much better.
In PyTorch you don't write the gradient yourself. You build a loss whose gradient is the policy gradient, , and let autograd do the rest. This is the pattern inside every policy-gradient library:
import torch
from torch.distributions import Categorical
def step(s, a): # the same short corridor
s2 = max(0, s + (1 if a == 1 else -1) * (-1 if s == 1 else 1))
return s2, -1.0, s2 == 3
torch.manual_seed(0)
logits = torch.tensor([0.0, -2.2], requires_grad=True) # π(right) ≈ 0.1 at the start
opt = torch.optim.SGD([logits], lr=2**-10)
for ep in range(1000):
s, done, log_probs, rewards = 0, False, [], []
while not done and len(rewards) < 1000:
dist = Categorical(logits=logits) # a policy network would map state -> logits
a = dist.sample()
log_probs.append(dist.log_prob(a))
s, r, done = step(s, a.item())
rewards.append(r)
G = torch.tensor(rewards).flip(0).cumsum(0).flip(0) # reward-to-go
loss = -(G * torch.stack(log_probs)).sum() # minimise −J == ascend J
opt.zero_grad(); loss.backward(); opt.step()
print(f"pi(right) = {torch.softmax(logits, 0)[1].item():.2f}")
# pi(right) = 0.63
The "loss" is not a real loss. Its value means nothing, and it can go up while the policy improves. It is only a device for getting the right gradient out of autograd.
Common pitfalls
- Forgetting the minus sign. Optimisers minimise. To maximise , minimise . Getting this wrong makes the agent learn to do as badly as possible, sometimes very efficiently.
- Huge variance. One lucky episode can swing the policy wildly. Use baselines, average over many episodes per update, and normalise returns (subtract the mean and divide by the standard deviation of each batch).
- Reusing old data. REINFORCE is on-policy. The gradient formula assumes the data came from the current policy. After an update, old episodes are stale and must be thrown away, which makes it sample-hungry. Proximal Policy Optimization squeezes a few more updates out of each batch, safely.
- Premature collapse. If the policy becomes nearly deterministic early, it stops exploring and the gradient vanishes. An entropy bonus, a reward for keeping the action distribution spread out, is the usual cure.
- Step size. Too large a step can wreck a good policy in one update, and because the next data comes from that wrecked policy, it may never recover. This is the problem TRPO and Proximal Policy Optimization were invented to solve.
Watch out The policy-gradient "loss" is a surrogate. Don't judge training by it. Plot the average episode return (and its spread over several random seeds) instead.
Where it leads
- Actor-Critic Methods: replace with a learned estimate, the critic, to cut variance further and allow updates before the episode ends.
- Proximal Policy Optimization: clip each update so the new policy can't move too far from the old one. Stable, simple, and the default for RLHF.
- Continuous actions: have the network output the mean (and spread) of a Gaussian distribution over actions, sample from it, and use the Gaussian's log-probability in exactly the same formula.
- Language models: the policy is the model, actions are tokens, and is the sum of the token log-probabilities of a response. Methods such as GRPO (used for DeepSeek-R1) are policy gradients with a group-average baseline (Reasoning Models and Test-Time Compute).
A bit of history
Ronald Williams introduced REINFORCE, including the use of a baseline, in a 1992 paper whose name is an acronym: "REward Increment = Nonnegative Factor × Offset Reinforcement × Characteristic Eligibility". Richard Sutton, David McAllester, Satinder Singh and Yishay Mansour proved the general policy gradient theorem in 2000, around the same time as Konda and Tsitsiklis's work on actor-critic. For years, value-based methods dominated practice. That changed in the mid-2010s, when trust-region methods (TRPO, 2015), A3C (2016) and Proximal Policy Optimization (2017) made policy gradients reliable with deep networks. Andrej Karpathy's 2016 blog post "Pong from Pixels", which trains a policy network on Atari Pong in about 130 lines of NumPy, became many people's introduction to the idea.
Try it
- Change the starting parameter to
theta = 2.2(π(right) ≈ 0.9). Does REINFORCE still find 0.59? Watch how the early returns compare.- Raise the step size to
2**-6. What happens to the learning curve, and why might a single unlucky episode cause it?- Add the constant baseline to the training loop: subtract the running average of
G[0]fromGbefore the update. Does the curve improve atalpha = 2**-10? At2**-8?Hint for 2: episodes from a poor policy can last hundreds of steps, so
np.sum(G * grad_log_pi)can be enormous.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Spinning Up in Deep RL
OpenAI's short, precise introduction to deep RL: key concepts and notation, the policy-gradient derivation, and clean reference implementations of VPG, PPO, DDPG, TD3 and SAC.
Reinforcement Learning: An Introduction
The foundational RL textbook by the field's founders. Free PDF.
Deep Reinforcement Learning: Pong from Pixels
A famous blog post that trains a policy network to play Pong with plain policy gradients in about 130 lines of NumPy, with a very clear explanation of why it works.
Policy Gradient Algorithms
The policy-gradient family in one place, from REINFORCE and actor-critic to A3C, TRPO, PPO and SAC, with consistent notation and derivations.
Simple statistical gradient-following algorithms for connectionist reinforcement learning
The REINFORCE paper: the likelihood-ratio policy gradient, including the use of a baseline.
Hugging Face Deep RL Course
A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/policy-gradients.md