The first actual RL algorithm of the course. Levine differentiates the RL objective directly — one identity turns an intractable gradient into something you can estimate from rollouts — then spends the rest of the lecture on why the naive estimator barely works and what fixes it: causality and reward-to-go, baselines, importance sampling for off-policy data, the pseudo-loss trick for autodiff, and the natural gradient.
The objective, and how to evaluate it from rollouts
Policy gradients are “in some ways kind of the simplest reinforcement learning
algorithm”: directly differentiate the RL objective and do gradient ascent on the policy
parameters. The policy πθ(at∣st) — a network with weights θ —
induces, together with the unknown dynamics, a trajectory distribution by the chain rule:
pθ(τ)=p(s1)∏t=1Tπθ(at∣st)p(st+1∣st,at)
with τ=(s1,a1,…,sT,aT). The objective is
J(θ)=Eτ∼pθ(τ)[∑tr(st,at)], and
this lecture works with the finite-horizon version.
Crucially, model-free RL never assumes we know p(s1) or the transition
probabilities — only that we can run the policy, which samples from them. That is
already enough to evaluate J(θ): roll out N trajectories and average their total
rewards. The whole game is doing the same for the derivative.
One identity makes the gradient estimable
Write r(τ) for the total reward of a trajectory, so
J(θ)=∫pθ(τ)r(τ)dτ and
∇θJ(θ)=∫∇θpθ(τ)r(τ)dτ — useless
as written, since ∇θpθ(τ) touches the unknown dynamics. Then comes
what Levine calls “basically the only piece of mathematical cleverness in this whole
derivation”:
What the gradient is actually doing
For a discrete policy, ∇θlogπθ is exactly the gradient you’d
compute in supervised maximum likelihood — except maximum likelihood raises the log
probability of every observed action, while the policy gradient weights each
trajectory’s log-likelihood gradient by its reward. High-reward trajectories get their
probabilities pushed up; low-reward ones get pushed down.
For continuous actions, take
πθ(at∣st)=N(fNN(st),Σ); the log-probability
is a quadratic in f(st)−at, and its gradient
−21Σ−1(f(st)−at)dθdf backpropagates through the
mean network. And a notable freebie: the derivation never used the Markov property, so
the same equation holds verbatim in partially observed settings — replace st with
ot and run it.
The catch is variance. With three samples and rewards drawn as bars on a number line,
where the distribution moves depends alarmingly on things that shouldn’t matter: add a
constant to every reward — which provably changes no optimal policy — and a finite-sample
gradient estimate moves differently. In expectation the estimator is always correct; for
any finite N it is noisy enough that “a lot of advances in policy gradient algorithms
basically revolve around different ways to reduce their variance.”
Two variance reducers: causality and baselines
Causality. Distribute the reward sum into the grad-log-pi sum and each action’s term
multiplies rewards from all time steps — including the past, which the action provably
cannot affect (“this is not an assumption… the only way this would not be true is if
you had time travel”). Those past-reward terms cancel in expectation, so drop them:
Q^i,t is the reward-to-go — a single-sample estimate of the Q-function,
foreshadowing actor-critic. Fewer terms in the sum means smaller numbers means lower
variance; the estimator stays unbiased. You always use this.
Baselines. Subtract b from the reward before weighting, so better-than-average
trajectories go up and worse-than-average go down regardless of whether raw rewards are
all positive:
Going off-policy with importance sampling
Policy gradients are the classic on-policy algorithm: the expectation is under
pθ(τ), so every gradient step demands fresh samples — painful when deep nets
need many small steps and samples are expensive. Importance sampling relaxes this. For
samples from any pˉ(τ):
Ex∼p[f(x)]=Ex∼q[q(x)p(x)f(x)]
and in the trajectory ratio the unknown initial-state and transition terms cancel,
leaving only the product of policy ratios
∏tπθ(at∣st)πθ′(at∣st) — computable. The
trouble: a product of T numbers each below 1 shrinks exponentially, so the importance
weights blow variance up “exponentially fast.” The escape hatch is to write the weight
over state–action marginals and ignore the state-marginal ratio, keeping only the
current action’s ratio. That’s no longer the exact gradient, but the error is bounded
when θ′ stays close to θ — the insight behind practical algorithms like
TRPO and PPO, developed properly in the advanced policy gradients lecture.
Implementing it: the pseudo-loss trick
Naively computing ∇θlogπθ per state–action pair means ~10,000
million-entry vectors. Instead, give your autodiff package a graph whose gradient is
the policy gradient:
Practice notes, verbatim spirit: the gradient is far noisier than supervised learning,
so batch sizes run in the thousands to tens of thousands; learning rates are hard, Adam
is “okay-ish” and the right starting point; budget for much more hyperparameter tuning
than supervised learning has taught you to expect.
Why step size is broken, and the natural gradient
Gradient ascent is really a constrained problem: maximize the linearized objective within
an ϵ-ball — but that ball lives in parameter space, and parameters affect the
policy unevenly. Constrain instead in distribution space with a parameterization-
independent divergence: require DKL(πθ′∥πθ)≤ϵ. The
second-order expansion of the KL is a quadratic form under the Fisher information matrix
F=Eπθ[∇logπθ∇logπθ⊤]
— estimable from the same samples — and the update becomes
θ′=θ+αF−1∇θJ(θ)
the natural gradient. With the preconditioner in place the vector field points at
the optimum. Natural policy gradient picks α; TRPO picks ϵ and derives
α, using conjugate gradient to get F−1∇J without forming
F.
Check yourself
Derivation-style exercises in the lecture’s spirit — work them on paper.
Problem 5.1log-gradient derivation
Derive, from scratch, why
∇θJ(θ)=Epθ(τ)[∇θlogpθ(τ)r(τ)]
requires no knowledge of the dynamics, starting from
J(θ)=∫pθ(τ)r(τ)dτ. Point to the exact step where the
transition probabilities disappear.
Show solution
Push ∇θ inside the integral, then apply
∇θpθ=pθ∇θlogpθ to get
∫pθ(τ)∇θlogpθ(τ)r(τ)dτ, an
expectation under pθ. Expanding
logpθ(τ)=logp(s1)+∑t[logπθ(at∣st)+logp(st+1∣st,at)],
the dynamics disappear at the differentiation step: ∇θlogp(s1)=0 and
∇θlogp(st+1∣st,at)=0 because neither depends on θ.
Only ∑t∇θlogπθ(at∣st) survives, and the dynamics now
appear only in the sampling distribution — handled by rolling out the policy.
Problem 5.2baseline variance
A one-step problem has two trajectories under the current policy: probability 0.5 each,
rewards 101 and 99, with ∇θlogπθ=+g for the first and −g for
the second. Compute the single-sample gradient estimator’s variance with baseline b=0
and with b=100 (the mean reward). What happens with b=99?
Show solution
With b=0: the estimator is +101g or −99g with equal probability; mean =g.
Variance =E[X2]−g2=21(1012+992)g2−g2=10000g2.
With b=100: estimator is +g or −g… mean =g⋅21(1)+... —
careful: values are (101−100)g=g and −(99−100)g=g; the estimator is alwaysg, variance 0, mean unchanged at g. With b=99: values 2g and 0, mean still
g, variance 21(4g2)−g2=g2. Same expectation every time — exactly the
unbiasedness theorem — but variance swings from 104g2 to 0 depending on b.
Problem 5.3importance-weight blowup
Your new policy agrees with the old one everywhere except it assigns ratio
πθ′/πθ=0.9 at every one of T=100 time steps. What is the
trajectory importance weight, and what does it do to the effective sample size? Why does
keeping only the per-step action ratio avoid this?
Show solution
The full weight is 0.9100≈2.7×10−5. With weights that small on
every sample (and occasionally enormous ones when ratios exceed 1), the variance of the
weighted estimator explodes — effectively almost none of your samples carry information,
which is the “variance goes to infinity exponentially fast” failure. Writing the gradient
over state–action marginals and dropping the state-marginal ratio leaves a single factor
of 0.9 per term rather than a product over all past steps, so the weight no longer
decays exponentially in T. The price is bias — acceptable, with bounded error, only
while θ′ stays close to θ, which is the constraint TRPO/PPO enforce.
Problem 5.4natural gradient intuition
In the (k,σ) example, the vanilla gradient’s σ-component dominates as
σ→0. Explain in one or two sentences per item: (a) why this happens, (b) why
no single learning rate fixes it, and (c) what property of the KL constraint makes the
natural gradient immune.
Show solution
(a) The Gaussian log-density scales as 1/σ2, so ∂/∂σ terms
grow like 1/σ3–1/σ4 while ∂/∂k stays moderate — after
normalization the σ direction swallows the step. (b) A rate small enough to keep
the σ updates stable makes progress in k negligible; a rate that moves k
overshoots in σ — the conditioning problem lives in the geometry, not the scalar.
(c) The KL divergence measures change between distributions, independent of
parameterization; expanding it gives the Fisher matrix as the local metric, and
F−1 rescales each direction by how much it actually changes the policy —
big-effect parameters get small steps and vice versa, which is exactly the per-parameter
learning rate you wanted.