Skip to main content
The methods so far learn action values and act greedily, or ϵ\epsilon-greedily, with respect to them. This section learns the policy directly: a parameterized policy πθ(a∣s)\pi_\theta(a \mid s) is improved by gradient ascent on the expected return. The algorithm, REINFORCE (Williams, 1992), is the starting point of most policy-gradient methods, including the PPO and GRPO variants used to fine-tune language and vision-language models (see the browser-control GRPO tutorial). The name describes what the update does. Actions that led to good outcomes become more probable, so they are positively reinforced, and actions that led to bad outcomes become less probable. Over many updates the action probabilities shift toward a policy that performs well.

Why learn the policy directly

A parameterized policy has several advantages over a policy derived from action values (Sutton & Barto, 2018):
  • It can become deterministic, or stay stochastic, as the task requires. An ϵ\epsilon-greedy policy always takes random actions with probability ϵ\epsilon. A softmax policy can move its probabilities as close to 0 or 1 as the return rewards. When the best policy is stochastic, for example when two states look the same to the agent but need different actions, a policy-gradient method can learn it, and an action-value method that acts greedily cannot.
  • The policy can be simpler than the value function. In some tasks it is easier to describe what to do than how much each action is worth.
  • The policy changes smoothly. A small change of θ\theta changes the action probabilities a little. With action values, a small change of QQ can switch the greedy action and change the behavior abruptly. This smoothness is behind the convergence guarantees of policy-gradient methods.
  • Continuous actions are natural. The policy can output the parameters of a distribution over actions, such as the mean of a Gaussian, instead of maximizing over infinitely many actions.

The three components

The hard part is the gradient. The policy gradient theorem (Sutton & Barto, 2018) states that ∇θJ(θ)∝∑sμ(s)∑aqπθ(s,a) ∇θπθ(a∣s)=Eπθ[qπθ(St,At) ∇θlog⁡πθ(At∣St)],\begin{aligned} \nabla_\theta J(\theta) &\propto \sum_s \mu(s) \sum_a q_{\pi_\theta}(s, a)\, \nabla_\theta \pi_\theta(a \mid s) \\ &= \mathbb{E}_{\pi_\theta} [ q_{\pi_\theta}(S_t, A_t)\, \nabla_\theta \log \pi_\theta(A_t \mid S_t) ], \end{aligned} where μ(s)\mu(s) is the fraction of time the policy spends in state ss. The gradient needs no derivative of the state distribution μ\mu, which depends on the unknown dynamics. The rest of this section derives the same result for whole trajectories, step by step.

Deriving the policy gradient

The log-derivative trick

