Policy Gradients

Make the actions that paid more likely and the actions that paid less unlikely. Subtract a baseline, and the same learning jitters about 3 times less.

Learn how a policy improves from nothing but its own tries and their scores, derived one step at a time, with every equation read aloud.

Press Sample an episode a few times, then Update. Watch the bars move toward the arm that paid more. Then press Play, switch on Subtract a baseline, and play again. Then we build it piece by piece: the return, the objective, the log-derivative trick, REINFORCE, reward-to-go and the baseline.

You need a little Python and what a probability is. A derivative helps in Chapter 3. We build the rest from zero.

Re-taught from Lecture 3, Policy Gradients, of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.

Teach a policy which arm pays

Illustrative toy. Each episode is one pull of one arm. Arms A, B and C pay 4, 6 and 5 on average, plus noise with a standard deviation of 1. Each update uses 4 episodes and a step size of 0.2. The baseline is a running average of earlier returns. In 200 simulated runs of 60 updates, the step-to-step jitter of arm B's chance was 0.034 without a baseline and 0.011 with one.

Chapter 0

A Policy You Can Nudge

Meet the policy as a list of action probabilities, and see why we tune those probabilities directly

A robot arm tries to put a mug on a coaster. Nobody shows it how. After each try it gets one number: plus 5 if the mug lands, minus 1 if it falls. Which way should it change its network so it lands more mugs?

The network is a policy: a function that takes the situation and returns a probability for each action. Its weights are the knobs, called θ (theta). Q-learning learns a value for each action and then searches for the best one. That search is easy for four arrow keys and hard for seven motor torques. A policy gradient method skips the search. It changes θ so that the actions that paid become more likely.

Start with the smallest policy: three actions, A, B and C, and no state. Each action gets a score called a logit: θ-A, θ-B and θ-C. A softmax turns the scores into probabilities that are positive and add to 1.

Say it aloud

Pi-theta of a equals e to the theta-a, divided by the sum over b of e to the theta-b.

πθ(a)
pi-theta of a the chance that the policy picks action a.
eθa
e to the theta-a the logit of action a, made positive by the exponential.
Σb
the sum over b add one term for every action b: A, B and C.
θb
theta-b the logit of action b: one knob, any real number.
In plain words

Make each logit positive with e. Divide each result by the total. Action a gets that share, pi-theta of a.

With numbers

With made-up logits 1, 0 and −1: e gives 2.72, 1.00 and 0.37, a total of 4.09. So the policy picks A 66.5%, B 24.5% and C 9.0% of the time.

Turn the three logits

Teal bars are the policy's probabilities. Drag one logit and watch all three bars move, because the shares must add to 1.

1.0
0.0
−1.0

A toy policy with no state. The later toys use the same three actions.

The failure. Set logit A to 3 and the others to −3. A now gets 99.5%, so the policy almost never tries B or C, and it can never learn that one of them pays more. The symptom is one bar near 100% early in training. Measure it with the entropy of the probabilities, a number that falls to 0 as one action takes over. The fix is smaller steps, or a small reward for entropy.

The road

  1. Trajectories and the return: one episode, one number.
  2. The objective: the average return, estimated by sampling.
  3. The log-derivative trick: the gradient of a chance, as something you can sample.
  4. The policy gradient, step by step: why the world's dynamics drop out.
  5. REINFORCE: sample, weight, step, in a corridor you can train.
  6. Why the estimate is noisy: variance, and why more episodes help slowly.
  7. Reward-to-go: an action cannot change the past.
  8. Baselines and the advantage: the hero's toggle, explained and proved.
  9. Beyond REINFORCE: actor-critic, natural gradient, TRPO and PPO.
  10. The field guide: terms, numbers, code and links.
Why does a policy gradient method suit a robot with seven continuous motor torques better than Q-learning?

Chapter 1

Trajectories and the Return

Record one episode as states, actions and rewards, and add the rewards into one number

Put a robot at one end of a corridor. It steps right each turn. Each step costs 0.1, and the goal, seven steps away, pays 10. How much is the whole trip worth?

The record of one episode is a trajectory, written τ (tau): the state, the action and the reward at each step, from start to end. Call the state at step t s-t, the action a-t and the reward r-t. The worth of the whole trip is the return. Late rewards count a little less: a factor γ (gamma) shrinks them once for each step of delay.

