◆ AI All-in-One

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
↗ Plan a path here

Read first

Markov Decision ProcessesGradient DescentNeural Networks

This leads to

Actor-Critic Methods
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Derivatives and Slopes
  4. Vectors
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Reinforcement Learning: The Basics
  12. Linear Regression
  13. The Perceptron
  14. Markov Decision Processes
  15. Logistic Regression
  16. Neural Networks
  17. 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 πθ(a∣s)\pi_\theta(a \mid s) that outputs action probabilities, and they adjust its parameters θ\theta 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.

0.33 ← 0.33 stay 0.33 → Before π(a | s) in one state 0.31 ← 0.31 stay 0.38 → After a good episode took →, return above average 0.29 ← 0.35 stay 0.35 → After a bad episode took ←, return below average update or θ ← θ + α · (G − b) · ∇ log π(a | s) actions followed by better-than-usual returns become more likely; worse ones less likely (softmax policy, α = 0.1, G − b = ±2; the right two panels each start from "Before")
Fig. 1 The policy-gradient update in one state. Before: all three actions equally likely. If the agent took → and the episode went better than usual, → becomes more likely (centre). If it took ← and things went worse than usual, ← becomes less likely (right). The numbers come from the softmax update worked through 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 J(θ)J(\theta). The update is "return × gradient of log-probability of the action taken": θ←θ+α Gt ∇θlog⁡πθ(At∣St)\theta \leftarrow \theta + \alpha\, G_t\, \nabla_\theta \log \pi_\theta(A_t \mid S_t). Good outcomes reinforce the actions that led to them.

How it works

The objective

Let τ=(S0,A0,R1,S1,A1,R2,… )\tau = (S_0, A_0, R_1, S_1, A_1, R_2, \dots) be a trajectory, and let R(τ)R(\tau) be its total (discounted) return. A policy with parameters θ\theta makes some trajectories more likely than others. Its quality is the expected return:

J(θ)=Eτ∼πθ[R(τ)]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\big[ R(\tau) \big]

We want ∇θJ\nabla_\theta J, the direction in parameter space that increases JJ fastest (Partial Derivatives and Gradients). Then we step uphill: θ←θ+α∇θJ\theta \leftarrow \theta + \alpha \nabla_\theta J. The difficulty is that θ\theta affects JJ 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 pθ(x)p_\theta(x), the chain rule gives ∇θlog⁡pθ(x)=∇θpθ(x)/pθ(x)\nabla_\theta \log p_\theta(x) = \nabla_\theta p_\theta(x) / p_\theta(x). Rearranged:

∇θpθ(x)=pθ(x) ∇θlog⁡pθ(x)\nabla_\theta p_\theta(x) = p_\theta(x)\, \nabla_\theta \log p_\theta(x)

Apply it inside the expectation. The expectation is a sum over trajectories, J=∑τpθ(τ)R(τ)J = \sum_\tau p_\theta(\tau) R(\tau), so

∇θJ=∑τ∇θpθ(τ) R(τ)=∑τpθ(τ) ∇θlog⁡pθ(τ) R(τ)=Eτ∼πθ[R(τ) ∇θlog⁡pθ(τ)]\nabla_\theta J = \sum_\tau \nabla_\theta p_\theta(\tau)\, R(\tau) = \sum_\tau p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau)\, R(\tau) = \mathbb{E}_{\tau \sim \pi_\theta}\big[ R(\tau)\, \nabla_\theta \log p_\theta(\tau) \big]

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 ∇θlog⁡πθ\nabla_\theta \log \pi_\theta is called the score function, and this is also known as the likelihood-ratio method.

What is log⁡pθ(τ)\log p_\theta(\tau)? The probability of a trajectory is a product of the start-state probability, the policy's choices and the environment's transitions:

pθ(τ)=p(S0)∏tπθ(At∣St) p(St+1∣St,At)p_\theta(\tau) = p(S_0) \prod_t \pi_\theta(A_t \mid S_t)\, p(S_{t+1} \mid S_t, A_t)

Taking the log turns the product into a sum, and only the policy terms depend on θ\theta. The environment's dynamics drop out of the gradient entirely:

∇θlog⁡pθ(τ)=∑t∇θlog⁡πθ(At∣St)\nabla_\theta \log p_\theta(\tau) = \sum_t \nabla_\theta \log \pi_\theta(A_t \mid S_t)

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 tt 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, GtG_t. 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 tt:

θ←θ+α γt Gt ∇θlog⁡πθ(At∣St)\theta \leftarrow \theta + \alpha\, \gamma^t\, G_t\, \nabla_\theta \log \pi_\theta(A_t \mid S_t)

The factor γt\gamma^t 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: ∇J(θ)∝∑sμ(s)∑aqπ(s,a) ∇θπθ(a∣s)\nabla J(\theta) \propto \sum_s \mu(s) \sum_a q_\pi(s, a)\, \nabla_\theta \pi_\theta(a \mid s), where μ(s)\mu(s) is how often the policy visits state ss. REINFORCE uses the sampled return GtG_t as an unbiased estimate of qπ(St,At)q_\pi(S_t, A_t).

A softmax policy, worked by hand

For discrete actions, a policy network outputs one score (logit) h(s,a)h(s, a) per action and turns them into probabilities with a softmax:

πθ(a∣s)=eh(s,a)∑beh(s,b)\pi_\theta(a \mid s) = \frac{e^{h(s, a)}}{\sum_b e^{h(s, b)}}

