CS 224R HW3: Offline RL

Learn a policy from a fixed log, with no new tries. Homework 3 has you build AWAC and IQL, then test whether IQL joins two half-trips into a path that no single trip in the data shows.

A lesson with a workbook. Each chapter explains one part of the homework, then gives you exercises on our own toy data.

Press Play. Behaviour cloning copies the log and turns into the dead end. Switch to IQL and play again: it follows trip A, then takes trip B's turn at the junction. Then we build each piece.

You need some Python, a neural network as a function, and the Bellman equation from Homework 2. The exercises run JavaScript in your browser.

Based on Homework 3 of Stanford CS 224R: Deep Reinforcement Learning (Spring 2026). The handout and starter code belong to the course. This page teaches the skills in our own words, on toy data. The Studio pill opens the Forge Studio, where you write the NumPy kernels.

Roll out a policy learned from the log

A toy map with exact moves, made up for this page. The log holds trip A twice and trip B once. The page runs tabular IQL on these 32 transitions. The settings are the homework's PointMass ones: γ = 0.95, reward −1 per step and 0 on reaching the goal, ζ = 0.9, λ = 0.1, weight cap 50.

Workbook progress
0 / 39 exercises (0%)
0
Day streak
Best: 0
39 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser.

Chapter 0

The Map: What You Build

See the five parts, the five files you edit, and the run each part trains

You get a file of logged transitions and no simulator during training. You fill the TODO blocks in five files, train on Modal, log to Weights & Biases, and compare the methods in tables. Offline RL means learning a policy from a fixed dataset, with no new interaction until evaluation.

The homework has two problems. Problem 1 builds AWAC, the advantage-weighted actor-critic. Problem 2 builds IQL, implicit Q-learning, then tests it on a PointMass dataset made for stitching.

PartTaskChapter
P1.1AWAC on antmaze-umaze, 3 seeds, about 1 hour2 to 5
P1.2AWAC on antmaze-medium-diverse, about 1.5 hours5
P2.1IQL with ζ = 0.2 and 0.9 on umaze; say which wins and why6, 7, 8
P2.2IQL on medium-diverse with the better ζ; compare with AWAC8
P2.3IQL against filtered BC on the stitching dataset9

Every run logs Eval_AverageReturn to the W&B dashboard: the mean return of the evaluation episodes. That curve, one per seed, is the result of each part.

Find the files for each part

Pick a part. The left column lights the files you edit. The right column lights the run it trains.

File names, datasets and run times from the handout and the starter repo.

Set up and run one seed

shellconda create -n cs224r-hw3 python=3.10.19 && conda activate cs224r-hw3
pip install modal && modal setup
wandb login                                  # once per machine
modal run --detach modal_train.py --algo awac --env-name antmaze-umaze-v0 \
    --exp-name awac_antmaze_umaze --use-wandb --seed 1     # one seed, for debugging
modal run --detach modal_train_para.py --algo awac --env-name antmaze-umaze-v0 \
    --exp-name awac_antmaze_umaze --use-wandb              # three seeds, for the comparison
modal volume get cs224r-hw3-results / ./data/              # logs, checkpoints, videos

The failure to expect: a three-seed run burns an hour, then shows a flat return. Debug on one seed first and watch the losses. Chapter 10 lists what healthy curves look like.

The road

  1. The log and the trap: why a Q-network lies at actions the data never tried.
  2. The AWAC critic: the Bellman target with the smaller of two critics.
  3. The AWAC advantage: one sampled action as the baseline.
  4. The AWAC actor: imitation weighted by exp(A / λ).
  5. Targets and the AWAC runs: the Polyak update, then P1.1 and P1.2.
  6. The IQL value: expectile regression. The hero's Show V(s).
  7. The IQL Q target and policy: bootstrap on V(s′), no sampled action. The hero's IQL.
  8. The ζ sweep and the hard maze: P2.1 and P2.2.
  9. Stitching on PointMass: P2.3 against filtered BC. The hero's junction.
  10. The field guide: symptoms, the checklist, links.
You swept ζ = 0.2 and 0.9 on umaze for P2.1. Which ζ do you run on the medium maze in P2.2?

Workbook

Exercise 0.1: Count the training runs Derive
Every method in every part trains on three seeds. P2.1 sweeps two values of ζ, and P2.3 trains IQL and filtered BC. How many single-seed training runs does the whole homework need?
runs
Show derivation
P1.1, P1.2, P2.2: one method each = 3 × 3 = 9 runs
P2.1: two ζ = 2 × 3 = 6 runs; P2.3: two methods = 2 × 3 = 6 runs
9 + 6 + 6 = 21 runs
Most of these take an hour or more. Debug on one seed first: a bug caught there saves a three-seed run.
Exercise 0.2: Order the work on one part Design
Tap the chips in the order you should do them.
?
→
?
→
?
→
?
→
?
three-seed run with modal_train_para.py fill the TODO blocks read the final Eval_AverageReturn of each seed one-seed run, watch the losses final values to mean and std in the table

Chapter 1

The Log and the Trap

Read one transition, score one episode, then watch a Q-network invent value where the data is silent

