Until now the agent has been scoring moves and picking the highest. Policy gradients flip the script, the agent directly learns a strategy and adjusts it based on outcomes. Robots learn continuous motion this way. ChatGPT gets fine-tuned this way. The log-probability trick at the heart of REINFORCE is the same gradient that trains modern RLHF.
After this lesson, you will be able to:
Understand why policy gradient methods are needed: value-based methods cannot handle continuous or stochastic action spaces, but learning the policy directly can
Follow the REINFORCE algorithm and the log-probability gradient trick: ∇J(θ) = E[∇ log π(a|s) · G_t], which converts the unmathematical "do more of what works" intuition into a differentiable gradient
Understand why raw REINFORCE has high variance (single-episode Monte Carlo estimates) and how baselines and advantage functions reduce it without introducing bias
See how actor-critic combines the best of value-based and policy-gradient methods: the critic provides low-variance advantage estimates, the actor learns the policy directly
Before we flip the script: recall from the Q-learning lesson, write down (a) the Bellman update for Q(s,a) in one line, (b) what 'argmax over actions' is doing geometrically, and (c) one specific kind of action space where this argmax falls apart. Once you've committed an answer, the motivation for policy gradients below will land much harder.
Write your answer in your own words — don't look back at the lesson. This is the most effective way to remember what you just learned.
Everything we have seen so far (Q-learning, DQN) learns a value function (Q or V) and derives a policy from it (pick the action with the highest value). This is the value-based approach.
Policy gradient methods flip this around: they learn the policy directly. Instead of asking "how valuable is each action?", they ask "what is the probability of each action, and how should I adjust those probabilities to get more reward?"
Why learn a policy directly?
Continuous actions: DQN outputs Q-values for discrete actions. But what if the action is a continuous steering angle, a robot joint torque, or a continuous token probability? You cannot take a max over infinite actions. Policy gradients output continuous action distributions naturally.
Stochastic policies: Sometimes the optimal policy is stochastic (mixed strategies in games like rock-paper-scissors). Value-based methods produce deterministic policies (always pick the max). Policy gradients naturally represent probability distributions over actions.
Simpler representation: In some problems, the optimal policy is simpler than the optimal value function. A policy might just be "go toward the goal," while the value function encodes complex contours of expected return across the state space.
Better convergence properties: Policy gradients update the policy smoothly (small changes to parameters = small changes to action probabilities). Value-based methods can have discontinuous policy changes when Q-value rankings shift.
Before the maths, see both ideas side by side on one small grid. The left agent reads a stored arrow in each cell. The right agent steps toward the neighbouring cell with the higher value.
Try it: Policy versus valueInteractive
Press Auto-play and watch both agents cross the grid. Then break one arrow and run them again.
Loading visualization...
Do: Press Auto-play and let both agents reach the goal. Then press Inject a bad arrow, which reverses the arrow in the top row at cell (0, 2), and press Auto-play again.
Notice: In the clean run both agents take the same number of steps. After the bad arrow, the policy agent steps onto that cell, is sent back, and loops until its counter shows stuck. The value agent still reaches the goal.
Why: A policy is a table of instructions, so one wrong entry is followed blindly. A value map scores every cell, and the agent compares neighbours. Drawn stand-in, not a trained model: both tables are computed exactly in advance and nothing here is learned. Learned value estimates can also be wrong.
A policy network takes a state as input and outputs a probability distribution over actions:
πθ(a∣s)=P(At=a∣St=s;θ)
The goal is to maximize the expected return:
J(θ)=Eτ∼πθ[t=0∑TγtRt+1]
The policy gradient theorem tells us how to compute the gradient of J with respect to theta:
∇θJ(θ)=Eτ∼πθ[t=0∑T∇θlogπθ(At∣St)⋅Gt]
Try it! Imagine you played 3 episodes of a game. Episode 1: you went left and scored +10. Episode 2: you went right and scored -5. Episode 3: you went left and scored +8. What should you adjust? Increase the probability of going left (it led to positive outcomes) and decrease the probability of going right (negative outcome). That is exactly what the equation above does mathematically.
This is the most important equation in policy gradient methods. Let us unpack it:
log pi_theta(A_t|S_t): The log-probability of the action actually taken. Its gradient tells us how to nudge the parameters to make this action more likely.
G_t: The return (total discounted reward) from time step t onward. This tells us whether the action was good or bad.
The product: If the return was positive (good outcome), increase the probability of the action. If negative, decrease it. The magnitude of the return scales the update.
Where this formula comes from is shown step by step in the collapsible derivations under "Deriving the policy gradient theorem" below.
What Do You Think?
In REINFORCE, if an action leads to a return of 0, what happens to that action's probability?
If the return is exactly 0, the gradient contribution is zero, the action probability does not change. In practice, returns are rarely exactly zero, and using a baseline (subtracting the average return) means a return of 0 would actually decrease the probability if the average return is positive.
The equation above is the punchline. Below is the derivation that earns it, one collapsible derivation per result, so open only the ones you want. We work in a discounted Markov decision process with states s, actions a, transition probabilities P(s' | s, a), reward R(s, a) and discount gamma between 0 and 1 (the setting of the Markov Decision Processes lesson).
The agent acts with a parameterized stochastic policy pi_theta(a | s). A trajectory τ=(s0,a0,r0,s1,a1,r1,…) starts from s_0 drawn from a start distribution rho, then repeats: draw a_t from pi_theta(. | s_t), collect r_t = R(s_t, a_t), draw s_(t+1) from P(. | s_t, a_t). The objective is the expected discounted return:
J(θ)=Eτ∼πθ[t=0∑∞γtrt]=∫R(τ)pθ(τ)dτ
Every numeric check below uses one toy MDP. It has two states and two actions. From each pair (state, action) the chance that the next state is state 0 is 0.8, 0.3, 0.5, 0.1 for the pairs (0,0), (0,1), (1,0), (1,1). The rewards R(s, a) for those four pairs are 1, 0, 0, 2. Episodes start in state 0, the policy is a softmax over a 2 by 2 table of logits theta = [[0.3, -0.2], [0.1, 0.4]], and gamma = 0.9. When a check says "horizon 3" it means three decisions per episode, small enough to list every trajectory.
First the identity that makes policy gradients possible: the gradient of an average can be written as an average, which we can sample.
The log-derivative trick says that for any density p(x; theta) that is differentiable in theta and any function f that does not depend on theta, the gradient of the expectation of f equals the expectation of f times the gradient of log p:
∇θEX∼pθ[f(X)]=EX∼pθ[f(X)∇θlogp(X;θ)]
The quantity nabla log p is called the score, and its expectation under p is always zero (the Fisher lesson, MLE, MAP & Fisher Information, derives it). It is the same score that drives maximum likelihood.
Next, apply the trick to a whole trajectory. The trajectory probability is a product of start, policy and transition terms, and the key fact is that only the policy terms depend on theta:
∇θlogpθ(τ)=t=0∑∞∇θlogπθ(at∣st)
Combining the two identities, with f equal to the trajectory return R(tau) = sum_t gamma^t r_t, gives the canonical policy gradient:
∇θJ(θ)=Eτ∼πθ[R(τ)⋅t=0∑∞∇θlogπθ(at∣st)]
The same scalar R(tau) multiplies every step, so the first action is credited with rewards it could never have caused. Causality removes that. A reward at time k cannot depend on actions taken after k, so in expectation it contributes nothing to the score of a later action. We keep only the return-to-go G_t, the discounted sum of rewards from time t on, and get the REINFORCE estimator of Williams (1992):
∇θJ(θ)=Eτ∼πθ[t=0∑∞γt⋅Gt⋅∇θlogπθ(at∣st)]
The gamma to the power t in front of each term is part of the exact discounted gradient. Implementations usually drop it; see the common-mistake box below.
The same gradient can be written by state instead of by trajectory. Let d(s) = sum over t of gamma^t times the probability of being in state s at time t (the discounted visitation of s; it sums to 1/(1 - gamma)). Then the policy gradient theorem says:
A baseline b(s) that depends only on the state can be subtracted from G_t (or from Q) without changing the expected gradient:
E[b(st)⋅∇θlogπθ(at∣st)∣st]=0
The baseline does change the variance of a sampled estimate. Write psi for the score of the action taken (a vector) and G for the return weight. The baseline that minimises the variance is the score-squared-weighted average return:
b∗(s)=E[∥∇θlogπθ(a∣s)∥2]E[∥∇θlogπθ(a∣s)∥2G]
Drag the baseline b (or use the snap buttons) and watch the histogram on this toy bandit with rewards 4, 6 and 10, a separate example from the numbers 6.2965, 1.0247 and 0.7412 above: the true gradient stays the same for every b while the spread of single-sample estimates changes, huge at b = 0, small near the average reward and smallest at b*.
Loading visualization...
In practice nobody computes b*; the canonical choice is the state value V(s), which is close to it, easy to learn with a second network, and gives the advantage A(s, a) = Q(s, a) - V(s). The actor-critic lesson (Actor-Critic Methods: A2C, A3C, and IMPALA) learns that value function and derives the TD advantage and GAE from it.
What Do You Think?
Suppose we subtract a baseline b(s_t, a_t) that depends on BOTH state AND action. Is the resulting policy gradient still unbiased?
Both result formulas below are the score nabla log pi that every estimator above multiplies by a weight. For a softmax over action preferences h(s, a) = theta . phi(s, a), with features phi(s, a), the policy is pi(a | s) = exp(h(s,a)) divided by the sum over b of exp(h(s,b)) (Sutton and Barto, section 13.1), and its score is the feature of the action taken minus the average feature under the policy:
∇θlogπθ(a∣s)=ϕ(s,a)−b∑πθ(b∣s)ϕ(s,b)
For continuous actions the standard choice is a Gaussian with mean mu(s) = theta . phi(s) and standard deviation sigma. Its score for the mean parameters is:
∇θlogπθ(a∣s)=σ2a−μ(s)ϕ(s)
#Why the variance of REINFORCE grows with the horizon
The estimator has no bias, so all its trouble is variance, and the variance grows with episode length. The cleanest way to see it is a deliberately simple model. Suppose each of T steps has an independent score with mean 0 and variance sigma^2, and an independent reward with mean 0 and variance 1, with rewards unaffected by the actions. Then the true gradient is 0, so every bit of the estimate is noise:
Var[g^full]=σ2T2,Var[g^to-go]=σ22T(T+1)
Real problems add a baseline and use discounting, which shrinks the effective horizon, but the growth with horizon is why long-horizon tasks need the variance-reduction tools of the Actor-Critic Methods: A2C, A3C, and IMPALA lesson, where the TD advantage and GAE are derived.
To keep a policy from becoming deterministic too early, a bonus beta times the entropy H of the policy is added to the objective. At one state the gradient of that entropy is:
When actions are continuous, a policy can output one action instead of a distribution: a = mu_theta(s). There is no density to take the log of, so the score-function trick does not apply. Instead the gradient flows through the action by the chain rule (Silver et al. 2014; Lillicrap et al. 2016 use it in DDPG):
The plain gradient measures a step in parameter distance, but what matters is how far the action distribution moves. The natural policy gradient (Kakade, A natural policy gradient, NIPS 14) multiplies the policy gradient by the inverse Fisher information matrix of the policy:
The derivation of the natural gradient as steepest ascent under a KL-distance constraint, giving the step proportional to the inverse Fisher matrix times the gradient, is in the MLE, MAP & Fisher Information lesson. Apply it with the loss replaced by minus J. The KL divergence itself is introduced in Information Theory & Entropy.
The trust-region idea behind TRPO and PPO is the same: a gradient step is a first-order guess that is only trustworthy for small changes of the policy, so cap the KL divergence between the old and new policy at a small number. That bound and the clipped objective are derived in the Proximal Policy Optimization lesson.
Williams (1992) gave the original score-function argument for REINFORCE. Sutton, McAllester, Singh and Mansour (2000) gave the formal Policy Gradient Theorem (Sutton and Barto, 2nd ed., chapter 13). The remaining piece of the modern recipe, the generalized advantage estimator GAE, is derived in Actor-Critic Methods: A2C, A3C, and IMPALA.
Initialize the policy network with random weights. The network takes a state as input and outputs a probability distribution over actions. For discrete actions, this is a softmax layer. For continuous actions, it outputs the mean and standard deviation of a Gaussian.
At initialization, the policy is essentially random, it assigns roughly equal probability to all actions regardless of state. The agent has no idea what to do.
The agent runs a complete episode using the current policy. At each time step, it samples an action from the policy distribution, executes it, and records the state, action, and reward. The episode produces a full trajectory: (s0, a0, r1, s1, a1, r2, ..., sT).
REINFORCE requires complete episodes, it cannot update mid-episode. This is a Monte Carlo method: it waits for the final outcome before learning.
Working backward from the end of the episode, compute the discounted return at each time step: G_t = r_ + gamma * r_ + gamma^2 * r_ + ... The return at each step tells us the total future reward from that point onward.
Steps that led to high cumulative reward will have high G_t. Steps that led to poor outcomes will have low G_t. This is the "scorecard" for every action in the episode.
For each time step, compute the gradient of log pi(a_t | s_t), the log-probability of the action actually taken. Multiply it by the return G_t. This gives the policy gradient: actions that led to high returns get their probabilities increased, and actions that led to low returns get decreased.
The log-probability trick converts the problem into a form amenable to standard backpropagation. The magnitude of G_t scales how strongly each action is reinforced or punished.
Sum up the per-step gradients across the entire episode and perform a gradient ascent step. The policy parameters theta shift to make high-return actions more probable and low-return actions less probable.
This is gradient ascent, not descent, we are maximizing expected reward. In practice, the loss is negated so standard optimizers (which minimize) can be used: loss = -sum(log_prob * G_t).
Discard the episode data and run a new episode with the updated policy. The new policy is slightly better, it tends to take actions that worked well in previous episodes and avoids actions that led to poor outcomes.
Over hundreds or thousands of episodes, the policy converges toward optimal behavior. Each episode provides a noisy but unbiased estimate of the gradient. Averaging over many episodes smooths out the noise.
Loading visualization...
Try it: Watch the Policy ShiftInteractive
See how a policy gradient agent adjusts its action distribution over time. The policy starts uniform (equal probability for all directions), and as the agent collects trajectories, it gradually shifts probability mass toward actions that lead to higher returns. Watch the probability arrows grow and shrink in real time.
REINFORCE works in theory but has a critical practical issue: high variance. The return G_t is a noisy, Monte Carlo estimate. It depends on the entire future trajectory, which includes randomness from the policy, the environment, and the episode length. This noise makes the gradient estimates wildly variable, causing slow and unstable learning.
The key insight for reducing variance: subtract a baseline b(s) from the return. This does not change the expected gradient (it remains unbiased) but can dramatically reduce variance:
∇θJ(θ)=E[t=0∑T∇θlogπθ(At∣St)⋅(Gt−b(St))]
The best baseline is the value function V(s), the expected return from state s. This gives us the advantage:
Try it: See how subtracting a baseline changes the gradient signalInteractive
Actor-critic methods combine policy gradients with value function learning. Two networks work together:
Actor: The policy network: chooses actions
Critic: The value network: evaluates how good the current state is
The critic provides the baseline for the actor, reducing variance. The actor provides the behavior for the critic to evaluate.
Actor update: θ←θ+αθ∇θlogπθ(At∣St)⋅A^tCritic update: w←w−αw∇w(Gt−Vw(St))2where A^t=Rt+1+γVw(St+1)−Vw(St)
The advantage estimate A-hat_t = R + gamma * V(s') - V(s) is called the TD error. It uses one step of actual reward and then bootstraps off the value estimate, balancing bias and variance:
REINFORCE (Monte Carlo): Low bias, high variance: waits for the full episode
TD Actor-Critic: Some bias (from the value estimate), much lower variance: updates after each step
n-step Actor-Critic: Adjustable tradeoff: uses n real steps before bootstrapping
Tests: Verify that after training, P(action 1) > 0.8. Implement the baseline version and verify it converges faster (higher P(action 1) after 500 episodes).
Policy gradients learn the policy directly. Instead of estimating values and deriving actions, policy gradient methods directly optimize the probability of taking good actions, enabling handling of continuous and stochastic action spaces
REINFORCE uses the log-probability trick. By multiplying the log-probability of actions by the return, high-return trajectories increase the probability of their actions while low-return ones decrease it
High variance is the main challenge. Raw policy gradients are extremely noisy because a single trajectory is a poor estimate of the expected return; baselines and advantage functions reduce this variance
Actor-critic combines value and policy learning. The actor learns the policy while the critic learns a value function; the advantage (reward minus baseline) provides low-variance gradient estimates while remaining unbiased
Interactive Lab
Toggle between a value-based agent (Q-table) and a policy-based agent (softmax over states) on the same task, see why policy gradients can express continuous and stochastic strategies that argmax-over-Q cannot.
What is the key advantage of policy gradient methods over value-based methods like DQN?
Policy gradients give us the ability to learn policies directly, but REINFORCE is too high-variance for complex problems. Next up: actor-critic methods, which pair the policy with a learned value function to cut that variance and learn from every step.