CS 285 HW2: Policy Gradients

A policy gradient pushes up every action that came before a high return. The raw push is noisy. On our CartPole toy, one fix, reward-to-go, balances the pole within 55,000 steps in 10 of 10 seeds. The raw return does it in 5.

A lesson with a workbook. Each chapter explains one part of Homework 2, then gives you exercises on our own toy data.

Press Train and watch the average return climb toward 200, the most a CartPole episode can earn. Switch the estimator and train again. Then switch the batch to 4,000 steps and see what the same 100,000 steps buy. Then we build each rung of the ladder.

You need Policy Gradients and Actor-Critic. The exercises run JavaScript in your browser.

A workbook on Homework 2 of UC Berkeley CS 185/285, Deep Reinforcement Learning, taught by Sergey Levine. It draws on the handout, Lecture 5, Lecture 6 and Section 3. The words, toys and devices here are our own.

Train REINFORCE on CartPole

Illustrative, our toy: the classic cart-pole equations in JavaScript, capped at 200 steps. A linear softmax policy, Adam at learning rate 0.2, discount 0.99, a budget of 100,000 steps. Random play averages 22.

Workbook progress
0 / 31 exercises (0%)
0
Day streak
Best: 0
31 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser; the matching numpy sits beside the chapter.

Chapter 0

The Map: What You Build

See one agent and the five fixes that each rewrite one array

Homework 2 builds one policy gradient agent. Then it adds fixes for noise, one at a time. Each fix rewrites one array: the weight that multiplies the log-probability of each step. The policy update itself never changes.

A batch is every step the agent collects in one iteration, from several episodes stored end to end. Each fix reads the batch and writes one number per step. So every array in this lesson has one entry per step.

Climb the ladder

Each box is one stage of an iteration. Choose a rung to see which stages it uses and what each array holds for a batch of 1,000 steps.

The stages follow the handout's agent and the loop in Lecture 6. The array lengths are for one 1,000-step batch.

PartWhere it livesChapter
The policy updatethe pseudo-loss: log-probability times weight1
Rewards to weightspg_agent.py: calculate_q_vals, Case 1 and Case 22
The value baselineestimate_advantage and the value step in PGAgent.update3
GAEestimate_advantage, the lambda branch4
Normalisationthe last step of estimate_advantage5
Tuningthe settings: batch, learning rate, discount, lambda6

The failure to expect: a wrong weight does not crash. The agent learns slower, or learns to fail. So test each function on a tiny episode first, the way the workbook does.

The road

  1. REINFORCE as weighted likelihood: the pseudo-loss and its sign. The hero's Full return.
  2. Reward-to-go and the two discounts: which rewards each step may claim. The hero's Reward-to-go.
  3. Baselines and where the hats go: subtract a value, keep the average.
  4. GAE in one backward pass: mix the critic with real rewards.
  5. Normalisation and its bias: rescale the batch. The hero's RTG + normalise.
  6. Tuning for sample efficiency: count environment steps. The hero's batch.
  7. Field guide: numbers, checklist, the core loop.
You switch reward-to-go on. Which array changes?

Workbook

Exercise 0.1: How many steps in a batch? Derive
Our toy collects whole episodes until the batch holds at least 1,000 steps. The episodes last 180, 200, 200, 150, 200 and 120 steps. How many entries does the weight array hold?
entries
Show derivation
after 5 episodes: 180 + 200 + 200 + 150 + 200 = 930, still under 1,000
the sixth episode runs to its end: 930 + 120 = 1,050
One weight per step, so 1,050 entries. The batch size is a floor, not an exact count.
Exercise 0.2: Order one iteration Design
Tap the chips in the order one iteration runs them, with GAE and normalisation on.
?
→
?
→
?
→
?
→
?
normalise the advantages run the policy for a batch take the policy step GAE from rewards and values predict V for every state
Exercise 0.3: Where does the critic learn? Trace
The value network gives the baseline. Which data does it learn from in one iteration?

Chapter 1

REINFORCE as Weighted Likelihood

Build a loss whose gradient is the policy gradient, and get its sign right

The agent's policy update never writes a gradient by hand. It builds a pseudo-loss: a number whose gradient is the policy gradient. Autograd does the rest. The policy step in the homework is this one loss.

Policy Gradients derives the estimate. The gradient of the average return equals the average of each step's ∇ log π times a weight. So the loss is the log-likelihood from behaviour cloning, with each step scaled by its weight. Good steps become more likely, bad ones less.

∇θJ ≈ (1/N) Σi Σt ∇θ log πθ(at | st) · Q̂t
Say it aloud

Grad-theta of J is about one over N, times the sum over episodes i and steps t, of grad-theta log pi-theta of a-t given s-t, times Q-hat-t.