Every training batch comes from a fixed set of transitions (s, a, r, s′, d): state, action, reward, next state and a done flag. Another policy collected them. The set never grows.

Both domains use a sparse reward: −1 on every step and 0 on the step that reaches the goal. The return is the sum of an episode's rewards. A success with T transitions returns −(T − 1). A failure returns close to minus the episode length.

DomainStateActionSettings in the starter
PointMassx and y position, normalized5 choices: stay, down, up, left, right, with noiseγ = 0.95, 50,000 steps
AntMazethe ant's body and positioncontinuous joint torquesγ = 0.99, 1,000,000 steps

Worked number: the best trajectory in the stitching dataset has 47 transitions. Its last step reaches the goal, so its return is 46 × (−1) + 0 = −46.

Now the trap. A Q-network maps a state and an action to an estimate of the return. Where the data has actions, the loss pins the estimate down. Elsewhere the network extrapolates: it outputs whatever its shape suggests, and nothing corrects it.

Fit Q on logged actions, then let a greedy policy choose

Dots are noisy Q targets at the logged actions. The blue curve is a fit. Raise the fit's flexibility or redraw the noise, and watch where the greedy pick lands.

4

Illustrative: a made-up true curve, 12 logged actions with noise of 0.15, and a least-squares polynomial standing in for the network.

Online, the agent would try the picked action and learn that it is bad. Offline, no new transition arrives. The policy moves toward the error, the next Bellman target reads it, and the error spreads. This is distribution shift.

One check catches it. With rewards in {−1, 0}, every true Q lies between −1 / (1 − γ) and 0. For PointMass that is −20 to 0. Log the mean and maximum Q; a value above 0 is an error by construction.

Why does the greedy pick drift to the edge of the plot when the fit is flexible?

Workbook

Exercise 1.1: Return of a success Derive
A PointMass episode reaches the goal on its 30th transition. What is its return?
Show derivation
29 steps that do not reach the goal: 29 × (−1) = −29
the 30th step reaches the goal: + 0
return = −29
Exercise 1.2: The lowest possible Q Derive
Rewards are −1 or 0 and γ = 0.95. An agent that never reaches the goal collects −1 forever. What is the discounted sum, the lowest true Q?
Show derivation
−1 − 0.95 − 0.95² − … = −1 / (1 − 0.95)
= −1 / 0.05 = −20
A logged Q below −20 or above 0 on PointMass is a bug, not a learning signal. On AntMaze, with γ = 0.99, the floor is −100.
Exercise 1.3: Split a log into episode returns Build
The dataset stores flat arrays. Write the function that splits them into episodes and returns each episode's return.
  1. Walk the arrays in order and add each reward to a running sum.
  2. If dones[i] is 1, push the sum and start a new one.
  3. If the log ends with no done flag, push the last partial sum too.
Show solution
javascriptfunction episodeReturns(rewards, dones) {
  const out = [];
  let sum = 0, open = false;
  for (let i = 0; i < rewards.length; i++) {
    sum += rewards[i]; open = true;
    if (dones[i]) { out.push(sum); sum = 0; open = false; }
  }
  if (open) out.push(sum);
  return out;
}
The starter's filtered BC ranks trajectories by exactly these returns before it keeps the top 10 percent.
Exercise 1.4: Where the error goes Trace
An offline critic over-estimates one unlogged action by +3. The actor is free to pick any action. What happens over training?

Chapter 2

The AWAC Critic: Two Critics, Take the Smaller

Build the Bellman target with a terminal mask and the minimum of two target critics

In awac_critic.py, update() receives a batch and one next action per transition. You compute the target, then a squared-error loss for each of the two online critics, q_net and q_net2. The starter does the backward pass.

Each critic has a target network: a slow copy that supplies the label. A critic's error at one action is noise. Take the larger of two noisy estimates and you keep the lucky one, so the target drifts up. Take the smaller and the drift reverses.

Compare one critic, the max of two and the min of two

Each tick is one state: the estimate minus the true value. Pick a rule and read the average error. Then raise the noise.

1.0

Illustrative: 400 toy states, each critic off by independent Gaussian noise. The max of two is on average +0.56σ high; the min is 0.56σ low.

Name the parts. The reward is r, the discount is γ, the done flag is d. The next action a′ is one sample from the current actor at the next state s′. The two target critics are Q1 and Q2.

Say it aloud

y equals r plus gamma times one minus d, times the smaller of Q-bar-one and Q-bar-two at s-prime, a-prime, with a-prime drawn from pi given s-prime.

y
y the target: the label both online critics regress toward. No gradient flows through it.
r
r the reward of this transition: −1, or 0 at the goal.
γ
gamma the discount: 0.95 on PointMass, 0.99 on AntMaze.
d
d the done flag, 1 if s′ ends the episode. Then 1 − d is 0 and the future drops out.
min
the smaller of the two estimates, taken per transition.
Q1, Q2
Q-bar-one, Q-bar-two the target critics, read through get_target_q.
a′ ∼ π(· | s′)
a-prime drawn from pi given s-prime one action sampled by the actor at the next state, passed in as next_actions.
In plain words

Ask both target critics what a′ is worth at s′. Keep the smaller. Multiply it by γ, zero it if d is 1, and add r. That is y.

