CS 224R HW1: Imitation Learning

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.

Fly the copy along the path

100%

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.

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

Chapter 0

The Map: What You Build

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.

What feeds what

Each problem is one fix for the wall. Its functions feed one or two training runs, and each run tests one idea.

Trace a function to its run

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.

ProblemYou writeYou measure
1 RegressionBCPolicy (networks.py), mse_loss (losses.py)flight length on easy and on hard, and why hard fails
2 Flow matchingFlowMatchingSchedule.interpolate, .sample (networks.py), flow_matching_loss (losses.py)flight length on hard, and why it works
3 DAggerDeterministicExpert.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.

Set up and run

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

The road

  1. The expert data: windows of 20 actions, and cloning as regression.
  2. The policy network: four numbers in, twenty heights out.
  3. The regression loss: why the best guess lands in the wall.
  4. Flow matching: the path: a straight line from noise, and its slope.
  5. Flow matching: sampling: twenty small steps from noise to a gap.
  6. DAgger: the drift: the hero's Cloning only and DAgger.
  7. The deterministic expert: labels that agree on one gap.
  8. Roll out and relabel: chunks, queries and windows.
  9. Evaluate by rollouts: mean, spread and the plots.
  10. The field guide: the checklist, the terms, the links.
The handout asks you to implement "bc loss". Which function in losses.py do you fill in?

Workbook

Exercise 0.1: A capped mean Derive
A toy policy flies 50 evaluation episodes. 20 reach the cap of 1,000 steps. The other 30 crash at step 100. What is the mean episode length?
steps
Show derivation
capped flights: 20 × 1,000 = 20,000 steps
early crashes: 30 × 100 = 3,000 steps
mean = 23,000 / 50 = 460
No single flight lasted 460 steps. A mean of a crash-or-survive policy hides two groups; Chapter 9 adds the spread to show them.
Exercise 0.2: Find the file Trace
You want to change how the Euler sampler steps through time. Which file do you open?
Exercise 0.3: Order the build Design
Tap the chips in the order the handout recommends.
?
→
?
→
?
→
?
→
?
→
?
→
?
flow_matching_loss rollout_episode BCPolicy DeterministicExpert.act mse_loss rollout_and_relabel interpolate and sample

Chapter 1

The Expert Data and the Cloning Objective

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.

Slide the window along an episode

Each cell is one step of one episode. Drag the start of the window and change the episode length.

50
0

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.

The objective

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.

Say it aloud

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.

θ*
theta-star the weights that training ends with.
argminθ
the theta that makes smallest search over weights for the lowest value of what follows.
1/N
one over N divide by the number of pairs N, so the sum becomes an average.
Σi
the sum over i one term for each pair, i from 1 to N.
ℓ
ell the loss for one pair: squared error in Problem 1.
πθ(si)
pi-theta of s-i the network's predicted chunk of 20 heights for state s-i.
a*i
a-star-i the expert's chunk for the same state: the label.
In plain words

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 numbers

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.

An episode lasts 25 steps. How many (state, chunk) pairs does it give?

Workbook

Exercise 1.1: Count the pairs Derive
An expert episode lasts 137 steps. How many (state, chunk) pairs does it give with chunks of 20?
pairs
Show derivation
last start step = 137 − 20 = 117
starts 0, 1, ..., 117 = 118 pairs
The final 19 steps appear only as labels, never as the state of a pair.
Exercise 1.2: Read the observation Trace
On easy mode, obs[1] and obs[2] always hold the same number. Why?
Exercise 1.3: Cut one chunk Build
Write the label of pair i from one episode's list of per-step actions.
  1. If a full chunk of K actions starts at step i, return the K actions from step i.
  2. If it does not fit (too close to the end, or i is negative), return an empty array.
Show solution
javascriptfunction chunkAt(actions, K, i) {
  if (i < 0 || i + K > actions.length) return [];
  return actions.slice(i, i + K);
}
The test i + K > length is the same limit as "starts 0 to L − K".
Exercise 1.4: What cloning needs Trace
Which of these does behaviour cloning use during training?

Chapter 2

The Policy Network

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.

Switch the sigmoid off

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.

Why does the stack end with a sigmoid?

Workbook

