Skip to content
intermediate

Deriving the Policy Gradient: From Expected Return to a Practical Estimator

The REINFORCE update looks like a magic trick: multiply a log-probability by a return, add it to the parameters, and hope the policy improves. It is not a…

Published 2026-10-02Updated 2026-10-0410 min read
A mesmerizing view of a school of fish captured underwater with a smartphone.
A mesmerizing view of a school of fish captured underwater with a smartphone. Photo by isaac mijangos on Pexels.

The REINFORCE update looks like a magic trick: multiply a log-probability by a return, add it to the parameters, and hope the policy improves. It is not a trick. It is what falls out when you differentiate an expectation you cannot differentiate directly.

If you already understand why stochastic policies matter and how sampled outcomes push action probabilities around, this article fills in the missing middle. We take the expected-return objective, differentiate it honestly, and arrive at the estimator you actually compute. The point is not to recite a formula. The point is to make every term in the update do a job you can name.

Why You Cannot Just Differentiate the Return

Start with the target. We want to maximize the expected return of a parameterized policy:

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

Here θ\theta is the parameter vector, τ\tau is a trajectory, and R(τ)R(\tau) is its return. The expectation runs over trajectories sampled by executing the policy in the environment.

The obstacle is structural. The parameter θ\theta sits inside the distribution you are averaging over, not inside the return. The environment decides rewards and transitions; it has no idea θ\theta exists. Differentiate a sampled return with respect to θ\theta and you get zero. The reward did not change because you nudged a weight in your network. The trajectory did.

You also never observe J(θ)J(\theta) directly. You observe sampled trajectories and their returns. Any usable gradient must therefore be expressible as an expectation itself, so a sample mean can estimate it. That is the whole game: turn the gradient of an expectation into an expectation of something computable.

Notation: Policy, Trajectory, Return, Objective

Before the algebra, fix the symbols.

The policy πθ(a∣s)\pi_\theta(a \mid s) is a distribution over actions given a state, parameterized by θ\theta. It is the only object we control. Everything else — the environment's dynamics, the reward function, the initial state distribution — is fixed and independent of θ\theta.

A trajectory τ=(s0,a0,s1,a1,… )\tau = (s_0, a_0, s_1, a_1, \dots) is a sequence of states and actions. Its probability factors into three kinds of terms:

p(τ∣θ)=ρ0(s0)∏t=0TP(st+1∣st,at) πθ(at∣st)p(\tau \mid \theta) = \rho_0(s_0) \prod_{t=0}^{T} P(s_{t+1} \mid s_t, a_t) \, \pi_\theta(a_t \mid s_t)

The initial-state term ρ0(s0)\rho_0(s_0) and the transition term P(st+1∣st,at)P(s_{t+1} \mid s_t, a_t) belong to the environment. Only the policy terms carry θ\theta.

The return R(τ)R(\tau) is the sum of rewards along the trajectory. Two conventions are common: finite-horizon undiscounted, R(τ)=∑t=0TrtR(\tau) = \sum_{t=0}^{T} r_t, and infinite-horizon discounted, R(τ)=∑t=0∞γtrtR(\tau) = \sum_{t=0}^{\infty} \gamma^t r_t. The derivation is nearly identical for both. I use the finite-horizon form to keep the notation light and note where discounting would slot in.

The objective is J(θ)=Eτ∼πθ[R(τ)]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)], and we want ∇θJ(θ)\nabla_\theta J(\theta).

Knowledge check

Check your understanding

Answer this question before you continue.

In the article’s trajectory-probability factorization, which terms carry dependence on θ?
Single Choice

Focus: Identify which factors in a trajectory probability depend on policy parameters.

The Log-Derivative Trick, Step by Step

Four connected stages show the objective as expected trajectory return, its gradient rewritten using the log-probability score, the trajectory score expanded into a sum of per-step policy scores, and the expectation approximated by a sample mean weighted by each trajectory's return.
Follow how the likelihood-ratio identity turns an expectation over trajectories into the per-step estimator used in REINFORCE.

Write the expectation as a sum over trajectories:

∇θJ(θ)=∇θ∑τp(τ∣θ)R(τ)\nabla_\theta J(\theta) = \nabla_\theta \sum_\tau p(\tau \mid \theta) R(\tau)

Push the gradient inside the sum. The return does not depend on θ\theta, so it passes through untouched:

=∑τR(τ) ∇θp(τ∣θ)= \sum_\tau R(\tau) \, \nabla_\theta p(\tau \mid \theta)

Now the useful move. Multiply and divide by p(τ∣θ)p(\tau \mid \theta):

=∑τp(τ∣θ) R(τ) ∇θp(τ∣θ)p(τ∣θ)= \sum_\tau p(\tau \mid \theta) \, R(\tau) \, \frac{\nabla_\theta p(\tau \mid \theta)}{p(\tau \mid \theta)}