With numbers

With made-up numbers: r = −1, d = 0, γ = 0.95, Q1 = −8.2, Q2 = −7.6. The smaller is −8.2, so y = −1 + 0.95 × (−8.2) = −8.79. On the step into the goal, r = 0 and d = 1, so y = 0.

The trap: the code runs and the return stays flat. Three bugs cause it. The target reads the online critics instead of the target critics. The target keeps its gradient, so it moves while you chase it. Or a [B, 1] tensor meets a [B] reward and broadcasts to [B, B]. Print the shapes once; compute the target inside torch.no_grad().

A transition reaches the goal: r = 0, d = 1. Both target critics say −3 at s′. What is y?

Workbook

Exercise 2.1: One target by hand Derive
r = −1, d = 0, γ = 0.95, Q1(s′, a′) = −4.0, Q2(s′, a′) = −5.0. Compute y.
Show derivation
min(−4.0, −5.0) = −5.0
y = −1 + 0.95 × 1 × (−5.0) = −1 − 4.75 = −5.75
Exercise 2.2: A goal transition Derive
r = 0, d = 1, γ = 0.95, Q1 = −3.0, Q2 = −2.0. Compute y.
Show derivation
1 − d = 0, so the bootstrap term is 0
y = 0 + 0 = 0
Exercise 2.3: A batch of double-Q targets Build
Write the target for a batch. All five inputs except gamma are arrays of the same length.
Show solution
javascriptfunction doubleQTargets(r, d, q1Next, q2Next, gamma) {
  return r.map((ri, i) =>
    ri + gamma * (1 - d[i]) * Math.min(q1Next[i], q2Next[i]));
}
In the homework the same line runs on tensors, inside torch.no_grad(), and every input is shape [B].
Exercise 2.4: The target that climbs Debug
On a toy batch this target makes the critics' values rise every epoch. Click the buggy line.
def td_target(r, d, q1_next, q2_next, gamma):    q_next = np.maximum(q1_next, q2_next)    mask = 1.0 - d    return r + gamma * mask * q_next
Show explanation
Line 2 keeps the larger estimate, so the target selects the lucky critic every time. Use the minimum.

Chapter 3

The AWAC Advantage: One Sample as the Baseline

Score the logged action against one action the policy would take, and sample the critic's next action at the right state

In awac_agent.py you fill two places. estimate_advantage() returns, for each logged pair, how much better the logged action is than the policy's usual choice. In train() you sample the critic's next action a′ at s′, then call the actor update with the advantage.

The advantage is the action's value minus the state's value. The state's value under the policy is the average Q over the policy's actions. AWAC does not average. It draws one action from the policy and uses its Q. That is cheap and right on average, but each draw is noisy.

Estimate one advantage, one sample at a time

The logged action is up. Each press draws one action from the policy and adds one dot: the advantage that draw gives. Watch the dots scatter around the true value.

Illustrative Q values and policy probabilities at one PointMass-like state with the homework's five actions.

Name the parts. The logged pair is (s, a). The critic value Q is the smaller of the two online critics, from get_q. The policy's sampled action at the same state is aπ.

Say it aloud

A of s, a equals Q of s, a minus Q of s, a-pi, with a-pi drawn from pi given s.

A(s, a)
A of s, a the advantage of the logged action. Positive means better than the policy's usual choice.
Q(s, a)
Q of s, a the online critics' value of the logged action, the smaller of the two.
Q(s, aπ)
Q of s, a-pi a one-sample stand-in for the state value V(s).
aπ ∼ π(· | s)
a-pi drawn from pi given s one action sampled from the actor at the current state s, not at s′.
In plain words

Ask the critic what the logged action a is worth at s. Draw one action aπ from the policy at the same s and ask its value. Subtract the second from the first.

With numbers

With made-up numbers from the device: Q(s, up) = −6, and the draw is left with Q = −7, so A = −6 − (−7) = +1. The true average over the policy is −7.5, so the exact advantage is +1.5.

The trap: two samples, two states. The critic's a′ comes from π at s′; the baseline aπ comes from π at s. Swap them and nothing crashes, but the advantage compares values at different states. Do both under torch.no_grad(), so the actor's gradient never flows into the critic.

The device's single-sample advantages range from 0 to +4, yet their average is +1.5. Why is the average right?

Workbook