∇θJ
grad-theta of J the direction to move the policy weights θ that raises the average return J fastest.
(1/N) Σi Σt
one over N, the sum over i and t add one term per step of every episode, then divide by the N episodes.
∇θ log πθ(at | st)
grad-theta log pi-theta of a-t given s-t the direction that makes the action taken at step t more likely.
Q̂t
Q-hat-t the weight on step t. Chapters 2 to 5 choose it.
In plain words

For each step, find the push that makes its action more likely. Scale the push by the weight Q-hat-t. Average the pushes and step θ that way.

With numbers

With made-up numbers: two steps with pushes +0.7 and −0.3 on one weight, and weights Q-hat 2 and 1. The sum is 1.4 − 0.3 = 1.1. One episode, so ∇J ≈ 1.1.

A softmax policy turns one score z per action into chances: π(a) = eza / Σb ezb. Its push on the scores has a closed form.

∇z log π(a) = ea − π
Say it aloud

Grad-z of log pi of a equals e-a minus pi.

∇z log π(a)
grad-z of log pi of a how each action score should move to make action a more likely. One number per action.
ea
e-a a one-hot vector: 1 at the action taken, 0 elsewhere.
π
pi the vector of current chances, which sums to 1.
In plain words

Raise the score of the action taken by one minus its chance. Lower every other score by its own chance.

With numbers

Scores z = (0, 0, 0), so π = (1/3, 1/3, 1/3). Take action 2: the push is (−0.333, 0.667, −0.333). With weight Q-hat = 2 and step size 0.5, the scores move by 0.5 × 2 × push. The chance of action 2 rises from 0.333 to 0.576.

Push the chances with a weight

Each bar is the chance of one action. Set the weight, then sample. A positive weight makes the sampled action more likely; a negative one makes it less likely.

2.0

Our toy: one state, three actions, step size 0.5. The update is the softmax push above, times the weight.

The trap: the sign of the pseudo-loss

symptom
The average return falls from about 22 to 9 or 10 within ten iterations, below random play. On our toy this takes 10,000 steps.
see it
Print the average return each iteration. A falling curve from the first iteration means the agent climbs the wrong way.
fix
An optimiser minimises. The loss is -(logp * weight).mean(), with the minus. Treat the weight as a constant: no gradient flows into it.
The chances are (0.2, 0.5, 0.3). You sample action 1 and its weight is −1. Which way does the score of action 1 move?

Workbook

Exercise 1.1: One component of the push Derive
The scores are z = (1, 0, −1). The agent took action 1 (the first). What is the first component of ∇z log π(a)? Give 3 decimals.
push
Show derivation
e1 = 2.718, e0 = 1, e−1 = 0.368; sum = 4.086
π(1) = 2.718 / 4.086 = 0.665
first component = 1 − 0.665 = 0.335
The action was already likely, so its push is small. Rare actions that pay get the largest push.
Exercise 1.2: Write the softmax push Build
  1. Subtract the largest score from every score, so Math.exp cannot overflow.
  2. Turn the scores into chances that sum to 1.
  3. Return a new array: the one-hot of a minus the chances.
Show solution
javascriptfunction softmaxPush(z, a) {
  const m = Math.max(...z);
  const e = z.map(v => Math.exp(v - m));
  const s = e.reduce((x, y) => x + y, 0);
  return e.map((v, i) => (i === a ? 1 : 0) - v / s);
}
Exercise 1.3: Why the agent learns to fail Debug
A neighbouring toy agent in PyTorch. Its return drops below random play from the first iteration. Click the buggy line.
logits = policy(obs)                      # [B, n_actions]
logp = logits.log_softmax(-1)[range(B), acts]
weight = torch.as_tensor(q_vals)          # constant, no grad
loss = (logp * weight).mean()
opt.zero_grad(); loss.backward(); opt.step()
Show why
Line 4 has no minus. The optimiser lowers the weighted log-likelihood, so high-return actions become less likely. Write -(logp * weight).mean().
Exercise 1.4: Why not differentiate the sample average? Trace
You estimate J by (1/N) Σ r(τi) over sampled episodes and call autograd on it. The gradient is zero. Why?

Chapter 2

Reward-to-Go and the Two Discounts

Give each step only the rewards after it, and count the discount from that step

calculate_q_vals has two cases. Case 1 gives every step of an episode the same weight: the discounted return of the whole episode. Case 2 gives step t only the rewards from t on. That is reward-to-go: an action cannot change a reward that came before it.

A discount can run on two clocks. The absolute discount counts from the start of the episode: a reward at step t′ gets γt′. The relative discount counts from the current step: γt′−t. Case 2 uses the relative one.

Q̂t = Σt′=tH−1 γt′−t rt′
Say it aloud

