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.
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.
Chapter 0
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.
| Part | Task | Chapter |
|---|---|---|
| P1.1 | AWAC on antmaze-umaze, 3 seeds, about 1 hour | 2 to 5 |
| P1.2 | AWAC on antmaze-medium-diverse, about 1.5 hours | 5 |
| P2.1 | IQL with ζ = 0.2 and 0.9 on umaze; say which wins and why | 6, 7, 8 |
| P2.2 | IQL on medium-diverse with the better ζ; compare with AWAC | 8 |
| P2.3 | IQL against filtered BC on the stitching dataset | 9 |
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.
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.
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.
Chapter 1
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.
| Domain | State | Action | Settings in the starter |
|---|---|---|---|
| PointMass | x and y position, normalized | 5 choices: stay, down, up, left, right, with noise | γ = 0.95, 50,000 steps |
| AntMaze | the ant's body and position | continuous 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.
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.
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.
dones[i] is 1, push the sum and start a new one.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;
}
Chapter 2
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.
Each tick is one state: the estimate minus the true value. Pick a rule and read the average error. Then raise the noise.
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.
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.
get_target_q.next_actions.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 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().
gamma are arrays of the same length.javascriptfunction doubleQTargets(r, d, q1Next, q2Next, gamma) {
return r.map((ri, i) =>
ri + gamma * (1 - d[i]) * Math.min(q1Next[i], q2Next[i]));
}
torch.no_grad(), and every input is shape [B].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
Chapter 3
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.
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π.
A of s, a equals Q of s, a minus Q of s, a-pi, with a-pi drawn from pi given s.
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 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.
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.javascriptfunction advantages(Q, states, actions, piActions) {
return states.map((s, i) => Q[s][actions[i]] - Q[s][piActions[i]]);
}
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
Chapter 4
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.
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 λ.
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.
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.
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 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.
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;
}
def actor_loss(log_prob, adv, lam): w = np.exp(adv * lam) w = np.minimum(w, 50.0) return -(log_prob * w).mean()
Chapter 5
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.
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.
theta-bar becomes one minus rho times theta-bar, plus rho times theta.
self.tau.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 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.
javascriptfunction polyak(target, online, rho) {
return target.map((t, i) => (1 - rho) * t + rho * online[i]);
}
AWACAgent.train() runs them, after the batch is sampled.np.std (divide by n). Three decimals.Chapter 6
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.
Dots are Q of five logged actions at one state. The blue line is the V that minimizes the expectile loss. Drag ζ.
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 ζ.
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.
update_v takes its mean over the batch.iql_expectile, 0.9 by default.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 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.
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;
}
values − m.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;
}
def expectile_loss(diff, zeta): weight = np.abs(zeta - (diff > 0)) return weight * diff ** 2
Chapter 7
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.
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.
y equals r plus gamma times one minus d, times V of s-prime.
[B, 1] to [B].Read V at the next state s′. Multiply by γ, zero it if d is 1, and add r. Nothing samples an action.
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.
A of s, a equals Q of s, a minus V of s.
q_sa in the starter.v_pi in the starter.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.
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.
vNext holds V(s′) for each transition.javascriptfunction iqlTargets(r, d, vNext, gamma) {
return r.map((ri, i) => ri + gamma * (1 - d[i]) * vNext[i]);
}
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()
(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).IQLAgent.train() runs them.Chapter 8
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.
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.
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.
[mean, std] of an array of final returns, with the standard deviation that divides by n.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
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.
Each bar is one of the 79 trajectories, sorted by return. Drag the cut and read what filtered BC would train on.
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.
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);
}
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])
max(1, int(np.ceil(...))), which gives 8.Chapter 10
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 | Likely cause | Fix |
|---|---|---|
| Q above 0, or below −1 / (1 − γ) | max instead of min, missing 1 − d, online nets in the target | read get_target_q under no_grad; check the mask |
| Critic loss explodes | gradient through the target, or a [B, B] broadcast | detach the target; assert shapes are [B] |
| Return stuck at the data's level | weights near 1 (adv * lambda), or most weights capped | log the mean and max weight |
| IQL V below the mean of Q | indicator written as u > 0 | test the loss on u = +1 and u = −1 |
AttributeError: v_net | value network not defined before v_optimizer | build it from v_network_initializer(self.ob_dim), move it to the device |
| Advantage noisy in AWAC only | the one-sample baseline | expected; IQL's learned V removes this noise source |
| Term | Meaning here | Value |
|---|---|---|
| γ | discount | 0.95 PointMass, 0.99 AntMaze |
| λ | actor temperature, awac_lambda | 0.1, weight cap 50 |
| ζ | expectile level, iql_expectile | sweep 0.2 and 0.9 |
| ρ | Polyak rate, self.tau | 0.005 |
| Stitching dataset | 79 trajectories, 8,184 transitions | best −46, mean −103.0 |
| Filtered BC | clone the top 10 percent | 8 trajectories, 407 transitions |
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 − ρ) θ + ρ θ
TODO in the five files; the shapes print as [B].Eval_AverageReturn.| Topic | Lesson |
|---|---|
| Offline RL from zero | Offline RL |
| Bellman targets and Q | Q-Learning |
| Two critics and target networks | Off-Policy Actor-Critic |
| The homework before this one | CS 224R HW2: Online RL |
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.