Say it aloud

R of tau equals the sum over t of gamma to the t, times r-t.

R(τ)
R of tau the return: what the whole trajectory tau is worth.
Σt
the sum over t one term for each step, from step 0 to the last step.
γt
gamma to the t the discount, a number from 0 to 1, multiplied by itself t times.
rt
r-t the reward at step t.
In plain words

Shrink each reward r-t by gamma once for every step you waited for it. Add them all. The total is R of tau.

With numbers

With made-up rewards 1, 0 and 2 and gamma 0.9: R = 1 + 0.9 × 0 + 0.81 × 2 = 2.62. The 2 counts as 1.62 because it came two steps late.

Unroll the return of one trip

Faint bars are the raw rewards. Solid bars are each reward after the discount. Press Unroll, then change gamma.

0.90

Illustrative corridor: steps 0 to 6 cost 0.1 each, and the goal pays 10 at step 7.

At gamma 0.9 the goal's 10 is worth 10 × 0.97 = 4.78. The seven step costs add to −0.52. The trip is worth 4.26.

The failure. Set gamma to 0.5. The goal is now worth 0.08, and the trip is worth −0.12, less than doing nothing. The robot stops caring about a goal it cannot reach soon. The symptom is an agent that always takes the near, small reward. To measure it, count the steps until gamma to the t falls below 0.1: 4 steps at 0.5, and 230 at 0.99. The fix is a gamma that matches how far away the goal is.

An episode gives rewards 0, 0 and 4, and gamma is 0.5. What is the return?

Chapter 2

The Objective Is the Average Return

Average the return over many episodes, because the same policy gives a different return each time

Go back to the three arms at the top of the page. Arm A pays about 4, arm B about 6 and arm C about 5, plus noise. Run the same policy twice and you get two different returns. So which number do we try to raise?

We raise the average. Call the chance of a whole trajectory under the policy p-theta of tau. The objective J(θ) is the expected return: the average of R(τ) over trajectories drawn from p-theta. Nobody can add up every possible trajectory, so we run N episodes and average their returns.

Say it aloud

J of theta equals the expected value, over tau drawn from p-theta, of R of tau. It is about one over N times the sum over i of R of tau-i.

J(θ)
J of theta the objective: the average return of the policy with knobs θ.
Eτ∼pθ
the expected value over tau drawn from p-theta the average over many episodes run with this policy.
R(τ)
R of tau the return of one trajectory, from Chapter 1.
(1/N) Σi
one over N times the sum over i add the N returns and divide by N.
τi
tau-i the i-th episode you ran.
In plain words

Run the policy N times. Write down each return R of tau-i. Their average estimates J of theta.

With numbers

With the toy's numbers: the policy picks A, B and C with chances 0.5, 0.3 and 0.2. So J = 0.5 × 4 + 0.3 × 6 + 0.2 × 5 = 4.8, the number the device below must find by sampling.

Estimate J by running episodes

Each dot is one episode's return. The warm line is the running average. Run episodes and watch the line settle near 4.8.

Illustrative toy: the arms pay 4, 6 and 5 plus noise with a standard deviation of 1. The policy stays fixed at 0.5, 0.3 and 0.2.

The failure. A few episodes can mislead. If the first three all happen to be arm B, the average is near 6, and the policy looks better than it is. The symptom is a score that jumps between two evaluations of the same policy. To measure it, run the same policy on several batches and compare their averages. The fix is to average more episodes and to report the spread with the number.

A policy picks A with chance 0.2, B with 0.5 and C with 0.3. The arms pay 4, 6 and 5 on average. What is J?

Chapter 3

The Log-Derivative Trick

Turn the gradient of an average into an average you can sample

We want the gradient of J: for each knob, which way raises the average return, and how fast. Write it with the symbol ∇ (nabla). The trouble is that θ changes which episodes happen, not what a given episode pays. You cannot backpropagate through a coin flip.

One line of calculus fixes it. The derivative of log f is the derivative of f divided by f. Multiply both sides by f.

Say it aloud

Nabla-theta of p-theta of x equals p-theta of x times nabla-theta of log p-theta of x.

∇θ
nabla-theta the gradient: for each knob in θ, how fast the thing after it rises.
pθ(x)
p-theta of x the chance of outcome x under the policy: one action, or a whole trajectory.
∇θ log pθ(x)
the score of x the gradient of the log of that chance: which way to turn θ to make x more likely.
In plain words