Q-hat-t equals the sum over t-prime from t to H minus one, of gamma to the t-prime minus t, times r-t-prime.

Q̂t
Q-hat-t the reward-to-go: the weight on step t.
Σt′=tH−1
the sum over t-prime from t to H minus one add the rewards from step t to the last step. H is the episode length.
γt′−t
gamma to the t-prime minus t the relative discount: 1 for the reward at step t, γ one step later, and so on.
rt′
r-t-prime the reward at step t-prime.
In plain words

Start at step t. Add its reward, then the next reward times gamma, then the one after times gamma squared, to the end of the episode.

With numbers

Four rewards of 1 and γ = 0.9. Q-hat = 3.439, 2.71, 1.9, 1. Case 1 gives all four steps 3.439.

The absolute version claims the same rewards, but each weight carries an extra γt from the episode start.

wt = γt Q̂t
Say it aloud

w-t equals gamma to the t, times Q-hat-t.

wt
w-t the weight on step t under the absolute discount.
γt
gamma to the t the discount from the episode start to step t.
Q̂t
Q-hat-t the relative reward-to-go from the equation above.
In plain words

Take the reward-to-go of step t. Shrink it once more by gamma for every step since the episode began.

With numbers

The same four rewards: w = 3.439, 2.439, 1.539, 0.729. At γ = 0.99, step 150 keeps 0.99150 = 0.22 of its weight.

Compare the weights step by step

A CartPole episode of 100 steps, reward 1 each. Each bar is the weight on one step. Choose a rule, then drag gamma.

0.990

Our toy episode. The three rules are the handout's Case 1, the absolute reward-to-go, and Case 2.

Why the relative clock? Under the absolute one, late states learn with a fraction of the push. A CartPole state at step 150 needs the same correction as one at step 5. The relative clock asks one thing of every state: prefer rewards sooner.

Why dropping past rewards keeps the average (the proof)
  1. Take one past reward rt′ with t′ < t. Fix everything up to step t: that fixes rt′ and st.
  2. Only at is still random. Its term averages to rt′ × Σa π(a | st) ∇ log π(a | st).
  3. π ∇ log π = ∇π, so the sum is ∇ Σa π(a | st) = ∇1 = 0.
  4. Every past reward adds zero on average. Dropping them changes the noise, not the mean.

The trap: reward-to-go across the episode boundary

symptom
The batch stores episodes end to end. A reward-to-go over the flat array runs past each episode's end, so a 9-step failure claims the next episode's 200 rewards.
see it
Two episodes, rewards (1, 1) then (1, 1, 1), γ = 1. Correct: 2, 1, 3, 2, 1. The flat sum gives 5, 4, 3, 2, 1.
fix
Compute the sum per episode, from its last step back. In the homework the rewards arrive as one array per episode.
With γ = 0.99 and the absolute discount, how strongly does step 100 learn compared with step 0, for the same reward-to-go?

Workbook

Exercise 2.1: Reward-to-go by hand Derive
An episode has rewards (0, 0, 1, 0, 2) and γ = 0.9. What is the relative reward-to-go Q̂ at step 1 (the second step)? Give 3 decimals.
Q̂1
Show derivation
Q̂1 = r1 + 0.9 r2 + 0.81 r3 + 0.729 r4
= 0 + 0.9 × 1 + 0.81 × 0 + 0.729 × 2 = 0.9 + 1.458 = 2.358
The absolute version would be 0.9 × 2.358 = 2.122.
Exercise 2.2: How much push is left late? Derive
Under the absolute discount with γ = 0.99, what fraction of its weight does step 150 keep? Give 3 decimals.
fraction
Show derivation
fraction = γ150 = 0.99150 = e150 × ln 0.99 = e−1.508 = 0.221
Step 150 learns at about a fifth of the strength of step 0. Late states of a long episode barely move.
Exercise 2.3: Write reward-to-go Build
A neighbouring version for one episode: an array of rewards in, an array of weights out.
  1. Walk from the last step to the first.
  2. Keep a running sum G. At each step set G = rt + γ G.
  3. Write G into a new array at index t. Do not change the input.
Show solution
javascriptfunction rewardToGo(rews, gamma) {
  const out = new Array(rews.length);
  let G = 0;
  for (let t = rews.length - 1; t >= 0; t--) {
    G = rews[t] + gamma * G;
    out[t] = G;
  }
  return out;
}
Exercise 2.4: Which states learn under Case 1? Trace
With Case 1, every step of an episode gets the same weight. A CartPole episode makes a good move at step 5 and a fatal one at step 40. What does the gradient do to these two moves?

Chapter 3

Baselines and Where the Hats Go

Subtract a learned value from the weight, and see which errors bias the push

