A goal pays once, at the end. Q-learning carries that reward back to every cell, one small update at a time. Homework 2 builds this, then PPO and an off-policy actor-critic for a robot arm.
A lesson with a workbook. Each chapter explains one part of the homework, then gives you exercises on our own toy data.
Press Play and watch the value of each cell fill in from the goals. Drag epsilon to change how often the agent tries a random move. Press Move the reward and watch the arrows turn. Then we build each part of the homework.
You need some Python and the idea of a probability. The exercises run JavaScript in your browser.
Based on Homework 2 of Stanford CS224R: Deep Reinforcement Learning (Spring 2026): the handout and the starter code. This page teaches in our own words with our own toy data.
The homework's grid, step reward of minus 1, learning rate 0.2 and discount 0.98. Epsilon stays where you set it here; the homework lowers it from 0.4 to 0.02. The move of the reward is ours.
Chapter 0
See what you build, which file holds each part, and what each run should reach
Problem 1 is a table of numbers. An agent learns to walk a 5 by 4 grid, and you change one reward to see its plan change. Problems 2 and 3 train neural networks for a simulated Sawyer arm with 4 joints. The arm must pick up a hammer and drive a nail.
The arm gets a sparse reward: 1.0 when the nail is in, and 0 at every other step. Problem 2 solves it with PPO, an on-policy method. Problem 3 solves it with an off-policy actor-critic that replays old data. Both start from 20 expert demonstrations.
Each block is one part you write or run, left to right. Choose a problem to see its file, its functions and the result to expect.
Parts and target success rates from the handout. Only the run a function feeds can check it, so test each one on tiny inputs first.
| Part | File and function | Chapter |
|---|---|---|
| P1 explore | gridworld_q_learning.py: greedy_action, choose_action | 1 |
| P1 learn | train_q_learning inner loop | 2 |
| P1 scenarios | run: the path and total reward of each scenario, and why | 3 |
| P2 GAE | on_policy.py: compute_gae | 4 |
| P2 clip | update: ratio and policy_loss | 5 |
| P2 run | update GAE block; plot success to 1M steps, expect 25% or more | 6 |
| P3 BC | off_policy.py: bc | 7 |
| P3 critic | update_critic | 8 |
| P3 actor and runs | update_actor; expect 90% before 100k steps; the UTD run; compare with PPO | 9 |
shellconda env create -f conda_env_modal.yml # once, on your machine conda activate cs224r-hw2 wandb login # paste your API key once python gridworld_q_learning.py # Problem 1: prints three scenarios modal run --detach modal_on_policy.py # Problem 2: PPO, about 1M steps modal run --detach modal_off_policy.py # Problem 3: actor-critic
The failure to expect: a run is slow, and a bug shows up an hour in. Test each function on tiny inputs first, the way the workbook does. --detach keeps a Modal run alive when you close the terminal.
train_on_policy.py and the value head in on_policy.py. You want your curve to stay comparable with the 25% reference. Which edit keeps it so?Chapter 1
Take the best known move most of the time, and a random one sometimes
Problem 1 starts with two small functions in gridworld_q_learning.py. greedy_action(q_table, state) returns the best action at a state. choose_action(q_table, state, epsilon, rng) sometimes picks a random action instead.
A Q-value Q(s, a) is the agent's estimate of the total reward it gets after it takes action a in state s. The table starts at zero. All four actions tie, and np.argmax returns the first index: 0, which is LEFT. A purely greedy agent walks into the left wall.
So the agent explores. With probability epsilon it picks one of the four actions at random. Otherwise it takes the action with the highest Q-value. This rule is epsilon-greedy.
The grey bars are the Q-values at one cell. The blue bars are the chance of each move. Drag epsilon, then sample 200 moves.
We made up the four Q-values. The rule and the action order (left, right, down, up) are the homework's.
How often does the agent take its best move? Call the chance of a random move epsilon, ε. Call the number of actions n. The random branch can also land on the best action.
P of a-star equals one minus epsilon, plus epsilon over n.
Draw a random number. If it is below epsilon, pick any of the n actions at random. Otherwise pick the best one.
Epsilon starts at 0.4 in the homework: P = 0.6 + 0.4 / 4 = 0.7. At the end epsilon is 0.02, so P = 0.985.
The starter lowers epsilon in a straight line from 0.4 to 0.02 over 5,000 episodes. epsilon_for_episode does this for you. Early moves explore, late moves exploit.
AssertionError in env.step: the action 1.8 is not in (0, 1, 2, 3).greedy_action returns. np.max gives the best value, a float.int(np.argmax(...)). Use the rng passed in, and draw the random action only inside the explore branch, so a seed gives the same run.fraction = episode / max(1, episodes − 1), then start + fraction × (end − start), with 5,000 episodes, start 0.4 and end 0.02. What is epsilon at episode 2,500? Give 3 decimals.u is below eps, return k.q.np.argmax does.javascriptfunction epsGreedy(q, eps, u, k) {
if (u < eps) return k;
let best = 0;
for (let i = 1; i < q.length; i++) if (q[i] > q[best]) best = i;
return best;
}
def pick_arm(values, eps, rng): if rng.random() < eps: return int(rng.integers(3)) best = np.max(values) return best
int(np.argmax(values)).Chapter 2
Move one table entry a fifth of the way toward what one step showed
The inner loop of train_q_learning is empty. Each step does five things: choose an action, call env.step, update one table entry, move to the next state, and stop when the episode ends.
What is a move worth? Call the reward at step t rt. A reward that comes later counts less: multiply it by the discount γ once for each step of delay. The homework uses γ = 0.98.
G equals the sum over t of gamma to the t, times r-t.
Shrink each reward r-t by gamma once per step of waiting. Add them. The total is G.
Three steps to Goal 1 with rewards −1, −1, 9: G = −1 − 0.98 + 0.9604 × 9 = 6.66.
The agent never sees G for a whole path at once. It sees one step: a reward r and a next state s′. Its best guess for the rest is the largest Q-value at s′. That reward plus that guess is the target. The update moves Q(s, a) a fraction α of the way toward it.
Q of s, a becomes Q of s, a plus alpha times: r, plus gamma times the max over a-prime of Q of s-prime, a-prime, minus Q of s, a.
q_table[y, x, action].Build the target: r, plus gamma times the best Q at s-prime, or r alone at a goal. Subtract the old Q. Add alpha times that gap to Q.
From a zero table, step UP from (4, 2) into Goal 1: r = −1 + 10 = 9, done. Q = 0 + 0.2 × 9 = 1.8. Next, RIGHT from (3, 2): target = −1 + 0.98 × 1.8 = 0.764, so Q = 0.153.
The agent walks right to the goal. Each Step applies one update. Then switch on the bug and watch the goal's value never arrive.
A toy corridor with the homework's numbers: step reward −1, goal bonus 10, α 0.2, γ 0.98. The agent always moves right.
start_q_values. In scenario 1 they should be (1.219, 2.265, 1.219, 2.265).state = next_state, then if done: break. Index the table as q_table[y, x]: the state is (x, y), the table is (height, width, 4).q[s][a]: a list of rows, one row of action values per state.done, the target is r.r + gamma times the largest value in q[s2].q[s][a] + alpha * (target - q[s][a]).javascriptfunction qUpdate(q, s, a, r, s2, done, alpha, gamma) {
const target = done ? r : r + gamma * Math.max(...q[s2]);
return q[s][a] + alpha * (target - q[s][a]);
}
for _ in range(horizon): a = pick(q, s, eps, rng) s2, r, done = env.step(s, a) if done: break target = r + gamma * q[s2].max() q[s, a] += alpha * (target - q[s, a]) s = s2
Chapter 3
Change the step reward and watch the best goal switch
Task 3 runs python gridworld_q_learning.py for three reward settings. For each, you check whether the agent reaches a goal, which one, the path and its total reward, and one sentence on why.
Goal 1 is 7 steps away and pays R1. Goal 2 is 4 steps away and pays R2. Every step costs the step reward rstep, walls included. To compare two plans, add up each path's rewards.
G-path equals n times r-step, plus R.
total_reward.Multiply the path length n by r-step. Add the bonus R. The path with the larger G-path wins.
Scenario 1: Goal 1 gives 7 × (−1) + 10 = 3 and Goal 2 gives 4 × (−1) + 5 = 1. Goal 1 wins by 2.
| Scenario | Goal 1, 7 steps | Goal 2, 4 steps | Stay 20 steps | Outcome |
|---|---|---|---|---|
| 1: rstep −1, R 10 and 5 | 3 | 1 | −20 | Goal 1, total 3 |
| 2: rstep −2, R 10 and 5 | −4 | −3 | −40 | Goal 2, total −3 |
| 3: rstep +1, R 1 and 1 | 8 | 5 | 20 | timeout, total 20 |
In scenario 2 the 3 extra steps to Goal 1 cost 6, more than its 5-point edge. In scenario 3 each step pays, so ending the episode stops the income. The agent never finishes. This is reward hacking: the agent maximizes the reward you wrote, not the task you meant.
Why do scenario 3's start values print as 50, not 20? The loop never marks a timeout as done, so the target keeps adding the next value. The table learns the worth of +1 forever.
V-stay equals r-step over one minus gamma.
Divide the per-step reward r-step by one minus gamma. The smaller that gap, the longer the future counts.
1 / (1 − 0.98) = 50. All four start values equal 50, so greedy_action picks LEFT, the first index, and the agent stays at (0, 0).
Each cell shows its best value and best action. The bright path runs from the start. Drag the step reward from −3 to +1.
Goal bonuses fixed at 10 and 5. The grid solves the discounted values (γ 0.98) exactly, so its switch sits near −1.53, not at the undiscounted −1.67.
expected and observed in the output, then check total_reward against G-path.steps * rStep + bonus.horizon * rStep.'stall' if staying is worth more than every goal.javascriptfunction bestOutcome(rStep, goals, horizon) {
let best = 'stall', bestG = horizon * rStep;
for (const g of goals) {
const G = g.steps * rStep + g.bonus;
if (G > bestG) { best = g.name; bestG = G; }
}
return best;
}
Chapter 4
Give each step of a rollout credit for how much better it went than the critic expected
Problem 2 trains the arm with PPO. Its first task is compute_gae in on_policy.py. It takes five arrays of length T (rewards, values, next values, discounts, dones), walks backwards through time, and returns the advantages and the returns.
The critic V(s) predicts the return from state s. An advantage says how much better a step went than V predicted. The smallest version looks one step ahead: the reward, plus the discounted value of the next state, minus the value of this state.
Delta-t equals r-t, plus gamma times one minus d-t times V of s-t-plus-one, minus V of s-t.
next_values[t].values[t].Take the reward r-t. Add gamma times the next value, unless the episode ended. Subtract this state's value.
With made-up numbers: r = 0, V(s) = 0.6, V(s′) = 0.8, γ = 0.9. δ = 0 + 0.72 − 0.6 = 0.12.
One step of lookahead leans on the critic, which may be wrong. A full return trusts only rewards, which are noisy. GAE blends the two with a knob λ: each step's advantage adds a shrinking share of the next step's advantage.
A-t equals delta-t, plus gamma lambda times one minus d-t times A-t-plus-one.
advantages[t].gae_lambda, 0.99 in the config.Start at the last step. Each advantage A-t is its own delta-t plus gamma lambda times the advantage after it. The returns are A-t plus V of s-t.
With made-up numbers: δ = 0.04, 0.12, 0.2, the last step ends the episode, γ 0.9, λ 0.5. A2 = 0.2, A1 = 0.12 + 0.45 × 0.2 = 0.21, A0 = 0.04 + 0.45 × 0.21 = 0.1345.
One rollout holds episode A, which ends with reward 1, and the start of episode B. Drag lambda. Then switch off the mask.
Made-up rewards and critic values, γ 0.9. The recursion is the handout's.
disc_all.min(). The rollout stores γ times the time step's discount, and the wrapper writes discount or 1.0, so every entry is 0.99. It never masks.self.gamma and dones. Do not also multiply by discounts.compute_gae loop from t = T − 1 down to 0?dones[t] is 1 on the last step of an episode.1 - dones[t] on the next value.javascriptfunction gae(rewards, values, nextValues, dones, gamma, lam) {
const A = new Array(rewards.length).fill(0);
let next = 0;
for (let t = rewards.length - 1; t >= 0; t--) {
const keep = 1 - dones[t];
const delta = rewards[t] + gamma * keep * nextValues[t] - values[t];
next = delta + gamma * lam * keep * next;
A[t] = next;
}
return A;
}
disc[t] already holds γ(1 − dt). The returns come out too small on long episodes. Click the buggy line.def returns(rew, disc, gamma, last_value): out, g = [0.0] * len(rew), last_value for t in reversed(range(len(rew))): g = rew[t] + gamma * disc[t] * g out[t] = g return out
disc[t], which holds gamma already. Each step shrinks the future by 0.98 instead of 0.99. Use one of the two.Chapter 5
Let one batch push the policy only a little way from the policy that collected it
Inside the minibatch loop of update, you write two lines. Step 1 sets ratio; the reverse KL line uses that name. Step 2 sets policy_loss. In scope: new_log_prob, olp_ep (the old log-probabilities) and adv_ep.
PPO reuses one rollout for 3 epochs. The policy changes while the data stays fixed. The ratio measures that change for each stored action: how much more likely the new policy makes it.
Rho-t equals exp of: log pi-theta of a-t given s-t, minus log pi-old of a-t given s-t.
new_log_prob.olp_ep.Subtract the old log-probability from the new one. Take exp of the difference. Densities of a 4-number action can be tiny, so never divide them directly.
With made-up numbers: new −0.90, old −1.20. ρ = exp(0.30) = 1.35. The new policy makes this action 35% more likely.
The plain objective is ρ times the advantage A. It keeps rewarding a bigger ρ, so one batch can drag the policy far. PPO also clips ρ to [1 − ε, 1 + ε], multiplies again, and keeps the smaller of the two products.
L-clip equals minus one over B times the sum over t of the min of rho-t A-t and clip of rho-t between one minus epsilon and one plus epsilon, times A-t.
policy_loss.adv_ep.clip_eps ε = 0.1.For each sample, multiply A-t by rho-t, and by the clipped rho-t. Keep the smaller product. Average, then negate.
ρ = 1.35, A = 2, ε = 0.1: the products are 2.70 and 1.1 × 2 = 2.20. The min is 2.20, so a batch of one gives L = −2.20.
The solid line is the objective for one sample. The dashed line is the unclipped ρA. Choose the sign of A, then drag ρ.
One sample with A = ±1. The clip value 0.1 is the homework's clip_eps.
policy_loss must be negative.torch.clamp, not the product.javascriptfunction ppoClipLoss(newLp, oldLp, adv, eps) {
let sum = 0;
for (let i = 0; i < adv.length; i++) {
const rho = Math.exp(newLp[i] - oldLp[i]);
const clipped = Math.min(Math.max(rho, 1 - eps), 1 + eps);
sum += Math.min(rho * adv[i], clipped * adv[i]);
}
return -sum / adv.length;
}
logp_new = dist.log_prob(actions) rho = logp_new / logp_old s1 = rho * adv s2 = torch.clamp(rho, 1 - eps, 1 + eps) * adv loss = -torch.min(s1, s2).mean()
torch.exp(logp_new - logp_old).Chapter 6
Feed the critic fixed targets, add the bonus and the anchor, then train to a million steps
Block (a) of update runs before the epoch loop, inside torch.no_grad(). You get critic values for obs_all and next_obs_all and call compute_gae. Name the results advantages_all and returns_all; the given code reads those names.
The given code then normalizes the advantages to mean 0 and standard deviation 1. The returns stay raw. They are the critic's regression target: R̂t = At + V(st), fixed for all 3 epochs.
L-V equals one over B times the sum over t of V-phi of s-t minus R-hat-t, squared.
value_loss.ret_ep.For each sample, subtract the target R-hat-t from the prediction. Square it. Average.
With made-up numbers: predictions 0.4 and 0.9, targets 0.6 and 0.5. L = (0.04 + 0.16) / 2 = 0.10.
The total loss adds four terms. The entropy H measures how spread out the action distribution is; subtracting it rewards exploration. The reverse KL measures drift from the frozen behaviour-cloning policy.
L equals L-clip, plus c-V times L-V, minus c-H times H, plus c-KL times KL.
Add the policy loss, half the value loss and a hundredth of the KL. Subtract a hundredth of the entropy H.
With made-up numbers: LCLIP −0.05, LV 0.2, H −2.3, KL 0.05. L = −0.05 + 0.1 + 0.023 + 0.0005 = 0.0735.
Each bar is one term's share of the loss. Shrink the actor's standard deviation and watch the entropy term grow. Then set its weight to 0.
The weights are the PPO config's. We made up the policy, value and KL numbers. Entropy is the Gaussian's, summed over 4 action numbers.
Then train: modal run modal_on_policy.py. Plot eval/episode_success up to 1 million steps and reach 25% or more. Watch actor_std too: if it falls toward 0 early, the policy stopped exploring.
F.mse_loss, and a value loss that does not fall.returns_all.shape. The critic returns [T, 1]; [T] plus [T, 1] makes [T, T], 4,096 by 4,096..squeeze(-1) on both critic outputs before compute_gae.torch.no_grad()?javascriptfunction normalizeAdv(adv) {
const n = adv.length;
const mean = adv.reduce((s, x) => s + x, 0) / n;
const std = Math.sqrt(adv.reduce((s, x) => s + (x - mean) ** 2, 0) / n);
return adv.map(x => (x - mean) / (std + 1e-8));
}
actor_std is near 0 and success has stopped rising. Click the buggy line.entropy = dist.entropy().sum(-1).mean() value_loss = F.mse_loss(v_pred, v_target) loss = (policy_loss + c_v * value_loss + c_h * entropy + c_kl * kl)
- c_h * entropy.Chapter 7
Raise the probability of each expert action before any reward arrives
Problem 3 starts with bc in off_policy.py. It takes a batch of states and expert actions and takes one gradient step on the actor. The training script calls it to pretrain, and again every 2 steps during RL (bc_freq).
With a sparse reward, a random arm almost never drives the nail, so the critic has nothing to learn from. Behaviour cloning copies the 20 demonstrations first. The actor outputs a Gaussian per action number: a mean from the network, squashed by tanh, and a fixed standard deviation of 0.1. During RL the same step keeps the actor near the demos while the critic is still poor.
L-BC equals minus one over B times the sum over b of log pi-theta of a-b given s-b.
Ask the actor how likely each expert action a-b is at its state s-b. Sum the log over the action numbers. Average over the batch and negate.
One number: mean 0.2, std 0.1, expert action 0.35. log p = −1.125 + 2.303 − 0.919 = 0.259, so this term of L is −0.259.
The one-number log-density is −(a − μ)² / (2σ²) − ln σ − ½ ln 2π, with mean μ and standard deviation σ. A density above 1 has a positive log, so the loss can go below 0. With σ fixed, BC moves only the mean.
The dots are 8 expert actions for one action number. Drag the mean, or press Fit to take gradient steps on the BC loss.
Made-up expert actions. The fixed standard deviation 0.1 is the off-policy actor's.
AttributeError: 'ACAgent' object has no attribute 'opt' at the first BC step.self.opt. This class has self.actor_opt and self.critic_opt.actor_opt. Sum the log-probability over the last axis, then take the mean. Add no first-time-only logic: RL calls this same function.mu and actions are [B][A] arrays.javascriptfunction bcLoss(mu, std, actions) {
let total = 0;
for (let b = 0; b < mu.length; b++) {
let lp = 0;
for (let d = 0; d < mu[b].length; d++) {
const z = (actions[b][d] - mu[b][d]) / std;
lp += -0.5 * z * z - Math.log(std) - 0.5 * Math.log(2 * Math.PI);
}
total += lp;
}
return -total / mu.length;
}
dist.log_prob(action) has shape [256, 4]. You write -dist.log_prob(action).mean(). What changes against the handout's loss?Chapter 8
Build a target from two random target critics, then train every critic toward it
update_critic gets a replay batch: states, actions, rewards, discounts and next states. You sample next actions from the actor, build a target, train all N critics toward it and soft-update the target critics. N is 2 by default, 10 in the UTD run.
Why not take the best guess? Each critic's estimate carries noise. The largest of several noisy guesses sits above the truth on average. Trained toward it, the critics drift up. This is maximization bias.
The dashed line is the true value. Each bar is one critic's noisy guess. Draw again, or draw 1,000 times, and read the average error of each rule.
Toy noise: each guess is the true value 1.0 plus Gaussian noise with std 0.1. Real critics have correlated errors.
The target uses the target critics Q̄, slow copies of the online critics. Pick two at random, take the smaller value per sample, and add it to the reward.
Y equals r, plus gamma times the min of Q-bar-i of s-prime, a-prime and Q-bar-j of s-prime, a-prime.
reward: here a 3-step discounted sum, shape [B, 1].discount: already 0.99 cubed for 3 steps, shape [B, 1]. Do not multiply by gamma again.Sample a-prime from the actor at s-prime. Ask two random target critics for its value. Keep the smaller. Multiply by the discount and add r. No gradient flows into y.
With made-up numbers: r = 0, discount 0.970, target critics say 0.62, 0.55, 0.71, and you pick the first and the third. y = 0.970 × 0.62 = 0.602.
L-Q equals the sum over i from 1 to N of the batch mean of Q-i of s, a minus y, squared.
critic_opt minimizes.For each online critic Q-i, take the mean squared gap to y over the batch. Add the N results.
With made-up numbers: one sample, two critics say 0.5 and 0.7, y = 0.6. L = 0.01 + 0.01 = 0.02.
Last, each target critic moves a small step toward its online twin: φ̄ ← (1 − τ) φ̄ + τ φ, with target weights φ̄, online weights φ and τ = 0.005. utils.soft_update_params does it. After 200 updates, 0.995200 = 37% of the old gap is left. The handout calls τ "ρ".
assert y.shape == q.shape. The replay batch gives reward and discount as [B, 1]. An extra unsqueeze(-1) makes [B, 1, 1], and the target spreads to [B, B, 1].random.sample (no repeats), build y under torch.no_grad(), use self.critic_target for y, and sum the loss over all N.targetQs[k][b] is target critic k on sample b. The pair i, j is given.targetQs[i][b] and targetQs[j][b].reward[b] + discount[b] * min for each b. The discount already holds gamma.javascriptfunction criticTarget(reward, discount, targetQs, i, j) {
return reward.map((r, b) =>
r + discount[b] * Math.min(targetQs[i][b], targetQs[j][b]));
}
with torch.no_grad(): a2 = actor(s2).sample(clip=0.3) qs = critic_target(s2, a2) qi, qj = random.choices(qs, k=2) y = r + disc * torch.min(qi, qj)
random.choices draws with replacement, so it can pick one critic twice and the min does nothing. Use random.sample(qs, 2).reward is [256, 1], and each critic output is [256, 1]. You write reward.unsqueeze(-1) + discount.unsqueeze(-1) * q_min. What shape is y?Chapter 9
Push the actor toward actions the critics score high, then measure what more updates buy
update_actor gets a batch of states only. You sample a fresh action from the actor, ask all N online critics for its value and step actor_opt on the negative mean. The buffer's stored action is not used: it came from an old policy and carries no gradient to θ.
L-pi equals minus one over N times the sum over i of Q-i of s, a-prime, where a-prime comes from pi-theta given s.
Sample a-prime. Average the N critics' scores, then average over the batch. Negate, because the optimizer only descends.
With made-up numbers: critic 1 says 0.4 and 0.6 on two states, critic 2 says 0.5 and 0.7. Means 0.45 and 0.65; L = −0.55.
The curve is a young critic's score over one action number. It has a false peak far from the demos. Press Step with BC on, then off.
An illustrative critic curve and step sizes. The real critic improves as data arrives; here it stays fixed.
Then two runs. The default (N = 2, UTD = 1) should reach 90% before 100k environment steps. The second sets agent.num_critics=10 and utd=5 and should reach 90% before 40k steps. The UTD ratio is the number of critic updates per environment step.
| Run | Critics | UTD | Env steps | Critic updates |
|---|---|---|---|---|
| default | 2 | 1 | 100,000 | 100,000 |
| ablation | 10 | 5 | 40,000 | 200,000 |
Then compare the runs. Read three numbers off each curve: the step of first success, the step that crosses 90%, the final rate. Tie each difference to one property: how often each method reuses a transition, and how each method limits its update.
actor_loss rises.actor_opt; update_critic clears the critic's gradients before its own step.qList[k][b] is online critic k on sample b, for the fresh actions.javascriptfunction actorLoss(qList) {
const N = qList.length, B = qList[0].length;
let sum = 0;
for (let b = 0; b < B; b++) {
let m = 0;
for (let k = 0; k < N; k++) m += qList[k][b];
sum += m / N;
}
return -sum / B;
}
train_off_policy.py does in one step after warmup, with UTD 5 and bc_freq 2.Chapter 10
Keep the numbers at hand, tick the checklist, and compare the curves
One table for the terms and settings, one checklist, then the core loop.
| Term | Meaning | Setting |
|---|---|---|
| epsilon | chance of a random action | 0.4 to 0.02 over 5,000 episodes |
| alpha, gamma (P1) | learning rate, discount | 0.2, 0.98; horizon 20 |
| advantage | how much better a step went than V said | GAE λ 0.99, γ 0.99 |
| ratio, clip | policy change per action; its limit | ε 0.1, 3 epochs, rollout 4,096 |
| loss weights (P2) | value, entropy, reverse KL | 0.5, 0.01, 0.01 |
| target critic | slow copy used for y | τ 0.005 |
| replay batch (P3) | 3-step reward and discount, [B, 1] | B 256, lr 1e-4, actor std 0.1 |
| UTD | critic updates per env step | 1 by default, 5 in the ablation |
compute_gae.bc steps actor_opt and sums over the action axis.critic_target, random.sample and no extra gamma.The given training step of Problem 3, as pseudocode:
pseudocodeaction = agent.act(obs) # mean action during warmup for _ in range(utd): agent.update_critic(replay_iter) # your Chapter 8 if past_warmup: agent.update_actor(replay_iter) # your Chapter 9 if step % bc_freq == 0: agent.bc(demo_iter) # your Chapter 7 obs = env.step(action) # store the transition in replay
Put three curves on one chart: PPO, the off-policy default and the 10-critic UTD 5 run. Use eval/episode_success from Wandb; it can export each curve as a CSV. PPO needs about ten times the environment steps, because it throws each rollout away after a few epochs.
Teach it back with Teach, or go back to the grid and move the reward once more. Credit: Stanford CS224R, Deep Reinforcement Learning, Spring 2026, Homework 2. The handout and starter code belong to the course.