Take a function f(x)f(x) and a parameterized distribution p(x∣θ)p(x\mid\theta). The goal is the gradient of the expectation Ex∼p(x∣θ)[f(x)]\mathbb{E}_{x\sim p(x\mid\theta)}[f(x)], in a form that can be estimated from samples.
∇θEx∼p(x∣θ)[f(x)]  =  ∇θ∫f(x) p(x∣θ) dx\nabla_\theta \mathbb{E}_{x\sim p(x\mid\theta)}[f(x)] \;=\; \nabla_\theta \int f(x)\,p(x\mid\theta)\,dxExplanation: This uses the definition of an expectation under a density: E[f(x)]=∫f(x)p(x) dx.\mathbb{E}[f(x)] = \int f(x)p(x)\,dx.
=∫∇θ ⁣(f(x) p(x∣θ)) dx= \int \nabla_\theta\!( f(x)\,p(x\mid\theta) )\,dxExplanation: Under mild regularity conditions, differentiation and integration commute (Leibniz rule), allowing us to move ∇θ\nabla_\theta inside the integral.
=∫(f(x) ∇θp(x∣θ)  +  p(x∣θ) ∇θf(x)) dx= \int \big( f(x)\,\nabla_\theta p(x\mid\theta) \;+\; p(x\mid\theta)\,\nabla_\theta f(x) \big)\,dxExplanation: This applies the product rule to ∇θ(fp)\nabla_\theta(f p).
=∫f(x) ∇θp(x∣θ) dx= \int f(x)\,\nabla_\theta p(x\mid\theta)\,dxExplanation: We assume f(x)f(x) does not depend on θ\theta, so ∇θf(x)=0\nabla_\theta f(x)=0 and the second term vanishes. This is the standard situation in policy-gradient and score-function estimators: in our setting, ff is the return of the whole trajectory R(τ)R(\tau), which depends on the sampled trajectory but not directly on the policy parameters θ\theta. The θ\theta-dependence is captured by the distribution p(x∣θ)p(x \mid \theta) itself.
=∫f(x) p(x∣θ)  ∇θp(x∣θ)p(x∣θ) dx= \int f(x)\,p(x\mid\theta)\; \frac{\nabla_\theta p(x\mid\theta)}{p(x\mid\theta)}\,dxExplanation: Multiply and divide by p(x∣θ)p(x\mid\theta); this is valid whenever p(x∣θ)>0p(x\mid\theta)>0 on the support of interest.
=∫f(x) p(x∣θ)  ∇θlog⁡p(x∣θ) dx= \int f(x)\,p(x\mid\theta)\; \nabla_\theta \log p(x\mid\theta)\,dxExplanation: We use the log-derivative identity:∇θlog⁡p(x∣θ)=∇θp(x∣θ)p(x∣θ).\nabla_\theta \log p(x\mid\theta) = \frac{\nabla_\theta p(x\mid\theta)}{p(x\mid\theta)}.
=Ex∼p(x∣θ)[ f(x) ∇θlog⁡p(x∣θ) ]= \mathbb{E}_{x\sim p(x\mid\theta)} [\, f(x)\,\nabla_\theta \log p(x\mid\theta)\,]Explanation: We rewrite the integral back into expectation form.
The result turns the gradient of an expectation into an expectation of a quantity you can compute for each sample, even when ff is a black box without a gradient.

From trajectories to actions

In RL the random variable is a trajectory τ=(S0,A0,R1,S1,A1,R2,…,ST)\tau = (S_0, A_0, R_1, S_1, A_1, R_2, \dots, S_T), and ff is its return G0(τ)=∑t=0T−1γtRt+1G_0(\tau) = \sum_{t=0}^{T-1} \gamma^t R_{t+1}, so that J(θ)=Eτ∼πθ[G0(τ)]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[G_0(\tau)]. The probability of a trajectory factorizes into the start distribution, the policy and the dynamics: p(τ∣θ)=p(S0)∏t=0T−1πθ(At∣St) p(St+1,Rt+1∣St,At).p(\tau \mid \theta) = p(S_0) \prod_{t=0}^{T-1} \pi_\theta(A_t \mid S_t)\, p(S_{t+1}, R_{t+1} \mid S_t, A_t). Its logarithm is a sum, and only the policy terms depend on θ\theta: ∇θlog⁡p(τ∣θ)=∑t=0T−1∇θlog⁡πθ(At∣St).\nabla_\theta \log p(\tau \mid \theta) = \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(A_t \mid S_t). The dynamics drop out. The gradient needs the log-probabilities of the actions that were taken, which the agent computes itself, and never the transition probabilities of the environment. That is why REINFORCE is model-free. With the log-derivative trick, ∇θJ(θ)=Eτ∼πθ[G0(τ)∑t=0T−1∇θlog⁡πθ(At∣St)].\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta} \Bigl[ G_0(\tau) \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(A_t \mid S_t) \Bigr].

Reward-to-go