With the baseline on, estimate_advantage subtracts the value network's prediction from the reward-to-go. The value network learns from the same discounted reward-to-go. baseline_gradient_steps sets how many regression steps it takes per policy step.

A baseline b(s) is any number that depends on the state but not on the action. Subtracting it is safe, because its push averages to zero over the policy's own actions.

Ea∼π[ ∇ log π(a | s) b(s) ] = b(s) Σa ∇π(a | s) = 0
Say it aloud

The expected value under pi of grad log pi of a given s, times b of s, equals b of s times the sum over a of grad pi of a given s, which is zero.

Ea∼π[ ]
the expected value under pi the average over actions drawn from the policy at state s.
∇ log π(a | s)
grad log pi of a given s the push toward action a.
b(s)
b of s the baseline. Here, the value network's prediction V-hat of s.
Σa ∇π(a | s)
the sum over a of grad pi of a given s the gradient of the total chance, which is always 1. So it is 0.
In plain words

Weight every action's push by its chance and by the same b of s. The pushes cancel, because the chances must still sum to one.

With numbers

Two actions with chances 0.4 and 0.6 on one logistic weight: pushes 0.6 and −0.4. With b = 5: 0.4 × 0.6 × 5 + 0.6 × (−0.4) × 5 = 1.2 − 1.2 = 0.

The actor-critic weight r + γV(st+1) − V(st) holds two values. A hat marks a learned value, V̂, which has errors. Which hats are safe? A hat on V(st) is a baseline. A hat on V(st+1) is not, because the next state depends on the action.

bias = γ E[ ∇ log π(at | st) ( V̂(st+1) − V(st+1) ) ]
Say it aloud

The bias equals gamma times the expected value of grad log pi of a-t given s-t, times V-hat of s t plus one minus V of s t plus one.

bias
bias how far the average push lands from the true policy gradient.
γ
gamma the discount on the next state's value, 0.9 here.
E[ ]
the expected value the average over the action and the next state it leads to.
V̂(st+1) − V(st+1)
V-hat of s t plus one, minus V of s t plus one the critic's error at the next state.
In plain words

Look at the critic's error at each next state. If actions that lead to over-valued states get an extra push, the average push carries a bias. If the error is the same everywhere, it cancels like a baseline.

With numbers

With made-up numbers: chance 0.4 of action R, γ = 0.9. R reaches state A half the time, L reaches it 80% of the time. The critic is 2 too high at A only. Bias = 0.9 × 0.4 × 0.6 × (0.5 × 2 − 0.8 × 2) = −0.13, on a true gradient of −0.648.

Place the hats

Choose which values come from the learned critic. Drag its errors. The bars show the true gradient and the average push, computed exactly.

+2.0
+1.0

Our toy: V(A) = 10, V(B) = 0, γ = 0.9, reward 0, chance of R 0.4. The four placements are the quick exercise in Section 3.

The trap: value targets with another discount

symptom
The value net fits undiscounted sums while the weights use γ = 0.99. On a 200-step episode the mean advantage is −43, not near 0, and the baseline removes little noise.
see it
Print the mean advantage over the batch. With a working baseline it sits near zero.
fix
Train the value net on the same relative reward-to-go that the policy uses.
The critic is 3 too high at every state. You use r + γV̂(st+1) − V̂(st). Is the average push biased?

Workbook

Exercise 3.1: The bias of a hat Derive
The device's toy: chance of R is 0.4, γ = 0.9. R reaches B half the time; L reaches B 20% of the time. The critic is exact at A and 3 too high at B. The weight is r + γV̂(st+1) − V(st). What is the bias of the average push? Give 4 decimals.
bias
Show derivation
push on R: 1 − 0.4 = 0.6, weighted by its chance: 0.4 × 0.6 = 0.24
push on L: −0.4, weighted: 0.6 × (−0.4) = −0.24
average error after R: 0.5 × 3 = 1.5; after L: 0.2 × 3 = 0.6
bias = 0.9 × (0.24 × 1.5 − 0.24 × 0.6) = 0.9 × 0.216 = 0.1944
R leads to the over-valued state more often, so R gets pushed up too much.
Exercise 3.2: Which placements are unbiased? Trace
The weight is r + γV(st+1) − V(st), with each V either true or learned. Which placements give an unbiased gradient for any critic?
Exercise 3.3: A baseline that peeks ahead Debug
A neighbouring toy agent. Its policy improves slower than with no baseline at all. Click the buggy line.
q = reward_to_go(rews, gamma)           # [T]
v = critic(next_obs).squeeze(-1)        # [T]
adv = q - v.detach().numpy()
critic_loss = ((critic(obs).squeeze(-1) - torch.as_tensor(q)) ** 2).mean()
Show why
Line 2 predicts the value of the next state. That value depends on the action, so it is not a baseline, and it is one step off the reward-to-go. Use critic(obs).
Exercise 3.4: A constant error at the next state Trace
In the device, choose "Hat on V(st+1)" and switch on "Same error at B as at A". Set the error to +3. What is the bias?