Exercises 3.1 and 3.2 use the device's state: Q(s, ·) = [−9, −8, −6, −7, −10] for stay, down, up, left, right; π(· | s) = [0.1, 0.1, 0.4, 0.2, 0.2]; the logged action is up.
Exercise 3.1: One unlucky draw Derive
The draw is aπ = right. What advantage does AWAC give the logged action?
Show derivation
A = Q(s, up) − Q(s, right) = −6 − (−10) = +4
The true advantage is +1.5. One poor draw nearly triples it.
Exercise 3.2: The exact advantage Derive
Average Q over the policy's probabilities, then compute the exact advantage of up.
Show derivation
V = 0.1(−9) + 0.1(−8) + 0.4(−6) + 0.2(−7) + 0.2(−10)
= −0.9 − 0.8 − 2.4 − 1.4 − 2.0 = −7.5
A = −6 − (−7.5) = +1.5
Exercise 3.3: Advantages for a batch Build
A tabular stand-in for the critic: Q[s][a] is the value of action a at state s. For each transition i, return Q of the logged action minus Q of the sampled policy action at the same state.
Show solution
javascriptfunction advantages(Q, states, actions, piActions) {
  return states.map((s, i) => Q[s][actions[i]] - Q[s][piActions[i]]);
}
Exercise 3.4: The baseline from the wrong state Debug
This advantage runs without error, but it compares values at two different states. Click the buggy line.
def advantage(critic, actor, obs, act, next_obs):    q_sa = critic.get_q(obs, act)    a_pi = actor(next_obs).sample()    v_s = critic.get_q(obs, a_pi)    return q_sa - v_s
Show explanation
Line 3 samples the baseline action at the next state. The baseline must come from the policy at the current state, the same state as the logged action.

Chapter 4

The AWAC Actor: Imitation, Tilted

Weight each logged action by exp(A / λ), cap the weight at 50, and see what the temperature does

In MLP_policy.py, MLPPolicyAWAC.update() leaves one line to you: the exponential weights from adv_n and self.lambda_awac. The starter then caps them at 50 and forms the loss.

Behaviour cloning raises the log-probability of every logged action equally. AWAC multiplies each one by a weight that grows with its advantage. Good logged actions get pulled up hard; poor ones barely move. The actor only ever trains on logged actions, which keeps it near the data.

Turn the temperature

Five logged actions at one state, with their advantages. The top bars are the capped weights. The bottom bars are the policy that weighted cloning fits. Drag λ.

0.10

Illustrative advantages. The cap of 50 and the default λ = 0.1 are the starter's.

Name the parts. The batch has B logged pairs. Pair i has advantage Ai and the actor gives its logged action log-probability log π(ai | si). The temperature λ sets how sharply the weight grows.

Say it aloud

L-pi equals minus one over B times the sum over i of the smaller of e to the A-i over lambda and fifty, times log pi of a-i given s-i.

Lπ
L-pi the actor loss the optimizer lowers.
(1/B) Σi
one over B times the sum over i the mean over the batch.
exp(Ai / λ)
e to the A-i over lambda the weight: always positive, above 1 when Ai > 0. λ is the temperature, 0.1 by default.
min( ·, 50 )
the smaller of it and fifty the cap that stops one weight from overflowing.
log π(ai | si)
log pi of a-i given s-i how likely the actor makes the logged action.
In plain words

For each logged pair, divide its advantage Ai by λ, take e to that power, and cap it at 50. Multiply by the log-probability. Average over the batch and flip the sign.

With numbers

With made-up numbers: A = [0.2, 0.05, −0.3], λ = 0.1, so the weights are e2 = 7.39, e0.5 = 1.65 and e−3 = 0.05. With π = [0.5, 0.3, 0.2], Lπ = −(7.39 × −0.693 + 1.65 × −1.204 + 0.05 × −1.609) / 3 = 2.40.

The trap: exp(adv_n * lambda) instead of dividing. With λ = 0.1 every weight lands near 1, so AWAC becomes plain cloning. Nothing crashes; the return stops at the data's level. Log the mean and the maximum weight; if both sit near 1, check the line.

What does AWAC become as λ grows very large?

Workbook

Exercise 4.1: One weight Derive
A = 0.15 and λ = 0.1. Compute the weight, before the cap. Two decimals.
Show derivation
A / λ = 0.15 / 0.1 = 1.5
e1.5 = 4.48
Exercise 4.2: Hit the cap Derive
A = 0.6 and λ = 0.1. What weight reaches the loss, after the cap?
Show derivation
e0.6 / 0.1 = e6 = 403.4
min(403.4, 50) = 50
With λ = 0.1, any advantage above 0.1 × ln 50 = 0.39 saturates at 50. Above that, the weights stop ranking actions.
Exercise 4.3: The weighted cloning loss Build
Write the actor loss for a batch, with the weight capped at 50.
Show solution
javascriptfunction awrLoss(logp, adv, lam) {
  let s = 0;
  for (let i = 0; i < logp.length; i++) {
    s += Math.min(Math.exp(adv[i] / lam), 50) * logp[i];
  }
  return -s / logp.length;
}
Exercise 4.4: AWAC that never beats cloning Debug
With λ = 0.1, this actor trains like plain behaviour cloning. Click the buggy line.
def actor_loss(log_prob, adv, lam):    w = np.exp(adv * lam)    w = np.minimum(w, 50.0)    return -(log_prob * w).mean()
Show explanation
Line 2 multiplies by λ. An advantage of 0.2 gives e0.02 = 1.02 instead of e2 = 7.39, so every weight is near 1.

Chapter 5

Slow Targets and the Two AWAC Runs

Read the Polyak update, put one AWAC step in order, and summarise three seeds as a mean and a spread

The starter gives you update_target_network(). You must still know what it does, because it sets how fast every target in this homework moves. Then you run P1.1 on antmaze-umaze and P1.2 on antmaze-medium-diverse, three seeds each.

A Polyak update moves each target weight a small step toward the online weight after every training step. The target becomes a slow average of the recent online network, so the label holds still while the critic chases it.

