CS224R HW2: Online RL

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.

Step Q-learning on the grid

0.40

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.

Workbook progress
0 / 44 exercises (0%)
0
Day streak
Best: 0
44 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser. The Build pill above opens the Studio, where you write the homework's own functions in Python.

Chapter 0

The Map: What You Build

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.

Build in order

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.

PartFile and functionChapter
P1 exploregridworld_q_learning.py: greedy_action, choose_action1
P1 learntrain_q_learning inner loop2
P1 scenariosrun: the path and total reward of each scenario, and why3
P2 GAEon_policy.py: compute_gae4
P2 clipupdate: ratio and policy_loss5
P2 runupdate GAE block; plot success to 1M steps, expect 25% or more6
P3 BCoff_policy.py: bc7
P3 criticupdate_critic8
P3 actor and runsupdate_actor; expect 90% before 100k steps; the UTD run; compare with PPO9

Set up and run

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.

The road

  1. Choose an action: epsilon-greedy. The hero's epsilon slider.
  2. The Q-learning update: one table entry moves toward a target. The hero's Step.
  3. Three scenarios: one step reward flips the plan. The hero's Move the reward.
  4. Advantages with GAE: credit for each step of a rollout.
  5. The ratio and the clip: how far one PPO update may go.
  6. The full PPO loss and the run: critic, entropy, KL.
  7. Behaviour cloning: start the actor from the demos.
  8. The critic: the minimum of two target critics.
  9. The actor and the runs: climb the critic, then the UTD study.
  10. Field guide: numbers, checklist, the core loop.
What shows that your PPO from Problem 2 works?

Workbook

Exercise 0.1: Read a success rate Derive
A toy evaluation runs the arm for 40 episodes. 11 of them drive the nail in. What is the success rate, in percent?
%
Show derivation
an episode succeeds when it earns the one reward of 1.0
success rate = 11 / 40 = 0.275 = 27.5%
That clears the 25% a working PPO reaches by 1M steps. With a sparse reward, this rate is the signal to watch, not the loss.
Exercise 0.2: Which file may change? Trace
Your PPO run is slow, and you want to change the rollout length in 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?
Exercise 0.3: Order the Problem 3 work Design
Tap the chips in the order you should do them.
?
→
?
→
?
→
?
→
?
→
?
write update_actor run with 10 critics, UTD 5 write bc edit the argv in modal_off_policy.py write update_critic run with 2 critics, UTD 1

Chapter 1

Choose an Action: Epsilon-Greedy

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.

Turn epsilon and see the odds

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.

0.40

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(a*) = 1 − ε + ε / n
Say it aloud

P of a-star equals one minus epsilon, plus epsilon over n.

P(a*)
P of a-star the chance that the agent takes the action with the highest Q-value.
1 − ε
one minus epsilon the chance of the greedy branch. Epsilon is between 0 and 1.
ε / n
epsilon over n the chance that the random branch picks the best action too. Here n is 4.
In plain words

Draw a random number. If it is below epsilon, pick any of the n actions at random. Otherwise pick the best one.

With numbers

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.

The trap: a value instead of an index

symptom
An AssertionError in env.step: the action 1.8 is not in (0, 1, 2, 3).
see it
Print what greedy_action returns. np.max gives the best value, a float.
fix
Return the index: 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.
At episode 0 the table is all zeros and epsilon is 0. What does the agent do?

Workbook

Exercise 1.1: The chance of the best move Derive
A bandit has 5 arms. The agent uses epsilon-greedy with epsilon 0.2. What is the chance that it pulls the arm with the highest value?
probability
Show derivation
greedy branch: 1 − 0.2 = 0.8
random branch hits the best arm: 0.2 / 5 = 0.04
P = 0.8 + 0.04 = 0.84
Exercise 1.2: Epsilon halfway through Derive
The schedule is 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.
epsilon
Show derivation
fraction = 2500 / 4999 = 0.50010
epsilon = 0.4 + 0.50010 × (0.02 − 0.4) = 0.4 − 0.19004 = 0.20996
The divisor is 4,999, not 5,000, so the last episode lands on 0.02 exactly.
Exercise 1.3: Write epsilon-greedy Build
A neighbouring version you can test: the two random draws are passed in, so every test is fixed.
  1. If u is below eps, return k.
  2. Otherwise return the index of the largest value in q.
  3. On a tie, return the first index, as np.argmax does.