Chapter 4

GAE in One Backward Pass

Mix every n-step estimate with one weight, lambda, and compute it from the end back

With GAE on, estimate_advantage mixes n-step advantages with a weight λ. The code computes the mix in one backward pass.

The TD error δt is a one-step advantage: the reward plus the critic's guess for the next state, minus its guess for this one. The done flag dt is 1 at the last step of an episode, where there is no next state.

δt = rt + γ (1 − dt) V̂(st+1) − V̂(st)
Say it aloud

Delta-t equals r-t, plus gamma times one minus d-t times V-hat of s t plus one, minus V-hat of s-t.

δt
delta-t the TD error at step t.
rt
r-t the reward at step t.
γ
gamma the discount.
(1 − dt)
one minus d-t the mask: 0 at an episode's last step, so nothing comes from the next episode.
V̂(st+1)
V-hat of s t plus one the critic's guess for the next state.
V̂(st)
V-hat of s-t the critic's guess for this state.
In plain words

Take the reward. Add the next state's value, shrunk by gamma, unless the episode ended. Subtract this state's value.

With numbers

With made-up numbers: rewards (1, 0, 2), V-hat (2.0, 1.5, 1.8), γ = 0.9, the last step done. δ0 = 1 + 1.35 − 2.0 = 0.35; δ1 = 0 + 1.62 − 1.5 = 0.12; δ2 = 2 − 1.8 = 0.2.

Ât = δt + γλ (1 − dt) Ât+1
Say it aloud

A-hat-t equals delta-t, plus gamma lambda times one minus d-t, times A-hat t plus one.

Ât
A-hat-t the GAE advantage: the weight on step t.
δt
delta-t the TD error from the equation above.
γλ
gamma lambda how much of the next step's advantage carries back. λ is between 0 and 1.
(1 − dt)
one minus d-t the same mask: the carry stops at an episode's end.
Ât+1
A-hat t plus one the advantage already computed for the next step.
In plain words

Start at the last step with A-hat equal to its delta. Walk back. At each step, add gamma lambda times the advantage you just computed to this step's delta.

With numbers

The same episode with λ = 0.8, so γλ = 0.72. A-hat2 = 0.2; A-hat1 = 0.12 + 0.72 × 0.2 = 0.264; A-hat0 = 0.35 + 0.72 × 0.264 = 0.540.

What does the pass mix? An n-step advantage Â(n) uses n real rewards, then the critic. Unrolled, the recursion puts a weight on each one, and the full-episode estimate takes the weight left over.

Ât = (1 − λ) Σn=1H−t−1 λn−1 Ât(n) + λH−t−1 Ât(H−t)
Say it aloud

A-hat-t equals one minus lambda, times the sum over n from one to H minus t minus one of lambda to the n minus one times A-hat-t-n, plus lambda to the H minus t minus one times A-hat-t with H minus t steps.

Ât
A-hat-t what the backward pass returns.
(1 − λ) Σ λn−1
one minus lambda, the sum of lambda to the n minus one weights 0.2, 0.16, 0.128 and so on at λ = 0.8, for the short estimates.
Ât(n)
A-hat-t-n the advantage from n real rewards, then the critic's guess n steps ahead.
λH−t−1
lambda to the H minus t minus one the weight left over. All weights sum to 1.
Ât(H−t)
A-hat-t with H minus t steps the full reward-to-go minus V-hat of s-t.
In plain words

Give the 1-step estimate a share of one minus lambda, the 2-step estimate lambda times that, and so on. Whatever share is left goes to the full-episode estimate.

With numbers

At step 0 of the same episode: A-hat(1) = 0.35, A-hat(2) = 0.458, A-hat(3) = 0.62. Weights 0.2, 0.16, 0.64: 0.07 + 0.073 + 0.397 = 0.540, the same as the pass.

A correction to the source. The handout's equation 18 and Section 3's equation 58 write the finite mix with a normaliser (1 − λ) / (1 − λk). On this episode those give 0.398 and 0.456. The backward pass, and the handout's own sum of discounted δ (its equation 21), give 0.540: the weights above.

Find the best lambda

Each column is one λ. Purple is the bias of the average push, squared. Yellow is the noise of a 16-episode batch. Drag λ, switch the critic error, and add reward noise.

0.80
0.50