Watch a target follow its online network

The grey line is one online weight: noisy, with a jump at step 200. The yellow line is its target. Pick a rate.

Illustrative online weight. The default rate 0.005 is the starter's awac_tau and iql_tau.

Name the parts. A target weight is θ, its online weight is θ, and the rate is ρ. The code calls ρ self.tau.

Say it aloud

theta-bar becomes one minus rho times theta-bar, plus rho times theta.

θ ←
theta-bar becomes the target weight, overwritten in place each step.
ρ
rho the Polyak rate, 0.005. The code's name is self.tau.
θ
theta-bar the old target weight, which keeps 1 − ρ of its value.
θ
theta the online weight the optimizer just changed.
In plain words

Keep 99.5 percent of the target weight θ and add 0.5 percent of the online weight θ. Do this for every weight of both target critics, once per step.

With numbers

With made-up numbers: θ = 1.00, θ = 3.00, ρ = 0.005. The new target is 0.995 × 1.00 + 0.005 × 3.00 = 1.01. The gap halves every ln 0.5 / ln 0.995 = 138 steps.

One AWAC step runs in this order: sample a batch, sample a′ at s′, update the critics, estimate the advantages, update the actor, then Polyak-update the targets.

The trap in the summary: take one number per seed, the Eval_AverageReturn at the final checkpoint, then the mean and standard deviation across the three. A spread within one run is the wrong number. NumPy's np.std divides by n, not n − 1, so state which you used.

What happens at ρ = 1?

Workbook

Exercise 5.1: One Polyak step Derive
θ = 0.4, θ = 1.4, ρ = 0.005. Compute the new target weight. Three decimals.
Show derivation
0.995 × 0.4 + 0.005 × 1.4 = 0.398 + 0.007 = 0.405
Exercise 5.2: A Polyak update for a weight vector Build
Return the new target weights. Do not change the input arrays.
Show solution
javascriptfunction polyak(target, online, rho) {
  return target.map((t, i) => (1 - rho) * t + rho * online[i]);
}
Swap ρ and 1 − ρ and the target keeps only 0.5 percent of itself: it becomes the online network.
Exercise 5.3: Order one AWAC step Design
Tap the chips in the order AWACAgent.train() runs them, after the batch is sampled.
?
→
?
→
?
→
?
→
?
estimate advantages at s Polyak-update the targets sample a′ at s′ weighted actor update critic update with y
Exercise 5.4: Summarise three seeds Derive
Made-up final returns of three seeds: −18, −24, −27. Compute the standard deviation with np.std (divide by n). Three decimals.
Show derivation
mean = (−18 − 24 − 27) / 3 = −23
squared gaps: 25, 1, 16; their mean = 42 / 3 = 14
std = √14 = 3.742
Divide by n − 1 instead and you get √21 = 4.583. Say which one your table uses.

Chapter 6

The IQL Value: An Upper Expectile

Fit V(s) with a lopsided squared loss so it lands on the good logged actions, not their mean

In iql_critic.py you fill three places. In __init__ you build self.v_net from v_network_initializer(self.ob_dim) and move it to the device. expectile_loss(diff) returns the per-sample loss. update_v() averages it over the batch.

IQL wants V(s) to mean the value of the good logged actions at s. Plain squared error gives their mean, which the poor actions drag down. The maximum would ask about actions the data never tried. The expectile sits between: a squared loss that charges more when V is below a value than above it.

Slide the fit from the mean toward the top

Dots are Q of five logged actions at one state. The blue line is the V that minimizes the expectile loss. Drag ζ.

0.90

Illustrative values −2, 0, 1, 3, 8. The page solves for V exactly at each ζ.

Name the parts. The residual u is the target critic's value of the logged action minus the current V(s). The indicator 1[u < 0] is 1 when u is negative and 0 otherwise. The expectile level is ζ.

Say it aloud

L-zeta of u equals the absolute value of zeta minus the indicator of u below zero, times u squared, where u is Q-bar of s, a minus V of s.

Lζ(u)
L-zeta of u the loss of one sample; update_v takes its mean over the batch.
ζ
zeta the expectile level, between 0 and 1: iql_expectile, 0.9 by default.
1[u < 0]
the indicator of u below zero 1 if V is above the target, else 0.
u2
u squared the ordinary squared error.
u = Q(s, a) − V(s)
u equals Q-bar of s, a minus V of s the min of the two target critics at the logged action, minus the value network's output.
In plain words

Square the residual u. If u is positive, V is too low: multiply by ζ. If u is negative, V is too high: multiply by 1 − ζ. With ζ = 0.9, being too low costs nine times more, so V rises.

With numbers

With made-up numbers from the device, V = 2 and ζ = 0.9. The value 8 gives u = 6 and loss 0.9 × 36 = 32.4. The value −2 gives u = −4 and loss 0.1 × 16 = 1.6. The minimum moves V up to 5.69; the plain mean is 2.

The trap: writing the indicator as u > 0. Then the weights swap, and V fits the lower expectile at level 1 − ζ. With ζ = 0.9 the device's V drops to −0.46. Test your loss on one positive and one negative residual before a run.

