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.
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.
Chapter 0
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.
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.
| Part | Where it lives | Chapter |
|---|---|---|
| The policy update | the pseudo-loss: log-probability times weight | 1 |
| Rewards to weights | pg_agent.py: calculate_q_vals, Case 1 and Case 2 | 2 |
| The value baseline | estimate_advantage and the value step in PGAgent.update | 3 |
| GAE | estimate_advantage, the lambda branch | 4 |
| Normalisation | the last step of estimate_advantage | 5 |
| Tuning | the settings: batch, learning rate, discount, lambda | 6 |
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.
Chapter 1
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.
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.
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 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.
Grad-z of log pi of a equals e-a minus pi.
Raise the score of the action taken by one minus its chance. Lower every other score by its own chance.
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.
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.
Our toy: one state, three actions, step size 0.5. The update is the softmax push above, times the weight.
-(logp * weight).mean(), with the minus. Treat the weight as a constant: no gradient flows into it.Math.exp cannot overflow.a minus the chances.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);
}
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()
-(logp * weight).mean().Chapter 2
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-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.
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.
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.
w-t equals gamma to the t, times Q-hat-t.
Take the reward-to-go of step t. Shrink it once more by gamma for every step since the episode began.
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.
A CartPole episode of 100 steps, reward 1 each. Each bar is the weight on one step. Choose a rule, then drag gamma.
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.
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;
}
Chapter 3
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.
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.
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.
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.
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.
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 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.
Choose which values come from the learned critic. Drag its errors. The bars show the true gradient and the average push, computed exactly.
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.
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()
critic(obs).Chapter 4
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.
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.
Take the reward. Add the next state's value, shrunk by gamma, unless the episode ended. Subtract this state's value.
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.
A-hat-t equals delta-t, plus gamma lambda times one minus d-t, times A-hat t plus one.
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.
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.
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.
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.
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.
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.
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.
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.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;
}
Chapter 5
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.
A-bar-t equals A-hat-t minus mu, over sigma plus epsilon.
Find the mean and the spread of all advantages in the batch. Subtract the mean from each one. Divide by the spread.
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.
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.
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));
}
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)
Chapter 6
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.
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.
S-E equals s over the square root of n.
Find how far the seeds spread around their mean. Divide that by the square root of the number of seeds.
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.
Chapter 7
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.
| Term | What it is | Number to remember |
|---|---|---|
| Pseudo-loss | −mean(log π × weight) | wrong sign: return falls from 22 to about 9 |
| Softmax push | ea − π | (−1/3, 2/3, −1/3) from equal scores |
| Reward-to-go | rewards from step t on, relative discount | (1,1,1,1), γ 0.9: 3.439, 2.71, 1.9, 1 |
| Absolute discount | extra γt on each weight | 0.99150 = 0.22 |
| Baseline | any b(s); its push averages to 0 | mean 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 |
| GAE | A = δ + γλ(1 − d)Anext | λ 0: TD error; λ 1: reward-to-go minus V |
| Normalisation | (A − μ) / (σ + ε) over the batch | batch of 1: 0; batch of 2: ±1 |
| Standard error | s / √n over seeds | 3 seeds: s / 1.73 |
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
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.