The gradient of the chance of x is the score of x times the chance of x. That chance in front is what turns a sum into an average we can sample.

With numbers

With made-up numbers: the policy picks A with chance 0.5, and the score of A for logit θ-A is 1 − 0.5 = 0.5. So the gradient of π(A) for θ-A is 0.5 × 0.5 = 0.25.

For the softmax policy the score is short. Take the action a that the policy took and any logit b. The rate at which log π(a) changes as only θ-b moves is:

∂ log π(a) / ∂θb = 1[b = a] − π(b)

Here 1[b = a] is 1 when b is the action taken and 0 otherwise. So the taken action's logit goes up by 1 − π(a), and every other logit goes down by its own probability. The pushes add to zero.

Push the logits after one action

The policy starts at 50%, 30% and 20%. Pick the action taken and set its return. Purple arrows show the score times the return; outlines show the policy after one step.

1.0

Toy numbers. The step adds 0.5 times the return times the score to each logit.

The failure. If every return is positive, every taken action goes up, only by different amounts. The direction is right on average, but each step is mostly noise. The symptom is probabilities that jitter toward whatever the policy sampled last. To measure it, compare the size of each step with the net change over many steps. The fix is a baseline, in Chapter 8.

The policy is 50%, 30%, 20% over A, B, C. It took B. What is the score for logit A?

Chapter 4

The Policy Gradient, Step by Step

Apply the trick to a whole trajectory and watch the world's part cancel

A trajectory holds two kinds of chance. The policy picks each action. The world picks each next state, with chance P(s-t+1 | s-t, a-t), read "P of the next state given the state and the action". We do not know P and cannot differentiate it. The derivation below never needs it.

  1. Write J as a sum over every trajectory, each return weighted by its chance.
    J(θ) = Στ pθ(τ) R(τ)
  2. Take the gradient. R(τ) has no θ in it, so only the chance moves.
    ∇J(θ) = Στ ∇pθ(τ) R(τ)
  3. Use the log-derivative trick. The chance comes back in front, so the sum is an average again.
    ∇J(θ) = Στ pθ(τ) ∇log pθ(τ) R(τ) = Eτ∼pθ[ ∇log pθ(τ) R(τ) ]
  4. Write out the chance of a trajectory: the chance of the start state, p(s-0), then one policy term and one world term per step. The log turns the product into a sum.
    log pθ(τ) = log p(s0) + Σt [ log πθ(at|st) + log P(st+1|st,at) ]
  5. Take the gradient. The start term and every world term have no θ in them, so they become 0.
    ∇log pθ(τ) = Σt ∇log πθ(at|st)

Put step 5 into step 3. The result is the policy gradient in trajectory form. Williams (1992) built REINFORCE on it, and Sutton and colleagues (2000) proved a general version, the policy gradient theorem.

Say it aloud

Nabla-theta of J equals the expected value, over tau drawn from p-theta, of the sum over t of the score of a-t given s-t, times R of tau.

∇θJ(θ)
nabla-theta of J how to turn every knob to raise the average return.
Eτ∼pθ
the expected value over tau drawn from p-theta the average over episodes run with the current policy.
Σt
the sum over t one term for each step of the episode.
∇θ log πθ(at|st)
the score of a-t given s-t which way to turn θ to make the action taken at step t more likely in state s-t.
R(τ)
R of tau the return of the whole episode, a plain number.
In plain words

Run an episode. At each step, take the score of the action you took. Add the scores, multiply by the episode's return, and average over episodes.

With numbers

In the toy each episode is one step. The policy is 0.5, 0.3, 0.2 and the arms pay 4, 6, 5. The average is −0.40 for θ-A, +0.36 for θ-B and +0.04 for θ-C. Lower A, raise B, and leave C almost alone.

Check the gradient by sampling

Dashed outlines are the exact gradient. Filled bars are the estimate from N episodes. Slide N up and watch the bars meet the outlines.

10