Our toy: a 5-cell chain, 6 steps at most, reward 1 at the far end plus Gaussian noise, γ = 0.9, chance of moving right 0.6. The exact advantage comes from dynamic programming; 4,000 sampled episodes per column.

Read the device: at λ = 0 the critic's error becomes bias. At λ = 1 the bias is gone and every reward's noise adds up. More reward noise moves the best λ lower.

The trap: no mask at the episode boundary

symptom
The flat batch holds episodes end to end. Without the mask, the last step of one episode bootstraps from the first state of the next. Its advantage then soaks up the next episode's errors.
see it
Put two copies of one 3-step episode end to end. Both copies must get the same advantages. Without the mask, the first copy's differ.
fix
Multiply by (1 − dt) in both places: the next value in δt, and the carry in the recursion.
What does GAE give at λ = 0?

Workbook

Exercise 4.1: One backward pass by hand Derive
Rewards (0, 1, 1), V̂ = (1.0, 1.2, 0.6), γ = 0.9, λ = 0.5, and the last step is done. What is Â0? Give 3 decimals.
Â0
Show derivation
δ2 = 1 − 0.6 = 0.4 (done: no next value)
δ1 = 1 + 0.9 × 0.6 − 1.2 = 0.34
δ0 = 0 + 0.9 × 1.2 − 1.0 = 0.08
γλ = 0.45: Â2 = 0.4, Â1 = 0.34 + 0.45 × 0.4 = 0.52, Â0 = 0.08 + 0.45 × 0.52 = 0.314
Exercise 4.2: The weight left for the full estimate Derive
An episode has H = 4 steps and λ = 0.9. At step 0, what weight does the backward pass give the full-episode estimate Â0(4)? Give 3 decimals.
weight
Show derivation
short weights: 0.1, 0.09, 0.081 for n = 1, 2, 3; their sum is 0.271
left over: λH−t−1 = 0.93 = 0.729 = 1 − 0.271
Near the end of a short episode, GAE leans on real rewards, whatever λ says.
Exercise 4.3: Write GAE with the mask Build
A neighbouring version over a flat batch. vals[t] is V̂(st); the next state's value is vals[t+1] unless dones[t] is 1. Every batch ends with a done.
  1. Walk from the last index to the first, carrying the next advantage.
  2. Compute δt with the mask on the next value.
  3. Set At = δt + γλ(1 − dt) × carry.
Show solution
javascriptfunction gae(rews, vals, dones, gamma, lam) {
  const T = rews.length, A = new Array(T);
  let carry = 0;
  for (let t = T - 1; t >= 0; t--) {
    const m = 1 - dones[t];
    const vNext = m ? vals[t + 1] : 0;
    const delta = rews[t] + gamma * vNext - vals[t];
    carry = delta + gamma * lam * m * carry;
    A[t] = carry;
  }
  return A;
}
Exercise 4.4: The two ends of lambda on the chain Trace
In the device, keep the critic error on. Compare λ = 0 with λ = 1. Which statement matches what the bars show?
Exercise 4.5: Order the backward pass Design
Tap the chips in the order the code runs them for one step t, from the start of the loop body.
?
→
?
→
?
→
?
store A[t] = carry m = 1 − dones[t] carry = delta + γλ m carry delta = r + γ m V[t+1] − V[t]

Chapter 5

Advantage Normalisation and Its Bias

Rescale the batch to mean 0 and spread 1, and see what that costs a small batch

With normalisation on, the agent rescales the batch's advantages before the policy step. It subtracts their mean and divides by their spread. This is the last step of estimate_advantage.

Āt = ( Ât − μ ) / ( σ + ε )
Say it aloud

A-bar-t equals A-hat-t minus mu, over sigma plus epsilon.

Āt
A-bar-t the normalised weight on step t.
Ât − μ
A-hat-t minus mu the advantage minus μ, the mean over the whole batch.
σ + ε
sigma plus epsilon the batch's standard deviation, plus ε = 10−8 so an all-equal batch does not divide by zero.
In plain words

Find the mean and the spread of all advantages in the batch. Subtract the mean from each one. Divide by the spread.

With numbers

With made-up numbers: A-hat = (3, −1, 0, 2). μ = 1, σ = √2.5 = 1.581. A-bar = (1.26, −1.26, −0.63, 0.63).

It does two jobs. Subtracting μ acts like a constant baseline. Dividing by σ makes the step size the same for a task whose returns are 10 and one whose returns are 10,000. The handout notes that in simple tasks it can stand in for a baseline.

The cost: μ and σ come from the same batch, so each weight depends on the other samples. With one sample, the weight is always 0. With two different samples, it is always +1 and −1. So a small batch shrinks the average push.

Shrink the batch, shrink the push

A two-armed bandit. Each bar is the average normalised push for one batch size, as a share of its large-batch size. Choose a batch size and sample.