At ζ = 0.5, what does V fit?

Workbook

Exercise 6.1: One sample's loss Derive
ζ = 0.9, Q(s, a) = −7, V(s) = −4. Compute Lζ(u).
Show derivation
u = −7 − (−4) = −3, so 1[u < 0] = 1
|0.9 − 1| × 9 = 0.1 × 9 = 0.9
Exercise 6.2: Expectile of two values Derive
Two logged actions have Q = 0 and Q = 10. Find the 0.9 expectile. At the minimum, the weighted pulls from both sides balance: ζ(10 − m) = (1 − ζ)(m − 0).
Show derivation
0.9(10 − m) = 0.1 m
9 − 0.9m = 0.1m, so m = 9
The mean is 5. The 0.9 expectile sits close to the good action, still inside the logged range.
Exercise 6.3: The expectile loss Build
Return the mean expectile loss over an array of residuals u = Q − V.
Show solution
javascriptfunction expectileLoss(diffs, zeta) {
  let s = 0;
  for (const u of diffs) s += Math.abs(zeta - (u < 0 ? 1 : 0)) * u * u;
  return s / diffs.length;
}
Exercise 6.4: Fit an expectile Build
Find the scalar m that minimizes the mean expectile loss of values − m.
  1. Start at the mean.
  2. Give each value weight ζ if it is at or above m, else 1 − ζ.
  3. Set m to the weighted mean of the values. Repeat 200 times.
Show solution
javascriptfunction fitExpectile(values, zeta) {
  let m = values.reduce((a, v) => a + v, 0) / values.length;
  for (let k = 0; k < 200; k++) {
    let sw = 0, swx = 0;
    for (const v of values) { const w = v >= m ? zeta : 1 - zeta; sw += w; swx += w * v; }
    m = swx / sw;
  }
  return m;
}
The value network does the same job by gradient steps on the loss, one state at a time, across the whole dataset.
Exercise 6.5: The value that fits too low Debug
With ζ = 0.9 this loss pulls V below the mean. Click the buggy line.
def expectile_loss(diff, zeta):    weight = np.abs(zeta - (diff > 0))    return weight * diff ** 2
Show explanation
Line 2 flags positive residuals. A positive u then gets weight 1 − ζ = 0.1, so V is cheap to leave too low. The indicator must flag u < 0.

Chapter 7

The IQL Q Target and the Policy

Bootstrap on V(s′) so no sampled action enters the backup, then extract the policy with the AWAC loss

Three places are left. update_q() in iql_critic.py builds the target from v_net(next_ob_no) and trains both critics. In iql_agent.py, estimate_advantage() subtracts V from Q, and train() calls the AWAC actor update with that advantage.

AWAC's target needs an action at s′, sampled from the actor. If the actor drifts off the data, the target asks about unlogged actions. IQL's target asks V(s′) instead. V depends on the state alone, and it learned only from logged actions.

Run IQL sweeps on the hero's log

Each sweep fits V by the expectile, then sets every Q from r + γV(s′). Step and watch value flow back from the goal through the junction. Compare ζ.

Tabular IQL on the hero's 32 toy transitions, γ = 0.95. A table stands in for each network; each sweep solves the fits exactly.

Name the parts. Reward r, discount γ and done flag d are as before. V(s′) is the value network at the next state.

Say it aloud

y equals r plus gamma times one minus d, times V of s-prime.

y
y the target for both online critics, computed with no gradient.
r
r the reward of the logged transition.
γ
gamma the discount.
d
d the done flag; 1 − d removes the future at the goal.
V(s′)
V of s-prime the value network at the next state, squeezed from [B, 1] to [B].
In plain words

Read V at the next state s′. Multiply by γ, zero it if d is 1, and add r. Nothing samples an action.

With numbers

With made-up numbers: r = −1, d = 0, γ = 0.95, V(s′) = −6. Then y = −1 + 0.95 × (−6) = −6.7.

The policy uses the AWAC loss of Chapter 4. Only the baseline changes: a learned V(s), not one sampled action.

Say it aloud

A of s, a equals Q of s, a minus V of s.

A(s, a)
A of s, a the advantage that goes into exp(A / λ).
Q(s, a)
Q of s, a the smaller online critic at the logged action, q_sa in the starter.
V(s)
V of s the expectile value at the same state, v_pi in the starter.
In plain words

Subtract the state's expectile value V(s) from the logged action's Q(s, a). Positive means the action beats the good-action level at s.

With numbers

From the device at ζ = 0.9: at the junction, Q(up) = −3.71 and V = −6.67, so A(up) = +2.96 and its weight hits the cap of 50. Q(right) = −20.0 gives A = −13.3 and a weight near 0.

The trap: v_net returns [B, 1]. Without .squeeze(-1), adding it to a [B] reward broadcasts to a [B, B] target, and the MSE still returns a number. Assert target.shape == q1.shape. A second trap: copying AWAC's a′ sampling into IQL.

In the device, why does V(junction) rise from −14.6 to −6.7 when ζ goes from 0.5 to 0.9?

Workbook