The exact value for logit b is π(b) times (arm b's pay minus J). Same toy as Chapter 2.

The failure. At N = 10 the estimate for θ-C has the wrong sign about half the time. Its true value, 0.04, is tiny next to the noise. The symptom is a knob that wanders up and down across updates. To measure it, resample at the same N and count the sign flips. The fix is more episodes per update, plus the tools of Chapters 7 and 8.

Why do the world's transition chances drop out of the policy gradient?

Chapter 5

REINFORCE: Sample, Weight, Step

Turn the gradient into a loop a computer runs, and train a policy in a corridor

REINFORCE (Williams, 1992) is the policy gradient used as it stands. One update has four steps.

  1. Run the current policy for N episodes. Record every state, action and reward.
  2. Compute each episode's return R(τ).
  3. For every step, multiply the score of the action by the episode's return. Average over the N episodes.
  4. Add α times that average to θ, where α (alpha) is the step size. Throw the episodes away and go to step 1.

REINFORCE uses each batch once. After the step, θ is new, so the old episodes came from a different policy. A method that needs fresh data from the current policy is on-policy.

One update by hand, in the three-armed toy. The policy is 0.5, 0.3, 0.2, and two episodes ran: A paid 4 and B paid 6.

  1. Episode 1: 4 × (0.5, −0.3, −0.2) = (2, −1.2, −0.8).
  2. Episode 2: 6 × (−0.5, 0.7, −0.2) = (−3, 4.2, −1.2).
  3. Average: (−0.5, 1.5, −1.0). With α = 0.2 the logits move by (−0.1, +0.3, −0.2).
  4. New policy: 0.44, 0.40, 0.16. B went up most because it paid most.
pythondef reinforce_step(theta, episodes, alpha):
    grad = np.zeros_like(theta)              # theta: [n_states, n_actions] logits
    for ep in episodes:                      # ep: list of (s, a, r)
        R = sum(r for _, _, r in ep)         # the episode's return
        for s, a, _ in ep:
            pi = softmax(theta[s])           # [n_actions]
            score = -pi; score[a] += 1       # 1[b = a] - pi(b)
            grad[s] += score * R
    return theta + alpha * grad / len(episodes)

Train a policy in a corridor

The robot starts on the third square. The near coin pays 0.6, the far coin pays 1.0, and each step costs 0.05. Arrows show the chance of stepping right. Press Train.

2.0

Illustrative toy. Each square has its own two logits, and an episode ends at a coin or after 12 steps. A run is 40 updates. The best return is 0.85 (far coin); the near coin gives 0.50.

The failure. Set the batch to 1 and the step size to 6, then train a few times. About half the runs lock into the near coin. One early trip left gets a huge step, the policy stops going right, and it never sees the far coin again. The symptom is a return that flattens at 0.5; to measure it, count how many of several seeds reach 0.85. The fix is a bigger batch or a smaller step. With batch 8 and step 2, all 100 of our test runs found the far coin.

Fresh data is costly. If one robot episode takes 5 minutes and each update needs 100 episodes, 10,000 updates take 5 million minutes: about 9.5 years of robot time.

Why does REINFORCE throw its episodes away after each update?

Chapter 6

Why the Estimate Is Noisy

Measure the spread of the gradient estimate and see how slowly more episodes shrink it

The estimate from Chapter 5 is unbiased: averaged over many batches, it equals the true gradient. But one batch can be far off. The standard deviation of the estimate is the typical size of that error, and its square is the variance.

Take the toy at 0.5, 0.3, 0.2. The true gradient for θ-B is +0.36. One episode gives one of three kinds of value: if the policy took B, the return times 0.7; if not, the return times −0.3. Those are numbers near +4.2, −1.2 and −1.5. They average to 0.36, but each one is mostly noise.

Draw 400 gradient estimates

Each bar counts estimates of θ-B's gradient. The purple line is the true value, 0.36. Change N, the episodes per estimate, and watch the spread.

Same toy as Chapter 4, no baseline. The spread in the read-out is exact; the histogram is a fresh sample.

With N = 1 the standard deviation is 2.56, seven times the signal. Averaging N episodes divides it by the square root of N: N = 4 gives 1.28, and N = 64 gives 0.32. To halve the noise you need four times the episodes.

Why so noisy? The whole return multiplies the score, and the return carries all the luck of the episode: every random action and every random reward. A long episode carries more luck. The next two chapters remove two kinds of it without changing the average.

The failure. The symptom is a learning curve that looks like a random walk, and two seeds that end in different places. To measure it, estimate the gradient from two fresh batches and compare them. If they often point different ways, the noise is larger than the signal. The fix is bigger batches first, then reward-to-go and a baseline.

With N = 1 the standard deviation of the estimate is 2.56. About what is it with N = 16?

Chapter 7

Reward-to-Go: An Action Cannot Change the Past

Weight each action only by the rewards that came after it

Chapter 4 weights every action by the return of the whole episode. But the action at step 5 cannot change the reward at step 3. From that action's point of view, the earlier reward is luck, and luck adds noise.

So weight each action by the rewards from its own step to the end. Call that sum the reward-to-go, G-t. Each later reward is shrunk by gamma once per step after t.

Say it aloud

One over N times the sum over i and the sum over t of the score of a-i-t given s-i-t, times G-i-t; and G-i-t is the sum, from t-prime equals t to T, of gamma to the t-prime minus t, times r-i-t-prime.

(1/N) Σi
one over N times the sum over i average over the N episodes. The whole expression estimates ∇J.
Σt
the sum over t every step of episode i.
∇θ log πθ(ai,t|si,t)
the score of a-i-t which way to turn θ to make the action at step t of episode i more likely.
Gi,t
G-i-t the reward-to-go: what episode i paid from step t on.
Σt′=tT
the sum from t-prime equals t to T add the rewards from step t to the last step T, and none before t.
γt′−t
gamma to the t-prime minus t shrink each later reward once per step after t.
ri,t′
r-i-t-prime the reward at step t-prime of episode i.
In plain words

For each step t, add up the rewards from t to the end. That is G-i-t. Multiply the score of the action at step t by G-i-t instead of the whole return, then average over episodes.

With numbers

With made-up rewards 1, 1, 1, 1, 10 and gamma 1: the whole return is 14 for every step. The reward-to-go is 14, 13, 12, 11 and 10, so the last action gets credit for its own 10 only.

Credit each step with what came after

Warm bars are rewards. Purple bars are the weight each step's action gets. Pick a step and switch between the full return and the reward-to-go.

3

Two illustrative episodes, gamma 1. The second is the worked example above.

Why is this allowed? Given the state, the policy chooses the action at step t after an earlier reward is already fixed. So the score of that action times the earlier reward averages to zero. Dropping those terms keeps the average gradient and removes their noise.

The failure. Take the episode that wins 10 at step 0 and loses 10 at step 5. The full return is 0, so no action gets credit or blame. With reward-to-go the first action still sees 0, but each later action sees the −10 ahead of it. The symptom of skipping reward-to-go is slow learning on long episodes. To measure it, compare the gradient's spread with and without it on the same batch. The fix costs one loop from the last step back to the first.

An episode pays 2, 0, 3 with gamma 1. What is the reward-to-go at step 1, the second step?

Chapter 8

Baselines: Subtract the Usual, Keep the Average

Compare each return with a typical return, so an action goes up only when it beat the usual

In the toy every arm pays about 5, so every taken action goes up, even the weak arm A. Learning still works, because B goes up more, but each push is mostly noise. Ask "better than usual?" instead of "good?".

Pick a number for the usual return, the baseline b. It may depend on the state but not on the action. Subtract it from the reward-to-go. The difference, G-t minus b, is the advantage: how much better this action did than usual in this state.

Say it aloud

Nabla-theta of J is about one over N times the sum over i and t of the score of a-i-t given s-i-t, times G-i-t minus b of s-i-t.

∇θJ
nabla-theta of J how to turn every knob to raise the average return.
(1/N) Σi Σt
one over N times the sum over i and t add over the steps of each episode, then average over the N episodes.
∇θ log πθ(ai,t|si,t)
the score of a-i-t which way makes that action more likely.
Gi,t
G-i-t the reward-to-go, from Chapter 7.
b(si,t)
b of s-i-t the baseline: the usual return from that state, such as a running average or a learned value.
In plain words

At each step, subtract the usual return b from the reward-to-go G. If the difference is positive, push the action up; if negative, push it down.

With numbers

With the toy's numbers and b = 4.8: B pays 6, so its weight is +1.2 and B goes up. A pays 4, so its weight is −0.8 and A goes down. Without the baseline both went up.

Why does b leave the average alone? Here is the proof for one state s.

  1. Average the baseline term over actions. The baseline has no a in it, so it comes out.
    Ea∼π[ ∇log π(a|s) b(s) ] = b(s) Σa π(a|s) ∇log π(a|s)
  2. Use the trick backwards: a chance times its score is the gradient of the chance.
    = b(s) Σa ∇π(a|s) = b(s) ∇ Σa π(a|s)
  3. The chances add to 1 for every θ, and the gradient of a constant is 0.
    = b(s) ∇1 = 0

Shift every reward and compare the spread

The same 400 estimates of θ-B's gradient as Chapter 6, with N = 1. Add a constant to every reward, then switch the baseline on.

0

Here the baseline is the exact usual return, J. A real one comes from other episodes, as the failure below explains.

With nothing added, the spread is 2.56 without a baseline and 0.57 with one, and the mean is 0.36 both ways. Variance is the spread squared, so the baseline is worth (2.56 / 0.57)2, about 20 times more episodes. Add 10 to every reward and the factor grows to 157.

The failure. A baseline taken from the same batch it corrects leaks each return into its own baseline. With the plain batch mean, the expected gradient shrinks by a factor of 1 − 1/N. The symptom is slower learning with small batches. The fix is the mean of the other episodes, or a value learned from earlier data.

Why does subtracting a baseline b(s) leave the expected gradient unchanged?

Chapter 9

Beyond REINFORCE: Actor-Critic, TRPO and PPO

See what each later method changes in the same loop: who gives the baseline, how often to reuse a batch, how far to step

REINFORCE has two costs: a noisy gradient and fresh data for every step. The methods after it attack those costs. Each keeps the same core: the score of an action times an advantage.

MethodWhat it changesThe trade
Actor-criticA learned value V(s), the critic, is the baseline. One real reward plus gamma times V of the next state replaces the full reward-to-go.Less noise, some bias from an imperfect V.
GAE (Schulman et al., 2016)Blends one-step and many-step advantages with a knob λ from 0 to 1.λ = 1 is reward-to-go minus V; λ = 0 is the one-step version.
Natural gradient (Kakade, 2001)Measures a step by how much the policy's choices change, using the Fisher matrix, not by how far θ moves.Same step in any parameterisation; costly for big networks.
TRPO (Schulman et al., 2015)Takes the largest step that keeps the average KL divergence, a measure of how different two probability lists are, below a limit.Stable, but needs second-order maths and a line search.
PPO (Schulman et al., 2017)Reuses a batch for several passes and clips the objective so no sample pushes too far.First-order and simple; no hard limit on the step.

Reusing a batch needs a correction, because the episodes came from the old policy. Weight each step by the probability ratio r-t: the new policy's chance of the action divided by the old policy's chance. Ratios for a whole trajectory multiply, and that explodes: 1.1 per step over 100 steps is about 13,780. So these methods use one ratio per step, which is an approximation that holds only while the two policies stay close.

Say it aloud

L-clip of theta equals the average over t of the minimum of r-t times A-hat-t, and r-t clipped between one minus epsilon and one plus epsilon, times A-hat-t.

LCLIP(θ)
L-clip of theta PPO's objective; gradient steps raise it.
Et
the average over t the average over all steps in the batch.
min
the minimum keep the smaller of the two terms, the more cautious one.
rt(θ)
r-t of theta the probability ratio: the new chance of a-t over the old chance.
Ât
A-hat-t the advantage estimate for step t, fixed from the old policy.
clip(r, 1−ε, 1+ε)
r clipped between one minus epsilon and one plus epsilon the ratio held inside a band; epsilon, such as 0.2, is the band's half-width.
In plain words

Multiply the ratio r-t by the advantage, and also the clipped ratio. Keep the smaller. Once the ratio leaves the band in the way the advantage wants, the objective goes flat and that sample stops pushing.

With numbers

With made-up numbers A-hat = +2, epsilon 0.2 and ratio 1.5: the plain term is 3.0. The clipped term is 1.2 × 2 = 2.4, so PPO keeps 2.4.

Clip the objective

Purple is PPO's objective for one sample as the ratio changes. Dashed is the ratio times the advantage, unclipped. Flip the advantage's sign, widen epsilon, move the ratio.

0.20
1.50

One sample with a fixed advantage of plus or minus 2. Toy numbers.

The failure. Clipping limits each sample, not the policy as a whole, so many passes over one batch can still drift far. The symptom is a KL between old and new policy that climbs each pass. Log the average KL and the share of clipped samples to measure it. The fix is fewer passes, or stopping when KL passes a limit.

In PPO with A-hat = +2 and epsilon 0.2, what objective does a sample with ratio 1.6 give?

Chapter 10

The Field Guide

Keep the equations, the numbers, a checklist and the core code on one page

A policy gives each action a probability. Run it, score each episode, and push up the log-probability of each action in proportion to how much better than usual its future turned out. The world's dynamics drop out, so you need only samples. The estimate is unbiased and noisy; reward-to-go and a baseline cut the noise without changing the average.

The estimator, one fix at a time

VersionWeight on the score of a-tWhat it fixes
REINFORCER(τ), the whole returnNothing yet: unbiased, but noisy
+ reward-to-goG-t, rewards from t onDrops past rewards an action cannot change
+ baselineG-t − b(s-t), the advantageRemoves the common offset in every return
Actor-criticr-t + γV(s-t+1) − V(s-t)Less noise again, at the cost of some bias
PPOclipped ratio times Â-tReuses a batch without steps that run away

The numbers from this page

WhatNumberWhy it matters
Softmax of logits 1, 0, −166.5%, 24.5%, 9.0%Logits are shares after e and a divide
Steps until gamma to the t < 0.14 at 0.5; 230 at 0.99Gamma sets how far ahead the agent looks
Toy objective at 0.5, 0.3, 0.2J = 4.8The average return the policy has now
Exact toy gradient−0.40, +0.36, +0.04Lower A, raise B, leave C
Spread for θ-B, N = 12.56; 0.57 with a baselineA baseline is worth about 20 times the episodes
Corridor, batch 1, step 6about half the runs trappedSmall batches and big steps lock in early luck
Trajectory ratio, 1.1 over 100 stepsabout 13,780Why off-policy methods use one ratio per step

Before you trust a policy gradient run

The surrogate loss

Code never writes the gradient formula. It builds one number, the sum of log π(a|s) times the detached weights, and calls backward once. The gradient of that number equals the estimate. Its value means nothing, and it is valid only at the policy that collected the data.

pythonimport torch

def reinforce_losses(policy, value_net, states, actions, rewards, gamma=0.99):
    # one finished episode: states [T, obs_dim], actions [T, act_dim], rewards [T]
    T = len(rewards)
    returns, G = torch.zeros_like(rewards), 0.0
    for t in reversed(range(T)):                 # reward-to-go, one loop back
        G = rewards[t] + gamma * G
        returns[t] = G
    values = value_net(states).squeeze(-1)           # [T], the baseline b(s_t)
    adv = (returns - values).detach()                # the advantage, a fixed weight
    logp = policy(states).log_prob(actions).sum(-1)   # [T], Gaussian: sum over action dims
    disc = gamma ** torch.arange(T, dtype=rewards.dtype)  # the gamma-to-the-t factor
    policy_loss = -(disc * logp * adv).sum()          # minus: optimisers go downhill
    value_loss = ((values - returns.detach()) ** 2).mean()
    return policy_loss, value_loss                      # average over episodes, then backward

Which network for the policy

InputNetworkOutput
State vectors (joint angles, speeds)MLP, 2 to 3 hidden layersSoftmax logits, or a Gaussian mean and spread
Camera pixelsCNN, then an MLP headThe same two kinds
Partial views over timeRNN or LSTM over past observationsThe same two kinds
Several good actions at onceDiffusion policyNeeds extra tricks, since log π is not free

Keep going

The takeaway. Push up the log-probability of each action by how much better than usual its future turned out. The world's model never appears. Everything after REINFORCE is a way to make that push less noisy or to reuse data safely.
Which change lowers the variance of the policy gradient without changing its average?

Now press Present or Teach and derive the policy gradient from memory: the log-derivative trick, the dynamics that cancel, then reward-to-go and the baseline proof. Then go back to the hero, run it without a baseline and with one, and say why the second run is steadier.

Credit and source

This lesson re-teaches Lecture 3, Policy Gradients, of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it: Williams (1992), REINFORCE; Sutton, McAllester, Singh and Mansour (2000), the policy gradient theorem; Kakade (2001), the natural policy gradient; Schulman et al., TRPO (2015), GAE (2016) and PPO (2017). The toys and numbers here are our own.

CS 224R: Policy Gradients
The course site · PPO · TRPO · Back to Gleams