A copy of an expert drifts off the expert's path, and its errors grow. Homework 1 has you build three fixes for a Flappy Bird: regression, flow matching and DAgger. Seven pieces of code, three policies.
A lesson with a workbook. Each chapter explains one part of the homework, then gives you exercises on our own toy data.
Press Play to fly the cloned agent along the expert's path. A gust pushes it off the path, where it has no data, and its error grows. Switch to DAgger and fly again. Then we build each part of the homework.
You need some Python and the idea of a neural network as a function. The exercises run JavaScript in your browser.
Based on Homework 1 of Stanford CS 224R: Deep Reinforcement Learning (Spring 2026). Handout: PDF. Starter code: zip. This page teaches the skills in our own words and toy data.
An illustrative toy, not the homework's environment. The path, the gusts, the 300 steps and the error rule are ours. It shows the mechanism: cloning has labels only near the expert's path; DAgger adds labels where the policy flies.
Chapter 0
See the seven functions you write, the runs they feed, and what each run should show
You unzip the starter code and run python main.py. It stops at the first NotImplementedError. The handout lists seven pieces to write. You fill them in, train three policies on a Flappy Bird, and measure how long each one flies.
The bird sees four numbers: the distance to the next pipe, the height of gap 1, the height of gap 2 and its own height. Its action is a target height from 0 (top) to 1 (bottom). A built-in controller turns the target into thrust, so the bird has momentum. On easy mode every pipe has one gap. On hard mode, single-gap pipes alternate with double-gap pipes.
Each problem is one fix for the wall. Its functions feed one or two training runs, and each run tests one idea.
The numbers give the build order the handout suggests. Pick a problem to light its functions, its runs and what they should show.
Functions, files and runs from the handout. The expected results are the mechanisms this page derives, not measured numbers.
| Problem | You write | You measure |
|---|---|---|
| 1 Regression | BCPolicy (networks.py), mse_loss (losses.py) | flight length on easy and on hard, and why hard fails |
| 2 Flow matching | FlowMatchingSchedule.interpolate, .sample (networks.py), flow_matching_loss (losses.py) | flight length on hard, and why it works |
| 3 DAgger | DeterministicExpert.act, rollout_episode, rollout_and_relabel (dagger.py) | a learning curve over rounds, all three compared, and why it works |
Worked number: each result is the mean and the standard deviation of episode length over 50 evaluation episodes. An episode stops at a crash or at 1,000 steps, so every mean lies between 0 and 1,000.
shellconda create -n cs224r python=3.10 -y conda activate cs224r pip install torch gymnasium pygame matplotlib "imageio[ffmpeg]" "numpy==2.2.4" python main.py --method bc_reg --env easy # Problem 1 python main.py --method bc_reg --env hard python main.py --method bc_flow --env hard # Problem 2 python main.py --method dagger --env hard # Problem 3, 5 rounds python main.py --plot # the comparison plot
The failure to expect: the handout names the loss "bc loss", but the function in losses.py is mse_loss. Fill in the function the file has. Each run writes its result file, such as bc_reg_easy.txt, into results/<timestamp>/.
Chapter 1
Cut the expert's flights into state and chunk pairs, then fit them as a regression
Problem 1 starts with data you do not write. collect_expert_data in expert.py flies the expert for 500 episodes and records every state and every target height.
Behaviour cloning treats each recorded state as an input and the expert's action as its label. Then it trains a network, as for any regression. There is no reward and no exploration.
Each label is an action chunk: the expert's next 20 targets (ACTION_CHUNK = 20). The code slides a 20-step window along each episode. Pair i is the state at step i with the actions of steps i to i + 19.
Each cell is one step of one episode. Drag the start of the window and change the episode length.
The chunk size 20 is the homework's. Episode lengths are illustrative.
Worked example: an episode of 50 steps. The last full window starts at step 30, so the episode gives 50 − 20 + 1 = 31 pairs. An episode of fewer than 20 steps gives none.
Call the network's weights θ (theta), the state of pair i si and the expert's chunk for it a*i. The network πθ maps a state to a predicted chunk. A loss ℓ scores how far a prediction is from its label.
Theta-star is the theta that makes smallest one over N times the sum over i of ell of pi-theta of s-i and a-star-i.
Run every state s-i through the network. Score each prediction against its label a-star-i with ell. Average the N scores, and change theta until the average is as small as training can make it.
With made-up numbers: N = 2 pairs with losses 0.03 and 0.05. The average is 0.04. A training step that brings it to 0.035 moves theta the right way.
Problem 1 sets ℓ to squared error. Problem 2 keeps the same loop and swaps in a flow-matching loss.
The trap: a window must stay inside one episode. A window across a boundary pairs the end of one flight with the start of the next, which no expert did. You write this windowing yourself in Chapter 8.
javascriptfunction chunkAt(actions, K, i) {
if (i < 0 || i + K > actions.length) return [];
return actions.slice(i, i + K);
}
i + K > length is the same limit as "starts 0 to L − K".Chapter 2
Stack three linear layers so four numbers in become twenty heights out, each between 0 and 1
Problem 1 asks for BCPolicy in networks.py. __init__ builds the layers and forward(state) returns the chunk. The handout fixes the stack: Linear, ReLU, Linear, ReLU, Linear, Sigmoid.
A Linear layer multiplies by a weight matrix and adds a bias. ReLU keeps positive values and sets negative ones to 0. Without it, three linear layers act as one. The sigmoid squeezes any number into the range 0 to 1, the range of a target height. B is the batch size.
Each bar is one height of a toy chunk. The band is the range a height may take. Switch the sigmoid and watch which bars leave the band.
We made up the twenty raw outputs. The layer stack and the sizes 4, 256 and 20 are the homework's.
Worked example: the last Linear layer outputs 0.8 for one step of the chunk. The sigmoid gives 1 / (1 + e−0.8) = 1 / 1.449 = 0.690. So the bird aims 69 percent of the way down. A raw output of −3 gives 0.047, near the top.
pythonclass BCPolicy(nn.Module): # the contract, from the starter def __init__(self, state_dim=4, action_dim=20, hidden=256): ... def forward(self, state): ... # [B, 4] in, [B, 20] out, values in (0, 1)
The trap: a last layer with one output. The chunk has 20 numbers, so the last Linear maps to action_dim. With one output, the loss broadcasts [B, 1] against [B, 20]. PyTorch raises no error, and every step of the chunk gets the same height.
layers is a list of {W, b}, where W[j] is the row of weights for output j.javascriptfunction mlpForward(s, layers) {
let x = s;
layers.forEach((L, li) => {
const z = L.b.map((bj, j) => bj + L.W[j].reduce((a, w, k) => a + w * x[k], 0));
x = li < layers.length - 1 ? z.map(v => Math.max(0, v)) : z.map(v => 1 / (1 + Math.exp(-v)));
});
return x;
}
self.net = nn.Sequential( nn.Linear(6, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 8), nn.Tanh(),)
Chapter 3
Average the squared errors, then see why the best single guess on hard mode sits in the wall
mse_loss(policy, s_batch, a_batch) in losses.py returns one number. Call the batch size N, the chunk length K, the predicted height for pair i at step k âik and the expert's height a*ik.
L-M-S-E equals one over N K times the sum over i and k of a-hat-i-k minus a-star-i-k, squared.
Subtract each expert height a-star from the predicted height a-hat. Square each difference. Average over all N times K heights.
With made-up numbers: N = 2, K = 2, predictions (0.4, 0.5) and (0.2, 0.3), labels (0.3, 0.5) and (0.3, 0.7). The squares are 0.01, 0, 0.01 and 0.16. L = 0.18 / 4 = 0.045.
The handout sums over the chunk and averages over N only. That is K times larger, 0.09 here, with the same best θ. The docstring asks for the mean over both.
On hard mode the expert hovers between the two gaps, then picks one at random. The same state gets two labels. Which single prediction â(s) has the lowest squared error?
A-hat of s equals the expected value of a-star given s.
For one state s, average all the expert labels a-star recorded there. No other single prediction has a lower squared error.
Illustrative: labels 0.30 and 0.70, half each, so a-hat = 0.50. The loss there is 0.04. The loss at 0.30, a real gap, is 0.08. Squared error prefers the wall.
The curve is the loss for each possible prediction. Green bands are the openings, red is the wall. Move the share of labels that pick the lower gap.
Illustrative gaps at 0.30 and 0.70. In the homework the two gap centres are 150 px apart on a 448 px screen (0.335). Each opening is 75 px tall: 0.084 either side of its centre.
Why the mean: the slope of the average squared error with respect to â is 2(â − mean). It is zero only at the mean.
The trap: square first, then average. If you average the errors and square the result, errors of +0.1 and −0.1 cancel to a loss of 0 while both predictions are wrong.
pred and target are arrays of N rows, each of K numbers.javascriptfunction mseLoss(pred, target) {
let sum = 0, n = 0;
pred.forEach((row, i) => row.forEach((p, k) => {
const d = p - target[i][k];
sum += d * d; n++;
}));
return sum / n;
}
def loss(policy, s_batch, a_batch): pred = policy(s_batch) err = pred - a_batch return err.mean() ** 2
(err ** 2).mean().Chapter 4
Draw a straight line from noise to an expert chunk, and train the network to predict its slope
Problem 2 keeps the data and changes the model. A generative policy returns one sample of a chunk, not the average of all chunks. You write FlowMatchingSchedule.interpolate (networks.py), which builds the training inputs, and flow_matching_loss (losses.py), which scores the network. The network is a given 1-D U-Net.
Start from a chunk of noise ε (epsilon): 20 numbers drawn from a standard normal distribution. Call the expert chunk a and pick a time τ (tau) between 0 and 1.
A-tau equals tau times a, plus one minus tau times epsilon.
Walk the fraction tau of the way from the noise epsilon to the expert chunk a, in a straight line. At tau = 0 you stand on the noise. At tau = 1 you stand on a.
With made-up numbers for one step of the chunk: a = 0.30, epsilon = −1.2, tau = 0.25. Then a-tau = 0.075 − 0.9 = −0.825.
Time runs left to right, height up the screen. Pick a noise draw and a gap, then move tau. The arrow is the training target.
One step of a chunk, with illustrative values. The formula for the path and the target is the handout's.
Along a straight line the speed never changes. The velocity is the whole step from noise to data, a − ε: here 0.30 − (−1.2) = 1.5. Check: −0.825 + 0.75 × 1.5 = 0.30. The network vθ learns to predict it from the state s, the point and the time.
L-F-M is the mean of the squared distance between v-theta of s, a-tau and tau, and a minus epsilon.
For each pair, draw tau and epsilon, build a-tau, ask v-theta for a velocity and score it against a minus epsilon with squared error.
Made-up: the target is 1.5 and the network predicts 1.2. This term adds (1.2 − 1.5)² = 0.09.
The trap: the target is a − ε, not a. Also, τ has shape [B] and a has shape [B, 20]. Reshape τ to [B, 1], so each row gets its own τ.
a1 and eps are arrays of the same length; tau is one number.javascriptfunction interpolate(a1, eps, tau) {
return a1.map((a, k) => tau * a + (1 - tau) * eps[k]);
}
tau = torch.rand(B, 1)eps = torch.randn_like(a)x = tau * a + (1 - tau) * epstarget = apred = net(x, s, tau.squeeze(1))loss = ((pred - target) ** 2).mean()
a - eps. With target a, the sampler integrates the wrong field.Chapter 5
Start from fresh noise and take twenty small steps along the predicted velocity
At run time there is no expert chunk. FlowMatchingSchedule.sample(model, state) starts from noise and follows the network's velocity from τ = 0 to τ = 1. Call the number of steps n (num_steps, 20 in the homework).
A at tau plus one over n equals a-tau, plus one over n times v-theta of s, a-tau and tau.
Ask the network for the velocity at the current sample and time tau. Move one n-th of it, and add one n-th to tau. Repeat n times, then clamp each height to the range 0 to 1.
With a made-up field that aims at 0.30: n = 2, start at −0.6. At tau = 0 the velocity is 0.9, so the sample moves to −0.15. At tau = 0.5 the velocity is again 0.9, and the sample lands on 0.30.
Each purple line is one sample, from noise at the left to a height at the right. The band from 0 to 1 is drawn larger. Change the number of steps and count the samples that end in a gap.
The velocity here is the exact best field for a toy expert with labels near 0.30 and 0.70 (spread 0.03), not a trained network. The 24 starting points are fixed draws.
Why not one big step: at τ = 0 the network cannot yet tell which gap a sample will reach. The best velocity there points every sample at the mean, so one step lands all of them at 0.50, the wall. Small steps let the samples separate first.
The trap: query the network at the time where the step starts, i / n, not (i + 1) / n. With (i + 1) / n the last query asks about τ = 1, and the whole path runs one step ahead.
field(x, tau) returns a velocity array the same length as x.x0.javascriptfunction eulerSample(x0, n, field) {
let x = x0.slice();
for (let i = 0; i < n; i++) {
const v = field(x, i / n);
x = x.map((xi, k) => xi + v[k] / n);
}
return x.map(xi => Math.min(1, Math.max(0, xi)));
}
x = torch.randn(B, H)dt = 1.0 / nfor i in range(n): t = torch.full((B,), (i + 1) * dt) x = x + dt * model(x, state, t)return x.clamp(0.0, 1.0)
i * dt, from 0 to 0.95.Chapter 6
Follow a small error off the expert's states, then let the expert label the states the policy visits
Problem 3 keeps the MLP and the squared loss and changes the data. The first reason is distribution shift. The expert's flights cover only the states the expert visits. A clone that drifts a little reaches states with no labels, acts worse there, and drifts further. The hero shows it.
Ross and Bagnell (2010) give the worst case. Call the clone's mistake rate on the expert's states ε and the episode length T. Cloning can add about T²ε mistakes per episode. DAgger (Ross, Gordon and Bagnell, 2011) brings that to the order of Tε, under its own assumptions.
The warm curve is cloning's worst case, the blue line DAgger's. A bound above the grey line T says nothing, since an episode has only T steps.
Worst-case orders from the two papers, with constants dropped. They are bounds, not predictions for this homework.
Worked example: ε = 0.001 and T = 100. DAgger's order is Tε = 0.1 extra mistakes. Cloning's worst case is T²ε = 10.
DAgger (dataset aggregation) asks the expert for labels at the states the policy reaches. Call the policy π, the expert πexp and the dataset D.
D becomes D, united with the set of pairs s and pi-expert of s, for every s that pi visits.
Fly the current policy pi and record its states. Ask the expert pi-expert what it would do at each one. Add those pairs to D, keep the old ones, and retrain.
The starter runs 5 rounds of 30 episodes. If each episode lasts 200 steps (an illustrative length), one round adds 30 × (200 − 19) = 5,430 pairs.
The trap: storing the policy's own action as the label. The data then teaches the policy what it already does, and the learning curve stays flat.
run_dagger in order.for ep in range(num_episodes): states, expert_acts, policy_acts = fly(policy, seed + ep) for i in range(len(states) - K + 1): new_s.append(states[i]) new_a.append(policy_acts[i:i + K])
expert_acts[i:i + K].Chapter 7
Make every new label pick the same gap, so the mean of the labels is a gap and not the wall
The second reason is the wall from Chapter 3. The expert in expert.py flips a coin at each double pipe. If DAgger relabels with that expert, the new labels split between the gaps, and squared error still averages them.
DeterministicExpert.act(obs) in dagger.py copies the expert but removes the coin. Far from the pipe, it aims at the midpoint of the two gaps. When the distance obs[0] drops below the commit distance, 0.18, it commits to one gap. That is 144 px, about 48 steps before the pipe's centre reaches the bird. The handout asks you to choose the gap rule; the class docstring names it.
Both experts smooth their targets. Call the smoothed target s, the raw target r and the smoothing factor α (alpha, 0.15).
S becomes s plus alpha times r minus s.
At each step, move the smoothed target s a fraction alpha of the way toward the raw target r.
Illustrative: s = 0.50 at the midpoint, the expert commits to r = 0.30, alpha = 0.15. Step 1: 0.50 + 0.15 × (−0.20) = 0.47. After 6 steps s = 0.375, inside the opening, which reaches 0.084 either side of 0.30.
Six episodes approach the same double pipe. Each line is the target an expert returns. The dashed line is the mean of the labels, the thing squared error learns.
Illustrative gaps at 0.30 and 0.70 and fixed coin flips. The commit distance 0.18, alpha 0.15 and the hover-then-commit rule are the starter's.
The trap: an expert that keeps memory across episodes. act stores the last gap signature and the smoothed target. Reset the expert before each episode, or its first labels come from the last flight.
[dist, g1, g2].javascriptfunction lowerGapTargets(obsList, commitDist, alpha) {
let s = null;
return obsList.map(([dist, g1, g2]) => {
const raw = dist < commitDist ? g2 : (g1 + g2) / 2;
s = s === null ? raw : s + alpha * (raw - s);
return s;
});
}
Chapter 8
Fly the policy chunk by chunk, ask the expert at every step, and cut the answers into windows
Two functions remain. rollout_episode flies the current policy for one episode and records each state with the expert's label. rollout_and_relabel runs it for many episodes and windows the labels into pairs, the way collect_expert_data does for the demos.
The policy flies with receding-horizon control. It predicts 20 actions, executes the first 10 (EXECUTE_STEPS), then asks again with a fresh state. In code, keep a chunk buffer and a step counter. Query the policy when the buffer is empty or the counter reaches 10, and set the counter back to 0 after each query.
Top row: the actions the policy executes, with a mark at each query. Bottom row: the expert's label at every step. Pick how many actions run per query, and slide the window.
A 45-step toy episode. The chunk of 20 and the 10 executed steps are the homework's.
Worked example: an episode of 45 steps with 10 executed per query. The loop queries the policy at steps 0, 10, 20, 30 and 40: 5 queries. The expert answers at all 45 steps, so the episode gives 45 − 19 = 26 pairs.
The policy's actions move the bird. The expert's actions are only labels. That split is the point of DAgger: states from the learner, labels from the expert.
python# the environment calls you need (from the starter's hints) obs, info = env.reset(seed=seed) # obs: shape (4,) obs, reward, terminated, truncated, info = env.step(np.array([action])) done = terminated or truncated # crash, or 1,000 steps
The trap: windows across episodes. Cut each episode's list on its own, then append its pairs. Use seed + ep as the seed of episode ep, so each episode flies a different course.
rollout_episode, which action goes to env.step?policy(t) returns a chunk for the state at step t.javascriptfunction recedingActions(policy, T, E) {
let chunk = null, k = 0;
const out = [];
for (let t = 0; t < T; t++) {
if (chunk === null || k >= E) { chunk = policy(t); k = 0; }
out.push(chunk[k]);
k++;
}
return out;
}
chunk, k = None, 0while not done: if chunk is None or k >= EXECUTE_STEPS: chunk, k = policy_chunk(obs), 0 action = chunk[0] k += 1 obs, r, term, trunc, _ = env.step(np.array([action])) done = term or trunc
chunk[k], the next unexecuted one.Chapter 9
Fly 50 episodes, read the mean and the spread of their lengths, and draw the plots that compare the policies
A low training loss does not show that the bird flies. evaluate_policy in visualization.py flies the policy for 50 episodes and records each episode length: the steps before a crash, at most 1,000. A flight of 1,000 steps counts as a success.
Call the lengths L1 to LM, their number M and their mean μ (mu). The spread is the standard deviation σ (sigma).
Sigma is the square root of one over M times the sum over m of L-m minus mu, squared.
Subtract the mean mu from each length L-m, square, average over the M episodes, and take the square root. numpy's np.std divides by M, not M − 1.
With made-up lengths 1,000, 600, 1,000 and 600: mu = 800. Every length is 200 from the mean, so sigma = 200 steps.
Each dot is one toy episode. Move the share of episodes that crash early and watch the mean and the spread.
Toy lengths we made up, not results of the homework. Your own runs give your numbers.
A large σ next to a middling μ means the policy either survives or crashes early. Each run also saves five trajectories to its result file. Read them before you explain a result.
| Run | Measure |
|---|---|
bc_reg, easy and hard | mean ± std on each mode; then explain the drop on hard |
bc_flow, hard | mean ± std; then explain why it clears the double pipes |
dagger, hard | a learning curve: round on x, mean length on y, std as error bars, regression as a horizontal line |
--plot | a bar chart or table of all three on hard |
The trap: a learning curve without the error bars or without the regression line. Without both on one plot you cannot tell real progress from noise, or see whether DAgger beats the baseline.
np.std does. Give one decimal.lengths.np.std does).[mean, std].javascriptfunction meanStd(lengths) {
const M = lengths.length;
const mu = lengths.reduce((a, L) => a + L, 0) / M;
const v = lengths.reduce((a, L) => a + (L - mu) ** 2, 0) / M;
return [mu, Math.sqrt(v)];
}
Chapter 10
Check your runs, keep the terms and numbers on one page, and go further
Three policies, one bird. Regression learns the mean of the labels, which on hard mode is the wall. Flow matching keeps the data and learns to sample one gap. DAgger keeps the model, labels the states the policy visits, and makes those labels agree on one gap.
bc_reg_easy.txt, bc_reg_hard.txt, bc_flow_hard.txt and dagger_hard.txt.| Result | Chapter |
|---|---|
| regression on easy | 2, 3, 9 |
| why regression fails on hard | 3 |
| flow matching on hard | 4, 5, 9 |
| why flow matching works | 5 |
| the DAgger learning curve | 6, 7, 8, 9 |
| all three compared | 9 |
| why DAgger improves | 6, 7 |
| Term or number | Meaning |
|---|---|
| observation | [distance to pipe, gap 1 height, gap 2 height, bird height], each normalised |
| action | a target height from 0 (top) to 1 (bottom); a PD controller makes the thrust |
| chunk 20, execute 10 | predict 20 targets, run the first 10, query again |
| 500 demo episodes | the expert data for cloning |
| commit distance 0.18 | where the expert picks a gap, about 48 steps before the pipe |
| smoothing 0.15 | the expert's step toward its raw target |
| gaps 150 px apart, 75 px tall | on a 448 px screen: 0.335 apart, 0.084 either side of a centre |
| num_steps 20 | Euler steps per sampled chunk |
| 5 rounds, 30 episodes | the DAgger defaults in main.py |
| 50 episodes, cap 1,000 | each evaluation; lengths from 0 to 1,000 steps |
summarycloning θ* = argminθ (1/N) Σi ℓ(πθ(si), a*i)
regression L = mean of (â − a*)² best guess: â(s) = E[a* | s]
flow path aτ = τa + (1 − τ)ε target velocity: a − ε
sampling aτ+1/n = aτ + (1/n) vθ(s, aτ, τ), then clamp to [0, 1]
DAgger D ← D ∪ {(s, πexp(s)) : s visited by π}
smoothing s ← s + α(r − s)
evaluation mean ± std of 50 episode lengths
| Topic | Lesson |
|---|---|
| Cloning, DAgger and inverse RL in depth | Imitation Learning |
| Generative action models for robots | Diffusion Policy |
| The flow-matching model from scratch | Flow Matching |
| Learning from reward instead of labels | Policy Gradients |
| The next homework: online RL | CS 224R HW2 |
| Expert data plus value learning | Offline RL |
Sources: Ross and Bagnell, "Efficient Reductions for Imitation Learning" (2010). Ross, Gordon and Bagnell, "A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning" (2011). Lipman et al., "Flow Matching for Generative Modeling" (2022).
Course credit: this page follows Homework 1 of Stanford CS 224R, Spring 2026. Read the handout and the starter code for the exact contracts.
Now teach it back: open Present or Teach from the hero, or press Studio to write the Python kernels in the Forge Studio. Then go back to the hero and find the gust size where cloning starts to crash.