This estimator weights every action by the return of the whole episode, including rewards that arrived before the action was taken. Those rewards cannot depend on the action, and their contribution is zero in expectation. For a reward Rk+1R_{k+1} with k<tk < t, condition on everything up to StS_t: Rk+1R_{k+1} is then fixed, and the expected score of AtA_t is zero, because EAt∼πθ(⋅∣St)[∇θlog⁡πθ(At∣St)]=∑a∇θπθ(a∣St)=∇θ∑aπθ(a∣St)=∇θ1=0.\mathbb{E}_{A_t \sim \pi_\theta(\cdot \mid S_t)} \bigl[ \nabla_\theta \log \pi_\theta(A_t \mid S_t) \bigr] = \sum_a \nabla_\theta \pi_\theta(a \mid S_t) = \nabla_\theta \sum_a \pi_\theta(a \mid S_t) = \nabla_\theta 1 = 0. Dropping the earlier rewards leaves each action weighted by the rewards that follow it, ∑k≥tγkRk+1=γtGt\sum_{k \ge t} \gamma^k R_{k+1} = \gamma^t G_t: ∇θJ(θ)=Eτ∼πθ[∑t=0T−1γt Gt ∇θlog⁡πθ(At∣St)],Gt=∑k=0T−t−1γkRt+k+1.\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta} \Bigl[ \sum_{t=0}^{T-1} \gamma^t\, G_t\, \nabla_\theta \log \pi_\theta(A_t \mid S_t) \Bigr], \qquad G_t = \sum_{k=0}^{T-t-1}\gamma^k R_{t+k+1}. The expectation is unchanged. The variance is usually lower, because the dropped rewards add noise that the action did not cause, but this is not guaranteed: if an earlier reward happens to cancel part of the later return, dropping it can raise the variance. Because E[Gt∣St,At]=qπθ(St,At)\mathbb{E}[G_t \mid S_t, A_t] = q_{\pi_\theta}(S_t, A_t), this is the policy gradient theorem written for sampled trajectories. The Policy Gradient Minimal Examples measure both effects on a two-step task. The factor γt\gamma^t. The exact gradient of the discounted objective vπθ(s0)v_{\pi_\theta}(s_0) weights the update at time tt by γt\gamma^t, as Sutton and Barto’s REINFORCE does. Most implementations drop the factor and weight each action by GtG_t alone, which gives every time step equal weight. This page and the algorithm below follow that common simplification. It is exact for γ=1\gamma = 1, and for γ\gamma close to 1, such as 0.99, the two differ little over short episodes.

The softmax policy

For discrete actions the policy network outputs one preference, or logit, hθ(s,a)h_\theta(s, a) per action, and the policy is their softmax: πθ(a∣s)=ehθ(s,a)∑behθ(s,b).\pi_\theta(a \mid s) = \frac{e^{h_\theta(s,a)}}{\sum_b e^{h_\theta(s,b)}}. The score with respect to the preferences has a simple form: ∂log⁡πθ(a∣s)∂hθ(s,b)=1[a=b]−πθ(b∣s).\frac{\partial \log \pi_\theta(a \mid s)}{\partial h_\theta(s,b)} = \mathbb{1}[a = b] - \pi_\theta(b \mid s). The update raises the preference of the action taken, in proportion to 1−πθ(a∣s)1 - \pi_\theta(a \mid s), and lowers the others in proportion to their probabilities. Backpropagation carries this through the network to θ\theta. The scores are bounded, and an action that is already almost certain gets almost no further push. The Policy Gradient Minimal Examples work through the two-action case.

The algorithm

The expectation over trajectories is estimated with sampled episodes, a Monte Carlo estimate. Each update samples a trajectory with the current policy, computes the return GtG_t from every time step, and moves θ\theta along the sum of the weighted scores, without any knowledge of the transition or reward functions.
Algorithm: Monte Carlo Policy Gradient (REINFORCE)
REINFORCE on-policy Monte Carlo loop: rollout trajectory, compute returns, estimate policy gradient, update parameters, discard trajectory Editable Mermaid source: images/reinforce-loop.mermaid.md A trajectory is discarded after the update that uses it and is never reused. REINFORCE is an on-policy method, like Monte Carlo control. The update in line 10 uses the score of the current policy πθ\pi_\theta in line 8, and the returns in line 7 must come from trajectories generated by that same policy. Returns generated by another policy would adjust the action probabilities with outcomes that πθ\pi_\theta would not have produced.

Policy network

The policy network maps a state to one logit per action. Sampling an action and computing its log-probability takes four steps:
The loss for one episode is −∑tGtlog⁡πθ(at∣st)-\sum_t G_t \log \pi_\theta(a_t \mid s_t), and its gradient is the negative of the estimate gg above. For continuous actions the network outputs the parameters of a continuous distribution instead, such as the mean and standard deviation of a Gaussian.