Exercise 7.1: One IQL target Derive
r = −1, d = 0, γ = 0.95, V(s′) = −10. Compute y.
Show derivation
y = −1 + 0.95 × 1 × (−10) = −1 − 9.5 = −10.5
Exercise 7.2: A batch of IQL targets Build
Write the target for a batch. vNext holds V(s′) for each transition.
Show solution
javascriptfunction iqlTargets(r, d, vNext, gamma) {
  return r.map((ri, i) => ri + gamma * (1 - d[i]) * vNext[i]);
}
Exercise 7.3: The silent broadcast Debug
In NumPy, v_net(next_obs) returns shape (B, 1). The loss below is a number, but it is wrong. Click the buggy line.
def iql_q_loss(q1, r, d, next_obs, v_net, gamma):    v_next = v_net(next_obs)    target = r + gamma * (1.0 - d) * v_next    return ((q1 - target) ** 2).mean()
Show explanation
Line 2 keeps the trailing dimension. A (B,) reward plus a (B, 1) value broadcasts to (B, B), so every Q is compared with every target. Take v_net(next_obs)[:, 0]; in PyTorch, .squeeze(-1).
Exercise 7.4: Order one IQL step Design
Tap the chips in the order IQLAgent.train() runs them.
?
→
?
→
?
→
?
→
?
Q update on r + γV(s′) V update by the expectile Polyak-update the target critics advantage Q − V weighted actor update

Chapter 8

The ζ Sweep and the Hard Maze

Reason about what a low ζ does to the weights, and why a long horizon punishes sampled next actions

P2.1 runs IQL on umaze with ζ = 0.2 and ζ = 0.9 and asks which wins and why, in two or three sentences. P2.2 runs the better ζ on medium-diverse, then a table of AWAC and IQL on both mazes, and three sentences on the harder task.

Start with ζ = 0.2. V then sits near the low end of the logged values, so most logged actions get a positive advantage. With λ = 0.1, any advantage above 0.1 × ln 50 = 0.39 hits the cap. Many actions then share the weight 50, and the actor drifts back toward cloning everything. Check this with the weight logs, not by guessing.

Now the horizon. Suppose each AWAC backup adds a small error ε from a slightly unlogged a′. Each backup copies the next state's error, shrinks it by γ, and adds a fresh ε. Over a long maze these errors stack.

Stack a small backup error over a long maze

The red curve is the error a value inherits after H backups that each add ε. The green line is a backup that adds none. Drag the horizon and the error.

50
0.50

Illustrative model with γ = 0.99, the AntMaze discount. It shows one error source, not a measured result for either method.

Worked number: with ε = 0.5 and γ = 0.99, ten backups stack to 4.78. Fifty backups stack to 19.75, a fifth of the whole Q range from −100 to 0. IQL's target has no sampled a′, so this source is absent. That is the mechanism to test on medium-diverse, not a promised win.

The trap: quoting the best checkpoint, or choosing ζ on the medium maze. Both flatter the method with a choice made on the test. Use the final checkpoint of each seed, and the ζ that won on umaze.

Which sentence fits a P2.2 explanation, if IQL does beat AWAC on medium-diverse?

Workbook

Exercise 8.1: Where the weights saturate Derive
With λ = 0.1 and the cap 50, above which advantage does every weight equal 50? Three decimals.
Show derivation
exp(A / 0.1) = 50
A = 0.1 × ln 50 = 0.1 × 3.912 = 0.391
Exercise 8.2: Stack the error Derive
ε = 0.2 per backup, γ = 0.99, H = 20 backups. Add ε, γε, γ²ε, and so on for 20 terms. Three decimals.
Show derivation
sum = ε (1 − γH) / (1 − γ)
0.9920 = 0.8179
0.2 × (1 − 0.8179) / 0.01 = 0.2 × 18.21 = 3.642
Exercise 8.3: Read a low ζ Trace
With ζ = 0.2, the logged advantages at most states are large and positive. What do the actor weights look like?
Exercise 8.4: Mean and spread for the table Build
Return [mean, std] of an array of final returns, with the standard deviation that divides by n.
Show solution
javascriptfunction meanStd(xs) {
  const n = xs.length, m = xs.reduce((a, x) => a + x, 0) / n;
  const v = xs.reduce((a, x) => a + (x - m) * (x - m), 0) / n;
  return [m, Math.sqrt(v)];
}

Chapter 9

Stitching on PointMass

See what filtered BC keeps from the real dataset, and what a return above −46 can and cannot prove

P2.3 trains IQL, with your better ζ, and filtered BC on pointmass_stitching_dataset.npz. You compare the mean and standard deviation, across three seeds, of the average and the maximum return. Then draw one trajectory figure per method and check whether IQL beat −46.

Stitching is composing pieces of different trajectories into a better path than any one of them. Filtered BC keeps only the top 10 percent of trajectories by return, then clones them. It copies good trips, but it has no values to prefer one logged turn over another at a shared state.

Cut the real dataset the way filtered BC does

Each bar is one of the 79 trajectories, sorted by return. Drag the cut and read what filtered BC would train on.

10%

Real returns and lengths, computed from the starter's dataset file. The cut rounds up, as the starter's filter does.