Show solution
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;
}
Exercise 1.4: Find the crash Debug
A neighbouring task: a bandit picks one of 3 arms with epsilon-greedy. The environment asserts that the arm is 0, 1 or 2, and it fails. Click the buggy line.
def pick_arm(values, eps, rng):
    if rng.random() < eps:
        return int(rng.integers(3))
    best = np.max(values)
    return best
Show why
Line 4 takes the largest value, not its position. With values [0.1, 0.7, 0.3] it returns 0.7. Use int(np.argmax(values)).

Chapter 2

The Q-Learning Update

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 = Σt γt rt
Say it aloud

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

G
G the return: the worth of the rest of the episode.
Σt
the sum over t one term per step, from step 0 to the end.
γt
gamma to the t 0.98 multiplied by itself t times.
rt
r-t the reward at step t: the step reward, plus a goal bonus on arrival.
In plain words

Shrink each reward r-t by gamma once per step of waiting. Add them. The total is G.

With numbers

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(s, a) ← Q(s, a) + α [ r + γ maxa′ Q(s′, a′) − Q(s, a) ]
Say it aloud

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(s, a)
Q of s, a the table entry for this state and action: q_table[y, x, action].
α
alpha the learning rate, 0.2: how far one update moves.
r
r the reward that this one step returned.
γ
gamma the discount, 0.98.
maxa′ Q(s′, a′)
the max over a-prime of Q of s-prime, a-prime the best value at the next state. Leave it out when the step ends the episode.
In plain words

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.

With numbers

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.

Step the update down a corridor

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.

The trap: where the break goes

symptom
Break before the update, and the goal's reward never enters the table: the agent walks into a wall at evaluation. No break at all, and an agent on Goal 1 steps UP, stays on the goal and collects the bonus again.
see it
Print start_q_values. In scenario 1 they should be (1.219, 2.265, 1.219, 2.265).
fix
Update first, then 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) = 2, r = −1, the best Q at s′ is 5, α = 0.2, γ = 0.98, and the step is not terminal. What is the new Q(s, a)?

Workbook

Exercise 2.1: One update by hand Derive
Q(s, a) = 0.5. The step gives r = −1, and the best Q at s′ is 2.0. Use α = 0.2 and γ = 0.98. The step is not terminal. What is the new Q(s, a)?
value
Show derivation
target = −1 + 0.98 × 2.0 = 0.96
gap = 0.96 − 0.5 = 0.46
new Q = 0.5 + 0.2 × 0.46 = 0.592
Exercise 2.2: A discounted return Derive
An agent gets rewards 2, 0, 0, 5 on four steps. Use γ = 0.9. What is G? Give 3 decimals.
return
Show derivation
G = 2 + 0.9 × 0 + 0.81 × 0 + 0.729 × 5
= 2 + 3.645 = 5.645
Exercise 2.3: Which cell? Trace
The agent is at state (3, 1): column 3, row 1. The table has shape (4, 5, 4). Which entry holds the value of UP (action 3)?
Exercise 2.4: Write one Q-learning update Build
The table is q[s][a]: a list of rows, one row of action values per state.
  1. If done, the target is r.
  2. Otherwise the target is r + gamma times the largest value in q[s2].
  3. Return q[s][a] + alpha * (target - q[s][a]).
Show solution
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]);
}
Exercise 2.5: The lost goal Debug
A neighbouring loop on a line world. After training, every value is negative and the agent never heads for the goal. Click the buggy line.
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
Show why
Line 4 leaves the loop before the goal's step is written to the table. The only positive reward is lost. Update first, with target r on a terminal step, then break at the bottom.

Chapter 3

Three Scenarios, Three Plans

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.

Gpath = n · rstep + R
Say it aloud

G-path equals n times r-step, plus R.

Gpath
G-path the total reward of one shortest path, with no discount. The script prints it as total_reward.
n
n the number of steps: 7 to Goal 1, 4 to Goal 2.
rstep
r-step the reward on every step: −1, −2 or +1.
R
R the goal bonus, paid once on arrival.
In plain words