Applying the REINFORCE algorithm

A runnable end-to-end implementation on the CartPole-v1 environment lives in its own section so you can train, inspect episode returns, and experiment with hyperparameters directly. It uses the same policy architecture described above and plots a learning curve. CartPole environment

REINFORCE on CartPole-v1

Runnable policy-gradient agent with a learning-curve plot, modernized for the current Gymnasium API.

Why the learning curve is not monotonic

Train the model above and the episode returns rise on average but oscillate sharply; bursts to the 500 ceiling are routinely followed by drops to 50 to 150. Monotonic improvement is not expected for vanilla REINFORCE. The reasons are structural:
  1. Gradient variance: a single trajectory is used per update. One lucky or unlucky episode dominates the gradient at that step.
  2. Uncentered returns: without a baseline, every action inside a good episode gets reinforced, including suboptimal ones. The gradient carries “absolute goodness,” not “advantage.”
  3. Unbounded step size: the per-step loss −log⁡πθ(a∣s) Gt-\log\pi_\theta(a\mid s)\, G_t scales with the return GtG_t. A lucky 500-return episode produces a gradient step many times larger than a typical one, and a single oversized update can overshoot the current good region of parameter space; the very next episode’s policy is then markedly worse. Later methods (e.g. PPO) explicitly cap how much the policy is allowed to change per update.
  4. On-policy non-stationarity: the trajectory distribution itself changes with θ\theta, so yesterday’s gradient is stale today.
  5. Stochastic policy at eval time: even a well-trained policy samples from πθ(⋅∣s)\pi_\theta(\cdot\mid s), so episode returns inherently fluctuate.
Each of these motivates a specific fix downstream of REINFORCE.

Reducing variance with a baseline

The first and simplest fix targets reasons 1 and 2 above: subtract a state-dependent baseline b(s)b(s) from the return: ∇θJ(θ)=Eτ∼πθ[∑t=0T−1(Gt−b(St))∇θlog⁡πθ(At∣St)]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta} \bigl[ \sum_{t=0}^{T-1} ( G_t - b(S_t) ) \nabla_\theta \log \pi_\theta(A_t \mid S_t) \bigr] A baseline that does not depend on the action leaves the gradient unbiased. The proof is the same zero-mean property of the score used for reward-to-go: EA∼πθ(⋅∣s)[b(s) ∇θlog⁡πθ(A∣s)]=b(s)∑a∇θπθ(a∣s)=b(s) ∇θ1=0.\mathbb{E}_{A \sim \pi_\theta(\cdot \mid s)} \bigl[ b(s)\, \nabla_\theta \log \pi_\theta(A \mid s) \bigr] = b(s) \sum_a \nabla_\theta \pi_\theta(a \mid s) = b(s)\, \nabla_\theta 1 = 0. It can, however, reduce the variance a lot. The most common choice is b(s)=v^(s)b(s) = \hat v(s), an estimate of the state value learned by a separate network. This is REINFORCE with baseline. The difference Gt−v^(St)G_t - \hat v(S_t) estimates the advantage of the action taken. The method is still not actor-critic: the learned value is used only as a baseline and never to bootstrap the target (Sutton & Barto, 2018). Actor-Critic Methods replace GtG_t with a bootstrapped target such as Rt+1+γv^(St+1)R_{t+1} + \gamma \hat v(S_{t+1}), and they lead to PPO and GRPO, which also limit the size of each policy update to address reason 3. The DDPG navigation section uses a deterministic actor with a learned critic on a TurtleBot3, and compares its gradient with the one above. Key references: (Sutton & Barto, 2018); Williams (1992), Simple statistical gradient-following algorithms for connectionist reinforcement learning.

References

  • Sutton, R., Barto, A. (2018). Reinforcement Learning: An Introduction. Link

Found an error on this page? Report an issue.

Footnotes

  1. We write the objective as J(θ)J(\theta), as Sutton and Barto do (Sutton & Barto, 2018). It depends on the policy only through its parameters θ\theta. ↩