The fraction is the score function. Apply the identity ∇θlog⁡z=1z∇θz\nabla_\theta \log z = \frac{1}{z} \nabla_\theta z with z=p(τ∣θ)z = p(\tau \mid \theta):

=∑τp(τ∣θ) R(τ) ∇θlog⁡p(τ∣θ)= \sum_\tau p(\tau \mid \theta) \, R(\tau) \, \nabla_\theta \log p(\tau \mid \theta)

Collapse the sum back into an expectation:

∇θJ(θ)=Eτ∼πθ[R(τ) ∇θlog⁡p(τ∣θ)]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[ R(\tau) \, \nabla_\theta \log p(\tau \mid \theta) \right]

This is the likelihood-ratio form, and it is the hinge of the entire derivation. The gradient is now an expectation of something you can compute from sampled trajectories. The probability density has been converted into a log-probability gradient, which is far easier to work with.

Knowledge check

Check your understanding

Answer this question before you continue.

After multiplying and dividing each term by p(τ | θ), what does ∇θp(τ | θ) / p(τ | θ) become?
Comparison Reasoning

Focus: Explain how the likelihood-ratio identity rewrites the derivative of a trajectory probability.

From Trajectory Probability to Per-Step Log-Probabilities

The expression above is still about whole trajectories. To make it implementable, decompose the log-probability.

Take the log of the trajectory probability:

log⁡p(τ∣θ)=log⁡ρ0(s0)+∑t=0Tlog⁡P(st+1∣st,at)+∑t=0Tlog⁡πθ(at∣st)\log p(\tau \mid \theta) = \log \rho_0(s_0) + \sum_{t=0}^{T} \log P(s_{t+1} \mid s_t, a_t) + \sum_{t=0}^{T} \log \pi_\theta(a_t \mid s_t)

Differentiate with respect to θ\theta. The initial-state term and every transition term are environment functions with no θ\theta dependence, so their gradients are zero. Only the policy terms survive:

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

Substitute this back:

∇θJ(θ)=Eτ∼πθ[R(τ)∑t=0T∇θlog⁡πθ(at∣st)]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[ R(\tau) \sum_{t=0}^{T} \nabla_\theta \log \pi_\theta(a_t \mid s_t) \right]

This is where the derivation stops being about trajectories and starts being about individual state-action pairs. The environment terms dropped out because they carry no parameter dependence. What remains is a sum of per-step log-probability gradients, each weighted by the return of the trajectory it came from.

Knowledge check

Check your understanding

Answer this question before you continue.

When differentiating the log trajectory probability with respect to θ, why does it reduce to a sum of per-step policy log-probability gradients?
Misconception Check

Focus: Derive the per-step score expression by identifying which trajectory log-probability terms have nonzero parameter gradients.

The Estimator You Actually Compute

Replace the expectation with a sample mean over NN collected trajectories:

∇θJ(θ)≈1N∑i=1N∑t=0T∇θlog⁡πθ(ai,t∣si,t) R(τi)\nabla_\theta J(\theta) \approx \frac{1}{N} \sum_{i=1}^{N} \sum_{t=0}^{T} \nabla_\theta \log \pi_\theta(a_{i,t} \mid s_{i,t}) \, R(\tau_i)

This is the REINFORCE estimator. It is unbiased: its expectation equals the true policy gradient. It is also high variance, and the reasons are worth naming.

Three assumptions are baked in:

  • The policy is differentiable in θ\theta. If you cannot take ∇θlog⁡πθ(a∣s)\nabla_\theta \log \pi_\theta(a \mid s), the estimator does not exist.
  • Actions are sampled from the current policy. This is an on-policy estimator. Reusing data from an older policy requires importance sampling, which changes the estimator.
  • Enough trajectories are collected for the sample mean to be meaningful. A single trajectory gives a noisy, possibly misleading estimate.

The variance problem has a specific shape. The raw return R(τ)R(\tau) weights every action in the trajectory equally, including actions taken long before the reward arrived. An action that happened to precede a lucky reward gets credit it did not earn. Two standard refinements address this without changing the expectation:

Reward-to-go replaces R(τ)R(\tau) with the sum of rewards from timestep tt onward. Actions before a reward no longer receive credit for it. The estimator stays unbiased because the discarded terms have zero expectation under the policy.

Baselines subtract a state-dependent value b(st)b(s_t) from the return weight. Any baseline that does not depend on the action leaves the expectation unchanged, but a good baseline — typically a learned value function — reduces variance substantially. This is the seed of actor-critic methods, though the full machinery is a separate topic.

Worked Example: Reading the Update

Make it concrete. Suppose a single state with two actions, a1a_1 and a2a_2. The policy is a softmax over two logits, and the current probabilities are πθ(a1∣s)=0.7\pi_\theta(a_1 \mid s) = 0.7 and πθ(a2∣s)=0.3\pi_\theta(a_2 \mid s) = 0.3.