Multiply the path length n by r-step. Add the bonus R. The path with the larger G-path wins.

With numbers

Scenario 1: Goal 1 gives 7 × (−1) + 10 = 3 and Goal 2 gives 4 × (−1) + 5 = 1. Goal 1 wins by 2.

ScenarioGoal 1, 7 stepsGoal 2, 4 stepsStay 20 stepsOutcome
1: rstep −1, R 10 and 531−20Goal 1, total 3
2: rstep −2, R 10 and 5−4−3−40Goal 2, total −3
3: rstep +1, R 1 and 18520timeout, 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.

Vstay = rstep / ( 1 − γ )
Say it aloud

V-stay equals r-step over one minus gamma.

Vstay
V-stay the discounted worth of the same reward on every step, forever.
rstep
r-step the reward per step, +1 in scenario 3.
1 − γ
one minus gamma 0.02 here. It comes from the geometric sum 1 + γ + γ² + …
In plain words

Divide the per-step reward r-step by one minus gamma. The smaller that gap, the longer the future counts.

With numbers

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).

Slide the step reward and watch the plan flip

Each cell shows its best value and best action. The bright path runs from the start. Drag the step reward from −3 to +1.

−1.00

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.

The trap: a sentence with no arithmetic

symptom
"The agent went to Goal 2 because it is closer." It is closer in scenario 1 too, and there it loses.
see it
Compare expected and observed in the output, then check total_reward against G-path.
fix
Name the two totals in your sentence. For scenario 3, compare 20 for staying with 5 for the near goal.
Keep R1 = 10 and R2 = 5. At what step reward do the two goals tie, with no discount?

Workbook

Exercise 3.1: A new tie point Derive
A different grid: goal A is 6 steps away and pays 12. Goal B is 2 steps away and pays 4. At what step reward do the two totals tie?
step reward
Show derivation
6r + 12 = 2r + 4
4r = −8, so r = −2
Above −2 the far goal wins; below it the near goal wins.
Exercise 3.2: Forever at a lower discount Derive
Scenario 3 again, with γ = 0.9 and rstep = +1. With no timeout marked as done, what value do the start entries approach?
value
Show derivation
V = 1 / (1 − 0.9) = 1 / 0.1 = 10
A goal pays 1 and ends the stream, so it is worth about 1 + 0.9 + 0.81 + 0.729 + 1 × 0.729, still under 10.
Exercise 3.3: Read the tie Trace
After scenario 3, the start values print as (50.0, 50.0, 50.0, 50.0) for (left, right, down, up). What path does the greedy rollout take?
Exercise 3.4: Pick the winning plan Build
A neighbouring grid with any number of goals. Use totals with no discount, as the printout does.
  1. A goal is worth steps * rStep + bonus.
  2. Staying put for the whole horizon is worth horizon * rStep.
  3. Return the name of the best goal, or 'stall' if staying is worth more than every goal.
Show solution
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

Advantages With GAE

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.

δ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 of s-t-plus-one, minus V of s-t.

δt
delta-t the TD error at step t: the critic's surprise.
rt
r-t the reward at step t. On the hammer task it is 0, or 1 at success.
γ
gamma the discount, 0.99 in the PPO config.
(1 − dt)
one minus d-t the mask. d-t is 1 on the last step of an episode, so the future drops out.
V(st+1)
V of s-t-plus-one the critic's value of the next state: next_values[t].
V(st)
V of s-t the critic's value of this state: values[t].
In plain words

Take the reward r-t. Add gamma times the next value, unless the episode ended. Subtract this state's value.

With numbers

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.

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

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

At
A-t the advantage at step t: advantages[t].
δt
delta-t the TD error from the line above.
γλ
gamma lambda the decay per step of look-ahead. λ is gae_lambda, 0.99 in the config.
(1 − dt)
one minus d-t the same mask: no credit flows in from the next episode.
At+1
A-t-plus-one the next step's advantage. You have it already, because the loop runs backwards.
In plain words

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 numbers

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.

Turn lambda and watch the credit reach back

One rollout holds episode A, which ends with reward 1, and the start of episode B. Drag lambda. Then switch off the mask.

0.50

Made-up rewards and critic values, γ 0.9. The recursion is the handout's.

