In the previous post, we set up the reinforcement learning problem and looked at value functions and Bellman equations. These let us describe how good a given policy is. But we have not yet seen how to actually find a good policy.
Suppose the policy is parameterized by θ, written as πθ(at∣st). Together with the environment dynamics, this policy defines a distribution over trajectories:
Since the expectation over trajectories is usually intractable, we sample trajectories and use them to estimate ∇θJ(θ). This leads to the REINFORCE algorithm.1
In practice, the basic REINFORCE algorithm does not work very well. To see why, we need to look at the estimator more carefully.
Let
R(τ)=t=0∑T−1γtrt
denote the return of a trajectory. Compare the two estimators:
Maximum likelihood:REINFORCE:g^ML=N1i=1∑N∇θlogpθ(τi)g^RF=N1i=1∑N∇θlogpθ(τi)R(τi)
The REINFORCE estimator has the same likelihood-gradient term as maximum likelihood, but each sampled trajectory is weighted by its return. This means we can interpret it as a reward-weighted maximum likelihood objective: trajectories with high return are made more likely, and trajectories with low return are made less likely.
Now suppose we add the same constant c to the return of every trajectory:
Rc(τ)=R(τ)+c.
Since every trajectory receives the same bonus, their relative quality does not change. So the best policy should not change either. In fact,
Jc(θ)=Eτ∼pθ(τ)[R(τ)+c]=J(θ)+c,
and therefore
∇θJc(θ)=∇θJ(θ).
Using the shifted returns, the REINFORCE estimator becomes
g^c=N1i=1∑N∇θlogpθ(τi)(R(τi)+c).
Suppose c is large enough that all the shifted returns R(τi)+c are positive. Then every sampled trajectory contributes an update that increases its likelihood, whether that trajectory was relatively good or bad. If c is very negative, every shifted return can become negative, and the update pushes all the sampled trajectories in the opposite direction.
Still, the estimator is unbiased. The effect of c disappears in expectation:
So these extra updates cancel out on average, but not necessarily within a finite batch. In other words, the REINFORCE estimator is unbiased but can have high variance.
Improving the Policy Gradient Estimator
Reducing Variance With Baselines
To address the problem above, we can think of shifting the returns before using them in the gradient so that positive and negative updates are better balanced. In fact, subtracting a baseline from the returns leaves the estimator unbiased. The baseline can even depend on the current state.
Theorem. Let b:S→R be a deterministic state-dependent baseline. The following estimator is still an unbiased estimator of ∇θJ(θ):
∇^θJ(θ)=t=0∑T−1∇θlogπθ(at∣st)(R(τ)−b(st)).
Proof. The only thing we need to show is that the baseline term has expectation zero:
Eτ∼pθ(τ)[t=0∑T−1∇θlogπθ(at∣st)b(st)]=0.
For a fixed time t, condition on the partial trajectory up to state st:
τ(t)=(s0,a0,r0,…,st−1,at−1,rt−1,st).
Once we condition on τ(t), the state st is fixed, so b(st) is also fixed. The only remaining random variable in the baseline term is the action at∼πθ(⋅∣st):
By the tower property, the expectation of each baseline term is zero, so their sum is also zero. Therefore subtracting b(st) does not change the expected policy gradient. It can only change the variance of the estimator.
Removing Past Rewards
Another variance-reduction trick is to remove rewards that happened before the action. In the original estimator, each score term is multiplied by the full return:
t=0∑T−1∇θlogπθ(at∣st)(t′=0∑T−1γt′rt′).
For the action at, this full return contains two parts:
The term ∇θlogπθ(at∣st) tells us how to change the policy parameters to make action at more or less likely. But rewards before time t are already fixed when at is chosen, so they should not affect this update.
Theorem. The following estimator, which uses the reward-to-go, is still an unbiased estimator of ∇θJ(θ):
By the tower property, the removed past-reward terms have zero expectation. Therefore removing them does not change the expected policy gradient, but it can reduce variance. After this step, each action is weighted only by the rewards from that time onward.
Q-Estimates
Removing past rewards gives us the reward-to-go. This is better than using the full trajectory return, but it is still a sampled quantity from one rollout.
The next idea is to replace this sampled reward-to-go with its conditional expectation. That conditional expectation is exactly the state-action value:
Qπθ(st,at)=E[t′=t∑T−1γt′−trt′∣st,at].
So Q-estimates reduce variance by replacing a noisy sampled reward-to-go with an estimate of its expected value.
Theorem. The following estimator is an unbiased estimator of ∇θJ(θ):
In practice, Vπθ is also unknown, so we usually approximate it with a learned value function Vϕ:
b(s)=Vϕ(s).
Using Vϕ as the baseline still gives an unbiased estimator, because the baseline can be any deterministic function of the state. The approximation affects variance, not the expected gradient:
Unlike using Vϕ only as a baseline, replacing Qπθ with Qϕ can introduce bias unless Qϕ is exact.
Toward a Practical Algorithm
The expression above seems to require both Qϕ and Vϕ. In practice, we usually avoid learning both separately.
From the one-step transition property,
Qπθ(st,at)=E[rt+γVπθ(st+1)∣st,at].
So, given one sampled transition (st,at,rt,st+1), we can estimate the Q term by
Q^t=rt+γVϕ(st+1).
This turns the policy-gradient term into
∇θlogπθ(at∣st)γt(rt+γVϕ(st+1)−Vϕ(st)).
Now the main remaining question is how to learn Vϕ.
Policy Evaluation
Policy evaluation is the problem of estimating the value function of a fixed policy.
Even if the policy π is known exactly, computing Vπ is not always easy. Also, when the state space is large or infinite, we cannot store the value for every state. In practice, we approximate the value function with a neural network Vϕ.
Monte Carlo
The first thing we can try is to use the rewards from sampled trajectories directly. If a trajectory starts from s0=s, then the return from that trajectory gives a sample estimate of Vπ(s):
Vπ(s)=E[t=0∑T−1γtrt∣s0=s].
So we can fit Vϕ to the sampled return:
Vϕ(s0)≈t=0∑T−1γtrt.
More generally, for a state st inside a trajectory, the Monte Carlo target is the return from that time onward:
Vϕ(st)≈t′=t∑T−1γt′−trt′.
The Monte Carlo target is unbiased, but it can have high variance because different trajectories from the same state can produce very different returns. Reducing this variance would require averaging many trajectories from the same state, which is generally not feasible.
Temporal Difference
This leads to temporal difference learning. Instead of waiting for the full trajectory, TD uses one transition and the one-step Bellman relation:
Vπ(s)=E[r0+γVπ(s1)∣s0=s].
With N independent one-step transitions from s, this can be estimated as
Vπ(s)≈N1i=1∑N(r0(i)+γVπ(s1(i))).
Of course, Vπ is unknown. In practice, we replace it with Vϕ and use the one-step target
yt=rt+γVϕ(st+1).
Then Vϕ is updated to make Vϕ(st) closer to yt:
L(ϕ)=21(Vϕ(st)−yt)2.
As TD depends only on a single transition rather than a full trajectory, it usually has lower variance than Monte Carlo. However, errors in Vϕ(st+1) make the target biased. The value estimate can also be inaccurate and change quickly, especially early in training, which can make learning unstable.
k-Step TD
k-step TD sits between Monte Carlo and one-step TD. It uses the next k rewards from the trajectory and a value estimate for the remaining return:
Vπ(st)=E[i=0∑k−1γirt+i+γkVπ(st+k)∣st].
In practice, we use the target
yt(k)=i=0∑k−1γirt+i+γkVϕ(st+k).
Then Vϕ is updated toward this k-step target:
L(ϕ)=21(Vϕ(st)−yt(k))2.
When k=1, this becomes one-step TD. When k reaches the end of the episode, it becomes Monte Carlo. Between these two extremes, a smaller k usually gives lower variance but more bias, while a larger k gives higher variance but less bias.
Semi-Gradient TD
To see how TD is implemented, first write the value-fitting objective as
L(ϕ)=Es∼p0π[21(Vϕ(s)−Vπ(s))2].
Using the one-step Bellman relation, the gradient can be written as
∇ϕL(ϕ)=E[(Vϕ(st)−rt−γVπ(st+1))∇ϕVϕ(st)].
This would be exact if Vπ(st+1) were known, but it is not actionable in practice. TD replaces it with the current estimate Vϕ(st+1):
gt=(Vϕ(st)−rt−γVϕ(st+1))∇ϕVϕ(st).
The practical way to implement this is to use a stop-gradient on the target:
LTD(ϕ)=21(Vϕ(st)−rt−γsg[Vϕ(st+1)])2.
Here sg[⋅] treats its input as a constant during backpropagation. In PyTorch, this is .detach(). Therefore,
∇ϕLTD(ϕ)=(Vϕ(st)−rt−γVϕ(st+1))∇ϕVϕ(st).
This is different from directly minimizing the Bellman error
21(Vϕ(st)−rt−γVϕ(st+1))2,
because the full gradient would also differentiate through Vϕ(st+1):
So TD with stop-gradient is a semi-gradient method. It uses the current next-state value to form the target, but it does not update the parameters through that target.
There are also methods that try to directly optimize a true gradient objective for TD, often called gradient TD (GTD) methods.23 The original GTD algorithm is provably convergent, but it can be much slower than conventional TD in settings where conventional TD is stable.3
Actor-Critic Algorithm
Now we can put the pieces together.
Using the k-step TD target, define
Q^t(k)=i=0∑k−1γirt+i+γkVϕ(st+k).
Then the advantage estimate is
A^t(k)=Q^t(k)−Vϕ(st).
For the discounted-return objective, the policy-gradient update becomes:
∇θJ(θ)≈∇θlogπθ(at∣st)γtA^t(k).
However, many actor-critic implementations drop the outer γt factor and use
∇θJ(θ)≈∇θlogπθ(at∣st)A^t(k).
Dropping this factor means that the update no longer exactly matches the discounted-return objective.4 But in many practical settings, the discount factor is introduced mainly to reduce variance, make the return well-defined, and stabilize value estimation. We usually do not want the policy to ignore later states just because they occur later in the trajectory; we want the policy to behave well at every time step. So we keep γ inside the TD target, but we often remove the extra time-dependent weight from the actor update. In the algorithm below, I will use this common practical version.
The critic update fits Vϕ(st) to the k-step TD target:
Putting this together, the algorithm looks like this:
Algorithm: Actor-CriticInitialize policy parameters θ and value parameters ϕrepeatgθ←0,gϕ←0Sample trajectory τ∼pθ(τ)for t=0,1,…,T−1 doQ^t(k)←i=0∑k−1γirt+i+γkVϕ(st+k)A^t(k)←Q^t(k)−Vϕ(st)gθ←gθ+∇θlogπθ(at∣st)A^t(k)gϕ←gϕ+∇ϕ21(sg[Q^t(k)]−Vϕ(st))2end forθ←θ+Tαπgθϕ←ϕ−TαVgϕuntil convergence
This is called actor-critic because the policy acts, and the value function plays the role of a critic that evaluates the action.
Generalized Advantage Estimation (GAE)
We used a k-step TD target to estimate the advantage. This gives a bias-variance tradeoff: small k is more TD-like, so it usually has lower variance but more bias; large k is more Monte Carlo-like, so it usually has lower bias but higher variance.
Generalized Advantage Estimation (GAE) gives a smoother way to control this tradeoff.5 First, define the k-step TD advantage estimator:
A^tTD(k)=i=0∑k−1γirt+i+γkV(st+k)−V(st).
GAE takes an exponentially weighted average of these estimators with λ∈[0,1]:
The parameter λ lets us smoothly control the bias-variance tradeoff. Larger λ puts more weight on larger k-step estimates, so it has lower bias but higher variance. Smaller λ puts more weight on smaller k-step estimates, so it has lower variance but higher bias.
When λ=0, GAE becomes the one-step TD advantage estimate:
A^tGAE(γ,0)=A^tTD(1).
When λ=1, it becomes the Monte Carlo-style advantage estimate:
A^tGAE(γ,1)=A^tTD(∞).
GAE can also be written in a cleaner form:
A^tGAE(γ,λ)=l=0∑∞(γλ)lδt+lV,
where
δtV=rt+γV(st+1)−V(st)
is the TD residual. It measures how different the current value estimate is from the one-step Bellman target.
This changes the action sampling from πθ to πθ0, but the state distribution is still pθ(st). To reuse data from πθ0, we make a local approximation: if πθ is close to πθ0, then the two policies choose similar actions and should visit similar states. Therefore,
pθ(st)≈pθ0(st).
This approximation is only reasonable for small policy updates, which is why we need a constraint that keeps πθ close to πθ0. With this approximation, we define the surrogate objective
where A^t≈Aπθ0(st,at) is an advantage estimate.
The trust-region constraint also helps with (∗): importance sampling estimates can have high variance when the target policy πθ is too far from the behavior policy πθ0, because the ratios πθ(at∣st)/πθ0(at∣st) can become large.
Trust Region Policy Optimization (TRPO)
In practice, TRPO constrains the average KL divergence over states visited by the current policy.6 The constraint is
Geometrically, this update chooses the step with the largest projection onto the improvement direction while keeping the approximate KL change within ϵ.
Derivation of the local step
Using a Lagrange multiplier, the local constrained problem is
Δθmaxsubject togTΔθ21ΔθTFΔθ≤ϵ
The Lagrangian is
L(Δθ,λ)=gTΔθ−λ(21ΔθTFΔθ−ϵ).
Taking the derivative with respect to Δθ gives
g−λFΔθ=0.
Therefore,
Δθ=λ1F−1g.
Write this as
Δθ=αF−1g.
Plugging it into the approximate KL constraint gives
21α2gTF−1g=ϵ.
Solving for α gives
α=gTF−1g2ϵ.
The resulting algorithm is:
Algorithm: TRPOrepeatθ0←θSample trajectories τ(1),…,τ(N)∼(p0,πθ0,p)Estimate advantages A^t(i), typically using GAECompute the sampled surrogate objective:K(θ;θ0)←N1∑i=1N∑t=0T(i)−1γtπθ0(at(i)∣st(i))πθ(at(i)∣st(i))A^t(i)g←∇θK(θ;θ0)θ=θ0Approximately solve Fx=g using Fisher-vector products, so x≈F−1gΔθ←gTx2ϵxθ←θ0+Δθuntil convergence
As in the actor-critic methods above, many practical implementations drop the outer γt factor in the policy update.
In practice, the hard part is computing F−1g without explicitly forming or inverting the full Fisher matrix. TRPO uses conjugate gradients and Fisher-vector products for this; see the TRPO paper for details.6
Proximal Policy Optimization (PPO)
TRPO is conceptually nice: it tries to improve the policy while keeping the new policy close to the old one. But the update uses second-order optimization, which can be inefficient compared to ordinary SGD-style updates.
So the natural question is: can we keep the trust-region idea, but optimize with a normal first-order method like SGD or Adam?
This is the idea behind PPO.7 (The PPO paper presents PPO-Penalty and PPO-Clip. I will talk about the simpler PPO-Clip.)
For one sampled transition, PPO-Clip replaces the original surrogate term
So the unclipped term is just a weighted policy gradient, where the weight is the policy ratio.
After clipping, the gradient becomes
∇θCϵ(πθk(at∣st)πθ(at∣st),A^t)=⎩⎨⎧A^tπθk(at∣st)πθ(at∣st)∇θlogπθ(at∣st),0,A^tπθk(at∣st)πθ(at∣st)∇θlogπθ(at∣st),0,A^t≥0 and πθk(at∣st)πθ(at∣st)<1+ϵA^t≥0 and πθk(at∣st)πθ(at∣st)>1+ϵA^t<0 and πθk(at∣st)πθ(at∣st)>1−ϵA^t<0 and πθk(at∣st)πθ(at∣st)<1−ϵ
So PPO is applying a weighted policy gradient, but stops once a sample has already moved enough in that direction. In this sense, clipping plays a role similar to a trust-region constraint.
Putting this together, PPO-Clip looks like this:
Algorithm: PPO-Cliprepeatθk←θSample trajectories τ(1),…,τ(N)∼(p0,πθk,p)Estimate advantages A^t(i), typically using GAEfor e=1,…,K doSplit sampled transitions into minibatches Bfor each minibatch B doLclip(θ;B)←∣B∣1∑(i,t)∈Bmin(πθk(at(i)∣st(i))πθ(at(i)∣st(i))A^t(i),clip(πθk(at(i)∣st(i))πθ(at(i)∣st(i)),1−ϵ,1+ϵ)A^t(i))g←∇θLclip(θ;B)θ←θ+αgend forend foruntil convergence
In practice, PPO typically uses GAE to estimate the advantages and trains the value function on the same batch alongside the policy.
This is the end of the second post. We started from the policy gradient, extended it to actor-critic methods, and then studied TRPO and PPO for more stable policy updates. In the next post, we will take a different approach with Q-learning, which learns an optimal action-value function and derives a policy from it instead of optimizing the policy directly.
John Schulman, Sergey Levine, Philipp Moritz, Michael I. Jordan, and Pieter Abbeel, “Trust Region Policy Optimization”, Proceedings of the 32nd International Conference on Machine Learning, PMLR 37:1889–1897, 2015. ↩↩2