Our toy: arm R pays 1 on average and arm L pays 0, both with noise of 1; the chance of R is 0.5. We compute the large-batch size exactly and sample the bars.

The shrink never flips the sign here, and by B = 64 it is under 1%. On our CartPole toy with Adam, normalisation changed little. At batch 1,000 over 10 seeds, reward-to-go reached 195 in 31k to 55k steps, and with normalisation in 31k to 54k. Adam already rescales each step.

The trap: normalising each episode alone

symptom
One episode fails in 9 steps and the next balances for 200. Per-episode normalisation gives each episode mean 0, so half the failed episode's steps get pushed up.
see it
Print the mean advantage of each episode. If every one is exactly 0, the normaliser ran per episode.
fix
Compute one μ and one σ over the whole batch, after reward-to-go, the baseline or GAE.
A batch holds one step with advantage 7.3. What weight does normalisation give it?

Workbook

Exercise 5.1: Normalise by hand Derive
A batch has advantages (5, 1, 2, 0). Use the population standard deviation (divide by 4) and ignore ε. What is the normalised weight of the first step? Give 3 decimals.
Ā
Show derivation
μ = (5 + 1 + 2 + 0) / 4 = 2
deviations 3, −1, 0, −2; squares 9, 1, 0, 4; mean 3.5
σ = √3.5 = 1.871; Ā = 3 / 1.871 = 1.604
Exercise 5.2: A batch of two Derive
A batch holds two steps with advantages x and y, x > y. Ignore ε. What normalised weight does the step with x get, for any such x and y?
Ā
Show derivation
μ = (x + y) / 2, so the deviations are ±(x − y) / 2
σ = √(((x − y)/2)2) = (x − y) / 2
Ā(x) = ((x − y)/2) / ((x − y)/2) = 1
How much better x was is lost. That is the bias the device measures at B = 2.
Exercise 5.3: Write the normaliser Build
  1. Compute the mean of all entries.
  2. Compute the population standard deviation: divide the sum of squares by n.
  3. Return (a − mean) / (std + eps) for each entry, as a new array.
Show solution
javascriptfunction normalizeAdv(adv, eps) {
  const n = adv.length;
  const mu = adv.reduce((a, b) => a + b, 0) / n;
  const sd = Math.sqrt(adv.reduce((a, b) => a + (b - mu) ** 2, 0) / n);
  return adv.map(a => (a - mu) / (sd + eps));
}
Exercise 5.4: Find the per-episode normaliser Debug
A neighbouring toy agent: every episode's mean advantage prints as exactly 0. Click the buggy line.
advs = []
for ep_rews, ep_vals in zip(rews_list, vals_list):
    a = reward_to_go(ep_rews, gamma) - ep_vals
    a = (a - a.mean()) / (a.std() + 1e-8)
    advs.append(a)
adv = np.concatenate(advs)
Show why
Line 4 normalises inside the episode loop. Move it after line 6, so one mean and one spread cover the whole batch.

Chapter 6

Tuning for Sample Efficiency

Count environment steps, change one knob at a time, and trust a gap only past its noise

The last part of the homework asks for settings that learn in few environment steps: calls to the simulator. On a real robot, that is the cost. The knobs are the batch size, the learning rate, the discount, the network size, reward-to-go, normalisation and λ.

Iterations hide the cost. A batch of 4,000 steps does four times the work of a batch of 1,000 in each iteration. So plot the return against environment steps: one iteration moves the curve right by its batch size.

Run a sweep under 100,000 steps

Choose a batch and a learning rate, then run three seeds. Each run adds a curve, the mean of its seeds. Flip the x-axis between iterations and environment steps.

batch, in steps

learning rate

Illustrative, our toy CartPole: reward-to-go with normalisation, Adam, γ = 0.99. "Reached" means an iteration's average return first hits 195.

On our toy at learning rate 0.2, batch 500 reached 195 in 18k to 28k steps over 6 seeds. Batch 2,000 needed 74k to 95k. Against iterations, the large batch looks smoother and steadier. Against steps, it is the slowest.

Seeds of one setting differ a lot. Before you call one setting better, put an error bar on each mean. The standard error is how much a mean of n seeds would move if you ran the n seeds again.

SE = s / √n
Say it aloud

S-E equals s over the square root of n.

SE
S-E the standard error of the mean, in the unit of the result (here, steps).
s
s the sample standard deviation of the seeds' results, dividing by n − 1.
√n
the square root of n n is the number of seeds.
In plain words

Find how far the seeds spread around their mean. Divide that by the square root of the number of seeds.

With numbers

With made-up numbers: three seeds reach 195 at 38k, 52k and 61k steps. Mean 50.3k, s = 11.6k, SE = 11.6k / 1.73 = 6.7k. A rival setting 5k faster is inside that noise.