The trap: gamma twice, or no mask at all

symptom
Success rises slower than it should, or advantages at an episode end carry the next episode's values.
see it
Print 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.
fix
Follow the handout: γ(1 − dt) from self.gamma and dones. Do not also multiply by discounts.
Why does compute_gae loop from t = T − 1 down to 0?

Workbook

Exercise 4.1: One TD error Derive
r = 0, V(s) = 0.5, V(s′) = 0.7, γ = 0.99, and the step is not the last one. What is δ?
delta
Show derivation
δ = 0 + 0.99 × 0.7 − 0.5
= 0.693 − 0.5 = 0.193
Exercise 4.2: Lambda at 1 Derive
Use the chapter's episode: δ = 0.04, 0.12, 0.2, the last step ends it, γ = 0.9. Now set λ = 1. What is A0?
advantage
Show derivation
A2 = 0.2
A1 = 0.12 + 0.9 × 0.2 = 0.30
A0 = 0.04 + 0.9 × 0.30 = 0.31
Check: the discounted return from step 0 is 0.81 × 1 = 0.81, and V(s0) = 0.5. 0.81 − 0.5 = 0.31.
Exercise 4.3: Lambda at 0 Trace
Set λ = 0. What does each advantage At become?
Exercise 4.4: Write GAE Build
Plain arrays of length T. dones[t] is 1 on the last step of an episode.
  1. Walk from t = T − 1 down to 0, carrying the next advantage (0 at the start).
  2. Compute delta with the mask 1 - dones[t] on the next value.
  3. Set A[t] = delta + gamma × lam × mask × next advantage.
  4. Return the array of advantages.
Show solution
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;
}
Exercise 4.5: Gamma squared Debug
A neighbouring function: discounted returns for a batch. Here 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
Show why
Line 4 multiplies by gamma and by 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

The Ratio and the Clip

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.

ρt = exp( log πθ(at|st) − log πold(at|st) )
Say it aloud

Rho-t equals exp of: log pi-theta of a-t given s-t, minus log pi-old of a-t given s-t.

ρt
rho-t the ratio for sample t. It is 1 when the policy has not changed.
exp
exp e to the power, which turns a log difference back into a ratio.
log πθ(at|st)
log pi-theta of a-t given s-t the current policy's log-probability of the stored action: new_log_prob.
log πold(at|st)
log pi-old of a-t given s-t the same, recorded at rollout time: olp_ep.
In plain words

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 numbers

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.

LCLIP = −(1/B) Σt min( ρt At, clip(ρt, 1−ε, 1+ε) At )
Say it aloud

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.

LCLIP
L-clip the policy loss to minimize: policy_loss.
−(1/B) Σt
minus one over B times the sum over t minus the mean over the B samples of the minibatch. The minus turns "raise" into "minimize".
min
min the smaller of the two terms, sample by sample.
At
A-t the normalized advantage: adv_ep.
clip(ρt, 1−ε, 1+ε)
clip of rho-t rho-t held inside [0.9, 1.1] for clip_eps ε = 0.1.
In plain words

For each sample, multiply A-t by rho-t, and by the clipped rho-t. Keep the smaller product. Average, then negate.

With numbers

ρ = 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.

Drag the ratio past the clip

The solid line is the objective for one sample. The dashed line is the unclipped ρA. Choose the sign of A, then drag ρ.

1.35
0.10

One sample with A = ±1. The clip value 0.1 is the homework's clip_eps.

The trap: a lost minus sign

symptom
Eval success falls below the behaviour-cloning start in the first updates and stays there.
see it
On a batch with A > 0 and ρ = 1, policy_loss must be negative.
fix
Negate the mean of the min. Clip the ratio with torch.clamp, not the product.
A > 0 and ρ = 1.3 with ε = 0.1. What gradient does this sample give the policy?

Workbook