Worked number: 10 percent of 79 is 7.9, rounded up to 8 trajectories. Their returns run from −46 to −53, 407 transitions in all. The file holds 8,184 transitions; its mean return is −103.0, where the handout says about −104.

In the hero, IQL's path takes 10 transitions and returns −9. Neither logged trip gets there: A stalls, B starts elsewhere. That picture is what your trajectory figure must show on PointMass: a route made of logged pieces that no single trajectory contains.

The trap: a number alone. A return above −46 is evidence consistent with stitching. Compare methods with the same seeds and checkpoint, then point to the junction in the figure where the route changes trips.

What lets IQL take trip B's turn at the junction?

Workbook

Exercise 9.1: The hero's stitched return Derive
The stitched path takes 5 moves to the junction and 5 more to the goal. The last move reaches the goal. What is its return?
Show derivation
10 transitions, 9 of them cost −1, the goal step gives 0
return = −9
Exercise 9.2: Keep the top trajectories Build
Return the indices of the trajectories filtered BC keeps, in their original order.
  1. Keep n = ceil(count × pct / 100) trajectories, and at least 1.
  2. Rank by return, highest first. On a tie, the earlier index ranks first.
  3. Return the kept indices sorted ascending.
Show solution
javascriptfunction topTrajectories(returns, pct) {
  const n = Math.max(1, Math.ceil(returns.length * pct / 100));
  const order = returns.map((r, i) => i).sort((a, b) => returns[b] - returns[a] || a - b);
  return order.slice(0, n).sort((a, b) => a - b);
}
The starter's filter is already written. This exercise rebuilds the same cut on toy returns, with its own tie rule.
Exercise 9.3: Read the P2.3 table Trace
Made-up results: IQL averages −40 over three seeds, filtered BC −55. What can you claim?
Exercise 9.4: The filter that keeps one too few Debug
On the 79-trajectory dataset this keeps 7 trajectories, not 8. Click the buggy line.
def filter_top(returns, top_percent):    n = len(returns)    n_keep = int(n * top_percent / 100.0)    order = np.argsort(returns)[::-1]    return sorted(order[:n_keep])
Show explanation
Line 3 rounds 7.9 down to 7. The starter uses max(1, int(np.ceil(...))), which gives 8.

Chapter 10

The Field Guide

Match a symptom to its cause, tick the run checklist, and keep the contracts on one card

AWAC and IQL share a critic shape and an actor loss. They differ in one place: what the Q target reads at the next state. AWAC samples an action from its actor; IQL reads a value learned from logged actions by an upper expectile.

Symptom, cause, fix

SymptomLikely causeFix
Q above 0, or below −1 / (1 − γ)max instead of min, missing 1 − d, online nets in the targetread get_target_q under no_grad; check the mask
Critic loss explodesgradient through the target, or a [B, B] broadcastdetach the target; assert shapes are [B]
Return stuck at the data's levelweights near 1 (adv * lambda), or most weights cappedlog the mean and max weight
IQL V below the mean of Qindicator written as u > 0test the loss on u = +1 and u = −1
AttributeError: v_netvalue network not defined before v_optimizerbuild it from v_network_initializer(self.ob_dim), move it to the device
Advantage noisy in AWAC onlythe one-sample baselineexpected; IQL's learned V removes this noise source

Terms and numbers

TermMeaning hereValue
γdiscount0.95 PointMass, 0.99 AntMaze
λactor temperature, awac_lambda0.1, weight cap 50
ζexpectile level, iql_expectilesweep 0.2 and 0.9
ρPolyak rate, self.tau0.005
Stitching dataset79 trajectories, 8,184 transitionsbest −46, mean −103.0
Filtered BCclone the top 10 percent8 trajectories, 407 transitions

The contracts on one card

contracts# every tensor below is shape [B]; targets carry no gradient
AWAC target    y = r + γ(1 − d) · min(Q1, Q2)(s′, a′),   a′ ~ π(·|s′)
AWAC advantage A = Q(s, a) − Q(s, aπ),               aπ ~ π(·|s)
actor loss     L = −mean( min(exp(A / λ), 50) · log π(a|s) )
IQL value      L_V = mean( |ζ − 1[u < 0]| · u² ),       u = Q(s, a) − V(s)
IQL target     y = r + γ(1 − d) · V(s′)
IQL advantage  A = Q(s, a) − V(s)
Polyak         θ ← (1 − ρ) θ + ρ θ

Run checklist

Keep going

TopicLesson
Offline RL from zeroOffline RL
Bellman targets and QQ-Learning
Two critics and target networksOff-Policy Actor-Critic
The homework before this oneCS 224R HW2: Online RL
The one idea. A value that depends on the state, not the trip, lets a policy join logged pieces. Offline, the danger is asking that value about actions the data never tried.

Open the Studio pill to write the seven NumPy kernels in the Forge Studio. Then use Teach to explain the junction from a blank page, and go back to the hero and play both methods once more. Credit: Stanford CS 224R, Spring 2026, Homework 3; the handout and starter code are the course's.

AWAC and IQL use the same actor loss. Where do they differ?
CS 224R HW3: Offline RL, AWAC and IQL
Based on Stanford CS 224R (Spring 2026), Homework 3 · Course site · Back to Gleams