The trap: plotting against iterations

symptom
Batch 4,000 climbs fastest per iteration, so it looks best. Under a fixed step budget it gets only 25 iterations.
see it
Flip the device's x-axis. The order of the curves changes.
fix
Log the steps so far with every iteration, and use that column as the x-axis.
Batch A is 1,000 steps and batch B is 4,000. Both curves reach 195 at iteration 20. Which used fewer environment steps?

Workbook

Exercise 6.1: Iterations in a budget Derive
The budget is 100,000 environment steps and each batch holds 4,000. How many policy steps does the agent take?
iterations
Show derivation
iterations = budget / batch = 100,000 / 4,000 = 25
At batch 500 the same budget buys 200 policy steps.
Exercise 6.2: The standard error of three seeds Derive
Three seeds reach 195 at 30k, 42k and 36k steps. What is the standard error of their mean, in thousands of steps? Give 2 decimals.
k steps
Show derivation
mean = (30 + 42 + 36) / 3 = 36
deviations −6, 6, 0; squares 36, 36, 0; s = √(72 / 2) = 6
SE = 6 / √3 = 3.46
Exercise 6.3: Is the gap real? Trace
Setting A reaches 195 at a mean of 40k steps, SE 6k. Setting B at 46k, SE 7k, both over 3 seeds. What can you say?
Exercise 6.4: Plan a sweep Design
Tap the chips in the order you would run a sweep under a fixed step budget.
?
→
?
→
?
→
?
→
?
run 3 seeds of each value rerun the winner on new seeds run the default as a baseline pick one knob and 3 values compare means at equal steps, with SE

Chapter 7

Field Guide: Where Next

Keep the numbers, the checks and the core loop in one place

Every rung rewrites one array: the weight on each step. Reward-to-go and the baseline cut noise for free. GAE and normalisation buy less noise with a little bias. Count the cost in environment steps.

TermWhat it isNumber to remember
Pseudo-loss−mean(log π × weight)wrong sign: return falls from 22 to about 9
Softmax pushea − π(−1/3, 2/3, −1/3) from equal scores
Reward-to-gorewards from step t on, relative discount(1,1,1,1), γ 0.9: 3.439, 2.71, 1.9, 1
Absolute discountextra γt on each weight0.99150 = 0.22
Baselineany b(s); its push averages to 0mean advantage near 0 when it works
Hat on V(st+1)biased if the error differs by next state−0.13 on −0.648 in our toy
GAEA = δ + γλ(1 − d)Anextλ 0: TD error; λ 1: reward-to-go minus V
Normalisation(A − μ) / (σ + ε) over the batchbatch of 1: 0; batch of 2: ±1
Standard errors / √n over seeds3 seeds: s / 1.73

Build checklist

The core loop, on our toy

pythonimport numpy as np

def reward_to_go(r, gamma):           # one episode
    out, G = np.zeros(len(r)), 0.0
    for t in reversed(range(len(r))):
        G = r[t] + gamma * G; out[t] = G
    return out

def gae(r, v, done, gamma, lam):       # flat batch, done = 1 at episode ends
    A, carry = np.zeros(len(r)), 0.0
    for t in reversed(range(len(r))):
        m = 1 - done[t]
        v_next = v[t + 1] if m else 0.0
        carry = r[t] + gamma * v_next - v[t] + gamma * lam * m * carry
        A[t] = carry
    return A

def normalize(A, eps=1e-8):
    return (A - A.mean()) / (A.std() + eps)

# one iteration: collect -> weights -> step (softmax policy, scores z = W s)
# push on W for step t: outer(onehot(a_t) - pi(s_t), s_t) * weight_t

Keep going

The lectures behind each part

One array, many fixes. Every rung keeps the same update and changes only the weight on each step. Ask of each new trick: what does it do to the weight's mean, and what to its noise?

Teach it back with Teach, or go back to CartPole and race the estimators once more. Credit: UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine, Spring 2026, Homework 2. The handout, slides and starter code belong to the course.

Workbook

Exercise 7.1: Read the symptom Trace
The average return starts at 22 and falls to 9 by iteration 10. Which bug fits?
Exercise 7.2: Diagnose a slow learner Trace
Learning is slow. You print the advantages: the first steps of short episodes have weights near 200, as large as in long episodes. Which bug fits?
Exercise 7.3: Climb the ladder in order Design
Tap the rungs in the order the homework adds them, from the raw estimate up.
?
→
?
→
?
→
?
GAE with λ full discounted return value-net baseline reward-to-go
CS 285 HW2: Policy Gradients
UC Berkeley CS 185/285 · The handout · Back to Gleams