Exercise 5.1: A ratio from logs Derive
The new log-probability is −2.0 and the old one is −2.5. What is ρ? Give 3 decimals.
ratio
Show derivation
difference = −2.0 − (−2.5) = 0.5
ρ = exp(0.5) = 1.649
Exercise 5.2: The loss for a bad action Derive
One sample: A = −2, ρ = 0.85, ε = 0.1. What is LCLIP for this batch of one?
loss
Show derivation
unclipped: 0.85 × (−2) = −1.7
clipped: 0.9 × (−2) = −1.8
min = −1.8, so L = −(−1.8) = 1.8
ρ is below 0.9, so the clipped term is chosen and its slope is zero.
Exercise 5.3: Where the slope is zero Trace
With A < 0 and ε = 0.1, for which ratios does this sample give no gradient?
Exercise 5.4: Write the clipped loss Build
Arrays of log-probabilities and advantages for one minibatch.
  1. For each sample, rho = exp(new − old).
  2. Take the smaller of rho × A and clip(rho, 1 − eps, 1 + eps) × A.
  3. Return minus the mean over the batch.
Show solution
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;
}
Exercise 5.5: A ratio that is not a ratio Debug
A neighbouring loss for a discrete policy. The ratio is 1 when the policy has not changed, but here it comes out as about 0.8. Click the buggy line.
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()
Show why
Line 2 divides log-probabilities. The ratio of probabilities is exp of the difference: torch.exp(logp_new - logp_old).

Chapter 6

The Full PPO Loss and the Run

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.

LV = (1/B) Σt ( Vφ(st) − R̂t )2
Say it aloud

L-V equals one over B times the sum over t of V-phi of s-t minus R-hat-t, squared.

LV
L-V the value loss: value_loss.
(1/B) Σt
one over B times the sum over t the mean over the minibatch.
Vφ(st)
V-phi of s-t the critic's current prediction, with weights phi.
R̂t
R-hat-t the fixed target from GAE: ret_ep.
In plain words

For each sample, subtract the target R-hat-t from the prediction. Square it. Average.

With numbers

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 = LCLIP + cV LV − cH H + cKL KL
Say it aloud

L equals L-clip, plus c-V times L-V, minus c-H times H, plus c-KL times KL.

L
L the one loss that the optimizer minimizes for actor and critic together.
LCLIP
L-clip your policy loss from Chapter 5.
cV LV
c-V times L-V the value loss, weighted 0.5.
cH H
c-H times H the entropy, weighted 0.01. A narrow Gaussian has negative entropy.
cKL KL
c-KL times KL the reverse KL to the reference policy, weighted 0.01.
In plain words

Add the policy loss, half the value loss and a hundredth of the KL. Subtract a hundredth of the entropy H.

With numbers

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.

Mix the loss and squeeze the policy

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.

0.14
0.010

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.

The trap: a [T, 1] critic output

symptom
A broadcasting warning from F.mse_loss, and a value loss that does not fall.
see it
Print returns_all.shape. The critic returns [T, 1]; [T] plus [T, 1] makes [T, T], 4,096 by 4,096.
fix
Call .squeeze(-1) on both critic outputs before compute_gae.
Why does block (a) run inside torch.no_grad()?

Workbook

Exercise 6.1: Normalize one advantage Derive
Raw advantages are 2, 0, −1, 3. Normalize with the mean and the standard deviation over N (not N − 1). What does the 3 become? Give 3 decimals.
value
Show derivation
mean = (2 + 0 − 1 + 3) / 4 = 1
variance = (1 + 1 + 4 + 4) / 4 = 2.5, std = 1.581
(3 − 1) / 1.581 = 1.265
Exercise 6.2: The total loss Derive
LCLIP = −0.1, LV = 0.4, H = −2.0, KL = 0.2, with the config weights 0.5, 0.01 and 0.01. What is L?
loss
Show derivation
L = −0.1 + 0.5 × 0.4 − 0.01 × (−2.0) + 0.01 × 0.2
= −0.1 + 0.2 + 0.02 + 0.002 = 0.122
Exercise 6.3: Normalize the advantages Build
The same normalization the given PPO code applies after GAE.
  1. Compute the mean.
  2. Compute the standard deviation over N, not N − 1.
  3. Return (x − mean) / (std + 1e-8) for each entry.
Show solution
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));
}
Exercise 6.4: The policy that froze Debug
A neighbouring loss. After 50k steps 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)
Show why
Line 5 adds the entropy, so minimizing the loss lowers it and the policy narrows. The bonus must be subtracted: - c_h * entropy.

Chapter 7

Behaviour Cloning: Start From the Demos

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.