Exercise 2.1: Count the weights Derive
Count every weight and bias of the 4 → 256 → 256 → 20 stack. ReLU and the sigmoid have none.
parameters
Show derivation
layer 1: 4 × 256 + 256 = 1,280
layer 2: 256 × 256 + 256 = 65,792
layer 3: 256 × 20 + 20 = 5,140
total = 72,212
The middle layer holds 91 percent of the weights.
Exercise 2.2: One sigmoid Derive
The last Linear layer outputs 2 for one step. What height does the policy aim at? Give three decimals.
Show derivation
e−2 = 0.135
1 / (1 + 0.135) = 0.881
Height 0.881 is near the bottom of the screen, because 1 is the bottom.
Exercise 2.3: A tiny forward pass Build
Write the forward pass of a small MLP. layers is a list of {W, b}, where W[j] is the row of weights for output j.
  1. For each layer, compute out[j] = b[j] + the sum over k of W[j][k] × x[k].
  2. After every layer except the last, apply ReLU: max(0, value).
  3. After the last layer, apply the sigmoid 1 / (1 + e−value).
  4. Return the output array.
Show solution
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;
}
Exercise 2.4: The height that goes negative Debug
A neighbouring policy maps a 6-number state to 8 heights in (0, 1). Its outputs go below 0. Click the buggy line.
self.net = nn.Sequential(    nn.Linear(6, 128), nn.ReLU(),    nn.Linear(128, 128), nn.ReLU(),    nn.Linear(128, 8), nn.Tanh(),)
Show explanation
Line 4 ends with tanh, whose range is −1 to 1. A height in (0, 1) needs a sigmoid.

Chapter 3

The Regression Loss and the Wall

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.

Say it aloud

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.

LMSE
L-M-S-E the mean squared error: one number for the batch.
1/(NK)
one over N K divide by the count of all heights: N pairs times K steps.
ΣiΣk
the sum over i and k one term per pair i and per chunk step k.
âik
a-hat-i-k the network's height for pair i, step k.
a*ik
a-star-i-k the expert's height there.
( )2
squared the error times itself, so signs cannot cancel and big misses cost more.
In plain words

Subtract each expert height a-star from the predicted height a-hat. Square each difference. Average over all N times K heights.

With numbers

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.

The best guess is the mean

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?

Say it aloud

A-hat of s equals the expected value of a-star given s.

â(s)
a-hat of s the prediction with the lowest squared error at state s.
E[ ]
the expected value of the average of what is inside, over many draws.
a*
a-star one expert label.
| s
given s count only the labels recorded at state s.
In plain words

For one state s, average all the expert labels a-star recorded there. No other single prediction has a lower squared error.

With numbers

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.

Split the labels between two gaps

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.

50%

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.

At one state, 70 percent of labels say 0.30 and 30 percent say 0.70. Where does the squared-error optimum sit?

Workbook

Exercise 3.1: An uneven split Derive
At one state, three labels say 0.30 and one says 0.70. What does the squared-error optimum predict?
Show derivation
mean = (3 × 0.30 + 0.70) / 4 = 1.60 / 4 = 0.40
0.40 is 0.10 from the upper centre. An opening reaches 0.084 either side, so the bird still aims at the wall.
Exercise 3.2: The loss at the optimum Derive
Same labels: three at 0.30, one at 0.70. What is the average squared error of the prediction 0.40? Give three decimals.
Show derivation
three labels: (0.40 − 0.30)² = 0.01 each
one label: (0.40 − 0.70)² = 0.09
(3 × 0.01 + 0.09) / 4 = 0.12 / 4 = 0.030
Aiming at the common gap, 0.30, costs (0 + 0 + 0 + 0.16) / 4 = 0.040. The wall wins again.
Exercise 3.3: Mean squared error Build
Write the loss of the equation above for a batch of chunks.
  1. pred and target are arrays of N rows, each of K numbers.
  2. Square each difference pred[i][k] − target[i][k].
  3. Return the mean over all N × K squares.
Show solution
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;
}
Exercise 3.4: The loss that says zero Debug
This loss reports 0 for predictions (0.4, 0.2) against labels (0.3, 0.3). Click the buggy line.
def loss(policy, s_batch, a_batch):    pred = policy(s_batch)    err = pred - a_batch    return err.mean() ** 2
Show explanation
Line 4 averages first. The errors +0.1 and −0.1 cancel. Square each error, then average: (err ** 2).mean().

Chapter 4