The gradient of log⁡π\log \pi with respect to the logits is beautifully simple: 1 for the action taken, minus the probability of each action. That is, ea−π\mathbf{e}_a - \boldsymbol{\pi}, where ea\mathbf{e}_a is a one-hot vector.

Worked example (the figure above). Three actions, all logits 0, so π=(13,13,13)\boldsymbol{\pi} = (\tfrac13, \tfrac13, \tfrac13). The agent took → and the return was 2 above average. With α=0.1\alpha = 0.1:

  • Gradient of log⁡π(→)\log \pi(\rightarrow): (0,0,1)−(13,13,13)=(−13,−13,+23)(0, 0, 1) - (\tfrac13, \tfrac13, \tfrac13) = (-\tfrac13, -\tfrac13, +\tfrac23)
  • Update: 0.1×2×(−13,−13,+23)=(−0.067,−0.067,+0.133)0.1 \times 2 \times (-\tfrac13, -\tfrac13, +\tfrac23) = (-0.067, -0.067, +0.133)
  • New probabilities: softmax of (−0.067,−0.067,0.133)(-0.067, -0.067, 0.133) is (0.31,0.31,0.38)(0.31, 0.31, 0.38).

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 pp 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 p=2−2≈0.59p = 2 - \sqrt{2} \approx 0.59 and expected return −(6+42)≈−11.66-(6 + 4\sqrt 2) \approx -11.66.

-60 -40 -20 0 0 0.25 0.5 0.75 1 best: π(right) = 0.59 return −11.66 start: π(right) = 0.1 return −42.3 policy parameter: probability of choosing "right" J: expected return from the start Short corridor the controls are secretly reversed in one square, and the agent can't tell which. Deterministic policies fail: always-right and always-left never reach the goal (J → −∞). Policy gradient: climb J(θ) uphill, step by step (orange). It finds the best random policy, which a greedy value-based agent cannot represent.
Fig. 2 Expected return J for every value of the policy parameter in the short corridor, computed exactly by solving the Bellman equations. Starting from π(right) = 0.1 (return −42.3), gradient ascent climbs to the best stochastic policy, π(right) ≈ 0.59. A greedy value-based agent can only pick 0 or 1, where the return is −∞.

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 b(s)b(s) from the return:

θ←θ+α (Gt−b(St)) ∇θlog⁡πθ(At∣St)\theta \leftarrow \theta + \alpha\, \big(G_t - b(S_t)\big)\, \nabla_\theta \log \pi_\theta(A_t \mid S_t)

Any baseline that does not depend on the action leaves the expected gradient unchanged. That is because Ea[∇log⁡π(a∣s)]=∑a∇π(a∣s)=∇∑aπ(a∣s)=∇1=0\mathbb{E}_a[\nabla \log \pi(a \mid s)] = \sum_a \nabla \pi(a \mid s) = \nabla \sum_a \pi(a \mid s) = \nabla 1 = 0. 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 vπ(s)v_\pi(s). Learning that value with a second network is exactly what Actor-Critic Methods methods do, and Gt−v(St)G_t - v(S_t) is called the advantage.

In code

REINFORCE in NumPy on the short corridor. The policy is one parameter θ\theta with π(right)=σ(θ)\pi(\text{right}) = \sigma(\theta) (the sigmoid), so ∇θlog⁡π(right)=1−π(right)\nabla_\theta \log \pi(\text{right}) = 1 - \pi(\text{right}) and ∇θlog⁡π(left)=−π(right)\nabla_\theta \log \pi(\text{left}) = -\pi(\text{right}). It starts at a poor policy, π(right)≈0.1\pi(\text{right}) \approx 0.1.

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 π(right)≈0.1\pi(\text{right}) \approx 0.1 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, −∑tGtlog⁡πθ(At∣St)-\sum_t G_t \log \pi_\theta(A_t \mid S_t), 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 JJ, minimise −J-J. 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 GtG_t 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 log⁡π\log \pi 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

  1. Change the starting parameter to theta = 2.2 (π(right) ≈ 0.9). Does REINFORCE still find 0.59? Watch how the early returns compare.
  2. Raise the step size to 2**-6. What happens to the learning curve, and why might a single unlucky episode cause it?
  3. Add the constant baseline to the training loop: subtract the running average of G[0] from G before the update. Does the curve improve at alpha = 2**-10? At 2**-8?

Hint for 2: episodes from a poor policy can last hundreds of steps, so np.sum(G * grad_log_pi) can be enormous.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In REINFORCE, an action is followed by a return that is much better than usual. What happens to that action's probability in that state?

  2. Why don't policy gradients need a model of how the environment works?

  3. Subtracting a baseline b(s) from the return leaves the expected gradient unchanged. What does it change?

  4. In the short corridor, the observation is the same in every square. Why can policy gradients beat every value-based greedy agent there?

  5. During PyTorch training of a policy gradient, the 'loss' value goes up while average episode return improves. What should you conclude?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tutorial

Spinning Up in Deep RL

Joshua Achiam (OpenAI) · 2018 · Intermediate · Free

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.

Article

Deep Reinforcement Learning: Pong from Pixels

Andrej Karpathy · 2016 · Intermediate · Free

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.

Article

Policy Gradient Algorithms

Lilian Weng · 2018 · Advanced · Free

The policy-gradient family in one place, from REINFORCE and actor-critic to A3C, TRPO, PPO and SAC, with consistent notation and derivations.

Course

Hugging Face Deep RL Course

Hugging Face · Intermediate · Free

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