LBC = −(1/B) Σb log πθ(ab | sb)
Say it aloud

L-BC equals minus one over B times the sum over b of log pi-theta of a-b given s-b.

LBC
L-BC the behaviour-cloning loss.
−(1/B) Σb
minus one over B times the sum over b minus the mean over the B demo samples.
log πθ(ab | sb)
log pi-theta of a-b given s-b the log-density of the expert's 4-number action: the sum of 4 one-number log-densities.
In plain words

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.

With numbers

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.

Fit the policy to the demos

The dots are 8 expert actions for one action number. Drag the mean, or press Fit to take gradient steps on the BC loss.

−0.40

Made-up expert actions. The fixed standard deviation 0.1 is the off-policy actor's.

The trap: the wrong optimizer

symptom
AttributeError: 'ACAgent' object has no attribute 'opt' at the first BC step.
see it
PPO had one optimizer, self.opt. This class has self.actor_opt and self.critic_opt.
fix
Step 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.
The actor's std is fixed at 0.1. What does a BC step change?

Workbook

Exercise 7.1: A log-density at the mean Derive
Mean 0.2, std 0.1, action 0.2. What is the log-density? Give 3 decimals.
log p
Show derivation
(a − μ)² term: 0
−ln 0.1 = 2.303
−½ ln 2π = −0.919
log p = 0 + 2.303 − 0.919 = 1.384
Exercise 7.2: Write the BC loss Build
A Gaussian policy with one fixed std. mu and actions are [B][A] arrays.
  1. For each number, log p = −z²/2 − ln std − ½ ln 2π, with z = (a − mu) / std.
  2. Sum log p over the A action numbers of each sample.
  3. Return minus the mean over the B samples.
Show solution
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;
}
Exercise 7.3: Four numbers, one mean Trace
dist.log_prob(action) has shape [256, 4]. You write -dist.log_prob(action).mean(). What changes against the handout's loss?

Chapter 8

The Critic: the Smaller of Two Guesses

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.

Draw noisy critics and compare targets

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.

10

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 = r + γ min( Q̄i(s′, a′), Q̄j(s′, a′) )
Say it aloud

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.

y
y the target for every online critic, one number per sample.
r
r reward: here a 3-step discounted sum, shape [B, 1].
γ
gamma discount: already 0.99 cubed for 3 steps, shape [B, 1]. Do not multiply by gamma again.
min(Q̄i, Q̄j)
the min of Q-bar-i and Q-bar-j two distinct target critics picked at random, at the next state s-prime and a fresh next action a-prime from the actor.
In plain words

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 numbers

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.

LQ = Σi=1..N meanb ( Qi(s, a) − y )2
Say it aloud

L-Q equals the sum over i from 1 to N of the batch mean of Q-i of s, a minus y, squared.

LQ
L-Q the critic loss that critic_opt minimizes.
Σi=1..N
the sum over i from 1 to N one term for every online critic, not only the two picked.
Qi(s, a)
Q-i of s, a online critic i at the stored state and stored action.
y
y the fixed target from the line above.
In plain words

For each online critic Q-i, take the mean squared gap to y over the batch. Add the N results.

With numbers

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 τ "ρ".

The trap: shapes that broadcast

symptom
The critic loss climbs into the thousands. The handout lists this as a common bug.
see it
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].
fix
Use them as given. Pick critics with random.sample (no repeats), build y under torch.no_grad(), use self.critic_target for y, and sum the loss over all N.
Five critics guess 1.10, 0.95, 1.02, 0.90, 1.05 for a true value of 1.0. Which target errs high?

Workbook

Exercise 8.1: One target Derive
reward = 0.5, discount = 0.97. The picked target critics say 0.8 and 0.6. What is y?
target
Show derivation
min(0.8, 0.6) = 0.6
y = 0.5 + 0.97 × 0.6 = 0.5 + 0.582 = 1.082
Exercise 8.2: How far the target lags Derive
The online critic jumps and then stays fixed. With τ = 0.005, what share of the gap between target and online is left after 100 soft updates? Give 3 decimals.
share
Show derivation
each update keeps 1 − 0.005 = 0.995 of the gap
0.995100 = 0.606
Half the gap is gone after about 138 updates.
Exercise 8.3: Build the min-of-two target Build
Plain arrays. targetQs[k][b] is target critic k on sample b. The pair i, j is given.
  1. For each sample b, take the smaller of targetQs[i][b] and targetQs[j][b].
  2. Return reward[b] + discount[b] * min for each b. The discount already holds gamma.