Flow Matching: the Path and the Velocity Target

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.

Say it aloud

A-tau equals tau times a, plus one minus tau times epsilon.

aτ
a-tau the point on the path at time tau: the network's input.
τ
tau the flow time, drawn uniformly from 0 to 1 for each pair.
a
a the expert's chunk: the end of the path.
ε
epsilon the noise chunk: the start of the path, same shape as a.
In plain words

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 numbers

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.

Walk the path from noise to a gap

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.

0.25

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.

Say it aloud

L-F-M is the mean of the squared distance between v-theta of s, a-tau and tau, and a minus epsilon.

LFM
L-F-M the flow-matching loss for the batch.
mean
the mean of the average over pairs and chunk steps.
vθ(s, aτ, τ)
v-theta of s, a-tau and tau the network's predicted velocity.
a − ε
a minus epsilon the target velocity: the slope of the straight path.
‖ ‖2
the squared distance the sum of squared differences over the chunk.
In plain words

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.

With numbers

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

With ε = 0.4 and a = 0.70, what is the training target?

Workbook

Exercise 4.1: A point on the path Derive
a = 0.70, ε = 0.5, τ = 0.6. Compute aτ.
Show derivation
0.6 × 0.70 = 0.42
0.4 × 0.5 = 0.20
aτ = 0.62
The target velocity is 0.70 − 0.5 = 0.20. From 0.62, the remaining 0.4 of time at speed 0.20 reaches 0.70.
Exercise 4.2: The two ends Trace
During training, τ happens to be 0 for one pair. What is the network's input aτ?
Exercise 4.3: Interpolate a chunk Build
Write the path point for one chunk. The noise comes in as an argument so the tests are repeatable.
  1. a1 and eps are arrays of the same length; tau is one number.
  2. Return the array of tau × a1[k] + (1 − tau) × eps[k].
Show solution
javascriptfunction interpolate(a1, eps, tau) {
  return a1.map((a, k) => tau * a + (1 - tau) * eps[k]);
}
In PyTorch the batch has one τ per row, so τ needs shape [B, 1] before it multiplies a [B, 20] tensor.
Exercise 4.4: The loss that learns the mean Debug
A neighbouring flow policy trains, but its samples land between the gaps. Click the buggy line.
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()
Show explanation
Line 4 uses the clean chunk as the target. The velocity of the straight path is a - eps. With target a, the sampler integrates the wrong field.

Chapter 5

Flow Matching: Sampling by Integrating

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

Say it aloud

A at tau plus one over n equals a-tau, plus one over n times v-theta of s, a-tau and tau.

aτ+1/n
a at tau plus one over n the sample after one step.
aτ
a-tau the sample now. At tau = 0 it is fresh noise.
1/n
one over n the step size: 0.05 for n = 20.
vθ(s, aτ, τ)
v-theta of s, a-tau and tau the velocity the network predicts here and now.
In plain words

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 numbers

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.

Integrate noise into heights

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.

20

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.

With n = 20, at what times τ does the sampler query the network?

Workbook

Exercise 5.1: One Euler step Derive
A made-up field aims at 0.70: v(x, τ) = (0.70 − x) / (1 − τ). Take n = 3 and start at x = −0.5. Where is the sample after the first step?
Show derivation
τ = 0: v = (0.70 + 0.5) / 1 = 1.2
x = −0.5 + (1/3) × 1.2 = −0.1
The next two steps also move 0.4 each, so the sample ends on 0.70.
Exercise 5.2: One step only Trace
The labels split half and half between 0.30 and 0.70. You sample with n = 1 and a perfect network. Where do the samples land?
Exercise 5.3: An Euler sampler Build
Write the sampler for one chunk. field(x, tau) returns a velocity array the same length as x.
  1. Start from the noise array x0.
  2. For i = 0 to n − 1: set tau = i / n, get the velocity, move x by velocity / n.
  3. Clamp every value to the range 0 to 1 and return the array.
Show solution
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)));
}
Exercise 5.4: One step ahead Debug
This sampler asks the network about the wrong time. Click the buggy line.
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)
Show explanation
Line 4 queries at the end of the step. Euler uses the velocity where the step starts: i * dt, from 0 to 0.95.

Chapter 6

DAgger: Why Cloning Drifts and How Relabelling Fixes It

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.

Grow the horizon

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.

0.001
100

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.