For a softmax policy, the score ∇θlog⁡πθ(a∣s)\nabla_\theta \log \pi_\theta(a \mid s) points in the parameter-space direction that increases the probability of the sampled action and decreases the others. The return scales that direction. Both facts are local to the current parameters and the sampled action — they describe one gradient-ascent contribution, not a global law about how the policy will move after many updates.

Now sample. Suppose the agent takes a1a_1 and receives a return of +2+2. The update adds a positive multiple of the score for a1a_1, so this single contribution pushes π(a1)\pi(a_1) upward. Suppose instead the agent takes a1a_1 and receives a return of −1-1. The update subtracts, and this contribution pushes π(a1)\pi(a_1) downward.

Sampled actionReturnLocal effect on π(a1)\pi(a_1)
a1a_1+2+2Pushes up
a1a_1−1-1Pushes down
a1a_100Nearly unchanged

The third row is the quiet one. When the return is near zero, the update nearly vanishes. This is why sparse-reward problems learn slowly: most sampled trajectories carry almost no signal, and the gradient has almost nothing to scale.

Two qualifications matter here, because they are easy to overread.

First, the sign of a raw return is only meaningful relative to the reward origin. A return of +2+2 is not automatically "good" if the environment hands out +10+10 for doing nothing. What the update actually reinforces is the sampled action relative to the other actions the policy could have taken — and that relative comparison is what a baseline or advantage estimate makes explicit. With an uncentered return, the sign is a statement about the reward scale, not a verdict on action quality.

Second, with shared parameters across states and actions, a single update does not move only the sampled action's probability. The score for one state-action pair is a direction in the full parameter vector, and that direction can shift probabilities elsewhere. The clean two-logit picture is a teaching device, not a promise about every network.

The single most useful thing to carry away: the score supplies the direction; the return supplies the weight. The policy does not learn what to do from the return. It learns how much to reinforce what it already sampled.

Knowledge check

Check your understanding

Answer this question before you continue.

In the worked two-action softmax example, the agent samples a1 and obtains return +2. What does this single gradient-ascent contribution do locally to π(a1 | s)?
Scenario Interpretation

Focus: Interpret the local effect of a return-weighted score contribution in the article’s two-action softmax example.

Where the Derivation Stops Being Exact

The derivation is clean, but its assumptions have edges.

It assumes a stochastic, differentiable policy. Deterministic policies need a different route, because the log-probability of a deterministic action is not a well-behaved function of θ\theta.

It assumes on-policy sampling. The moment you reuse trajectories from an older policy, the expectation is over the wrong distribution, and you need importance sampling to correct it. That correction is not free — it adds its own variance.

The unbiasedness claim is about the expectation, not about any single batch. A high-variance estimator can produce individual updates that point the wrong way. A correct gradient in expectation is not a correct gradient on your one noisy batch.

Finally, the derivation says nothing about step size. A perfectly computed gradient can still produce a destructive update if the learning rate is too large. The gradient tells you the direction of steepest ascent locally; it does not tell you how far to walk.

What to Do With This

When you see a policy-gradient update in code or a paper, read it in two parts. First, find the log-probability term — that is the direction, and it points toward increasing the probability of what was sampled. Second, find the return or advantage term — that is the weight, and it decides whether the direction is reinforced or reversed.

Then check the sampling assumption. Is the implementation on-policy? Does it reuse old data? If so, where does the importance-sampling correction appear?

The natural next step is to implement the estimator on a small environment — a two-action bandit or a tiny gridworld — and watch the action probabilities move after each update. Print the log-probability, the return, and the resulting parameter change. The formula stops being abstract the moment you see a positive return nudge a probability upward and a negative return pull it back down.

Once that runs, variance reduction is the next topic worth your time. Reward-to-go and baselines are the first tools, and they are where the gap between the textbook estimator and a usable one starts to close.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

An implementation reuses trajectories collected by an older policy but applies the ordinary REINFORCE estimator unchanged. Which issue does the article identify?
Question 1 of 2Scenario Interpretation

Focus: Recognize why trajectories from an older policy cannot be used as the ordinary on-policy estimator without correction.

Which baseline use matches the article’s condition for preserving the expected policy gradient while aiming to reduce variance?
Question 2 of 2Comparison Reasoning

Focus: State the condition under which a baseline can reduce estimator variance without changing the expected policy gradient.

References

  1. Part 3: Intro to Policy Optimization — Spinning Up documentationspinningup.openai.com
Practical resource

Build a stronger RL mental model

Use structured resources to connect equations, algorithms, and observable agent behavior.

Browse resources
Related sites

Continue across related AI foundations

Use LearnPyFast for Python foundations and LearnLLMFast for practical language-model and agent application concepts.

Python tutorialstutorial

LearnPyFast

Beginner-friendly Python tutorials, examples, and learning paths for practical programming foundations.

PythonProgrammingBeginners
Visit LearnPyFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related reinforcement learning tutorials

Continue with nearby RL concepts, algorithms, and experiments that build on the same decision process.