Show solution
javascriptfunction criticTarget(reward, discount, targetQs, i, j) {
  return reward.map((r, b) =>
    r + discount[b] * Math.min(targetQs[i][b], targetQs[j][b]));
}
Exercise 8.4: The same critic twice Debug
A neighbouring target for an ensemble. Sometimes the "min of two" is one critic's value alone. Click the buggy line.
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)
Show why
random.choices draws with replacement, so it can pick one critic twice and the min does nothing. Use random.sample(qs, 2).
Exercise 8.5: Read a shape Trace
B = 256. 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

The Actor and the UTD Run

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π = −(1/N) Σi Qi(s, a′),   a′ ~ πθ(· | s)
Say it aloud

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.

Lπ
L-pi the actor loss, averaged over the batch too.
−(1/N) Σi
minus one over N times the sum over i minus the mean over the N critics.
Qi(s, a′)
Q-i of s, a-prime online critic i's score for the fresh action.
a′ ~ πθ(· | s)
a-prime drawn from pi-theta given s mean plus noise, so the gradient flows back through the mean.
In plain words

Sample a-prime. Average the N critics' scores, then average over the batch. Negate, because the optimizer only descends.

With numbers

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.

Let the actor climb the critic

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.

RunCriticsUTDEnv stepsCritic updates
default21100,000100,000
ablation10540,000200,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.

The trap: climbing down

symptom
Success falls below the BC level and actor_loss rises.
see it
With positive Q-values the actor loss must be negative.
fix
Negate the mean. Step only actor_opt; update_critic clears the critic's gradients before its own step.
Why does the actor use a fresh action and not the buffer's action?

Workbook

Exercise 9.1: An actor loss Derive
Critic 1 says 0.2 and 0.6 on two states. Critic 2 says 0.4 and 0.8. What is the actor loss?
loss
Show derivation
mean over critics: (0.2 + 0.4) / 2 = 0.3, (0.6 + 0.8) / 2 = 0.7
mean over the batch: (0.3 + 0.7) / 2 = 0.5
L = −0.5
Exercise 9.2: Write the actor loss Build
qList[k][b] is online critic k on sample b, for the fresh actions.
  1. For each sample, average the N critics.
  2. Average over the batch.
  3. Return the negative.
Show solution
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;
}
Exercise 9.3: Count the updates Derive
A run uses UTD 3 for 60,000 environment steps. How many critic updates does it make?
updates
Show derivation
60,000 × 3 = 180,000
The actor still updates once per environment step after warmup.
Exercise 9.4: One training step Design
Order what train_off_policy.py does in one step after warmup, with UTD 5 and bc_freq 2.
?
→
?
→
?
→
?
→
?
bc on demos, if the step is even step the environment pick an action update_actor once update_critic 5 times

Chapter 10

Field Guide: Check Your Runs

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.

TermMeaningSetting
epsilonchance of a random action0.4 to 0.02 over 5,000 episodes
alpha, gamma (P1)learning rate, discount0.2, 0.98; horizon 20
advantagehow much better a step went than V saidGAE λ 0.99, γ 0.99
ratio, clippolicy change per action; its limitε 0.1, 3 epochs, rollout 4,096
loss weights (P2)value, entropy, reverse KL0.5, 0.01, 0.01
target criticslow 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
UTDcritic updates per env step1 by default, 5 in the ablation

The checklist

The core loop

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

Compare the curves

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.

Keep going

One thread runs through all three problems. Each learns a value from one step of experience and uses it to choose better actions. They differ in where the data comes from: a table, a fresh rollout or a replay buffer.

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.

Workbook

Exercise 10.1: The right curve Trace
Which chart do you use to compare the three runs?
Exercise 10.2: Read the curve Trace
Your UTD run reads 84% at 36k steps, 91% at 38k and 88% at 42k. Does it meet "at least 90% before 40k"?
CS224R HW2: Online RL
The course · Back to Gleams