The DAgger loop

DAgger (dataset aggregation) asks the expert for labels at the states the policy reaches. Call the policy π, the expert πexp and the dataset D.

Say it aloud

D becomes D, united with the set of pairs s and pi-expert of s, for every s that pi visits.

D
D the training set: the expert demos plus every earlier round's pairs.
←
becomes replace D with the right side.
∪
united with keep every old pair and add the new ones.
πexp(s)
pi-expert of s the expert's action at state s: the label.
s visited by π
s visited by pi the states the current policy reaches when it flies.
In plain words

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.

With numbers

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.

In DAgger, who supplies the states and who supplies the labels?

Workbook

Exercise 6.1: The worst case Derive
ε = 0.0005 and T = 200. Compute cloning's worst-case order T²ε.
mistakes
Show derivation
T² = 40,000
40,000 × 0.0005 = 20
Tε = 0.1. Doubling T doubles DAgger's order and multiplies cloning's by four.
Exercise 6.2: Why the old demos stay Trace
Round 3 retrains on D. Why keep the expert demos and the pairs of rounds 1 and 2?
Exercise 6.3: One round in order Design
Tap the steps of one round of run_dagger in order.
?
→
?
→
?
→
?
→
?
add the pairs to D evaluate the policy retrain on all of D fly the policy label each state with the expert
Exercise 6.4: The flat learning curve Debug
A DAgger loop runs five rounds and never improves. Click the buggy line.
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])
Show explanation
Line 5 windows the policy's own actions. The labels must be the expert's: expert_acts[i:i + K].

Chapter 7

The Deterministic Expert

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

Say it aloud

S becomes s plus alpha times r minus s.

s
s the smoothed target the expert returns.
←
becomes the new value replaces the old one, once per step.
α
alpha the share of the gap closed each step: 0.15.
r
r the raw target: the midpoint before the commit, one gap after it.
In plain words

At each step, move the smoothed target s a fraction alpha of the way toward the raw target r.

With numbers

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.

Relabel with each expert

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.

0.15

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.

DAgger relabels with the random expert instead. What happens?

Workbook

Exercise 7.1: One smoothing step Derive
s = 0.50, the expert commits to r = 0.70, and α = 0.3. What is s after one step?
Show derivation
s = 0.50 + 0.3 × (0.70 − 0.50) = 0.50 + 0.06 = 0.56
Exercise 7.2: Steps into the opening Derive
Same start, r = 0.70, α = 0.3. After how many steps is s first within 0.084 of 0.70?
steps
Show derivation
the distance to r shrinks by 0.7 each step: 0.20 × 0.7k
k = 1: 0.140, k = 2: 0.098, k = 3: 0.069
first below 0.084 at k = 3
With α = 0.15 it takes 6 steps, still far fewer than the 48 steps between commit and pipe.
Exercise 7.3: A lower-gap expert Build
A neighbouring expert always commits to the lower gap, gap 2. Write the targets it returns over one approach.
  1. Each observation is [dist, g1, g2].
  2. If dist < commitDist, the raw target is g2. Otherwise it is the midpoint (g1 + g2) / 2.
  3. The first smoothed target equals the first raw target. After that, s = s + alpha × (raw − s).
  4. Return the list of smoothed targets.
Show solution
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;
  });
}
Exercise 7.4: Where the gap rule matters Trace
On a single-gap pipe in hard mode, does it matter which gap the expert commits to?

Chapter 8

Roll Out and Relabel

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.

Fly one episode and cut it

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.

0

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.

In rollout_episode, which action goes to env.step?

Workbook

Exercise 8.1: Count the queries Derive
An episode crashes after 85 steps. The policy executes 10 actions per query. How many times is the policy queried?
queries
Show derivation
queries at steps 0, 10, 20, ..., 80
80 / 10 + 1 = 9
The ninth chunk runs only steps 80 to 84 before the crash.
Exercise 8.2: Receding horizon Build
Write the list of actions a policy executes over T steps. policy(t) returns a chunk for the state at step t.
  1. Keep a chunk and a counter. At the start the chunk is empty.
  2. If there is no chunk or the counter has reached E, set chunk = policy(t) and the counter to 0.
  3. Execute chunk[counter], then add 1 to the counter.
  4. Return the T executed actions.
Show solution
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;
}
Exercise 8.3: The bird that repeats itself Debug
This rollout queries every 10 steps, but the bird holds one height for each 10 steps. Click the buggy line.
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
Show explanation
Line 5 always takes the first action of the chunk. It must take chunk[k], the next unexecuted one.
Exercise 8.4: Which labels go with a state Trace
After a rollout you have the states s0 to s44 and the expert's answers e0 to e44. Which label chunk goes with s7?

Chapter 9

Evaluate a Policy by Rollouts

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

Say it aloud

Sigma is the square root of one over M times the sum over m of L-m minus mu, squared.

σ
sigma the standard deviation of the episode lengths, in steps.
√
the square root of brings squared steps back to steps.
1/M
one over M divide by the number of episodes, 50 here.
Σm
the sum over m one term per episode m.
Lm
L-m the length of episode m, from 0 to 1,000 steps.
μ
mu the mean length: the sum of the lengths divided by M.
In plain words

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 numbers

With made-up lengths 1,000, 600, 1,000 and 600: mu = 800. Every length is 200 from the mean, so sigma = 200 steps.

Read a mean and a spread

Each dot is one toy episode. Move the share of episodes that crash early and watch the mean and the spread.

30%

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.

What to measure

RunMeasure
bc_reg, easy and hardmean ± std on each mode; then explain the drop on hard
bc_flow, hardmean ± std; then explain why it clears the double pipes
dagger, harda learning curve: round on x, mean length on y, std as error bars, regression as a horizontal line
--plota 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.

Policy A: 600 ± 20. Policy B: 600 ± 400. What does B's spread tell you?

Workbook

Exercise 9.1: The mean Derive
Four toy episodes last 1,000, 400, 1,000 and 200 steps. What is the mean length?
steps
Show derivation
(1,000 + 400 + 1,000 + 200) / 4 = 2,600 / 4 = 650
Exercise 9.2: The spread Derive
Same four lengths. Compute the standard deviation the way np.std does. Give one decimal.
steps
Show derivation
differences: 350, −250, 350, −450
squares: 122,500 + 62,500 + 122,500 + 202,500 = 510,000
510,000 / 4 = 127,500; √127,500 = 357.1
Dividing by 3 instead would give 412.3. Use the same form as the starter.
Exercise 9.3: Mean and spread Build
Write the two numbers a results table needs.
  1. Compute the mean of lengths.
  2. Compute the standard deviation, dividing by the count (as np.std does).
  3. Return [mean, std].
Show solution
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)];
}
Exercise 9.4: Draw the learning curve Trace
Which plot shows whether DAgger improves round by round?

Chapter 10

The Field Guide

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.

Run checklist

The chapter behind each result

ResultChapter
regression on easy2, 3, 9
why regression fails on hard3
flow matching on hard4, 5, 9
why flow matching works5
the DAgger learning curve6, 7, 8, 9
all three compared9
why DAgger improves6, 7

Terms and numbers

Term or numberMeaning
observation[distance to pipe, gap 1 height, gap 2 height, bird height], each normalised
actiona target height from 0 (top) to 1 (bottom); a PD controller makes the thrust
chunk 20, execute 10predict 20 targets, run the first 10, query again
500 demo episodesthe expert data for cloning
commit distance 0.18where the expert picks a gap, about 48 steps before the pipe
smoothing 0.15the expert's step toward its raw target
gaps 150 px apart, 75 px tallon a 448 px screen: 0.335 apart, 0.084 either side of a centre
num_steps 20Euler steps per sampled chunk
5 rounds, 30 episodesthe DAgger defaults in main.py
50 episodes, cap 1,000each evaluation; lengths from 0 to 1,000 steps

The equations

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

Keep going

TopicLesson
Cloning, DAgger and inverse RL in depthImitation Learning
Generative action models for robotsDiffusion Policy
The flow-matching model from scratchFlow Matching
Learning from reward instead of labelsPolicy Gradients
The next homework: online RLCS 224R HW2
Expert data plus value learningOffline 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.

The one idea. Squared error learns the mean of the labels it sees. Change what it sees (DAgger with one consistent gap) or change what it learns (a velocity that carries noise to one gap).

Workbook

Exercise 10.1: Name the mechanism Trace
DAgger on hard flies longer each round. Which explanation names the mechanism?

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.

CS 224R HW1: Imitation Learning
Read the handout · Back to Gleams