A robot's log holds two routes around a wall. A Gaussian actor told to copy the log aims between them, at the wall. A flow policy copies one route for each noise sample. On our toy it reaches the goal in 90% of runs or more for every BC weight above 4.3.
A lesson with a workbook. Each chapter explains one part of Homework 5, then gives you exercises on our own toy log.
Pick an agent. Drag α, the weight on staying near the log. Blue rays reach the goal; red rays hit a wall. Then we build SAC+BC, IQL and FQL piece by piece.
You need the offline RL basics from Offline RL and the IQL code from CS224R HW3. The exercises run JavaScript in your browser.
Based on Homework 5 of UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine (Spring 2026): the handout (PDF), the starter code and Lecture 18 (PDF). The words, toys and numbers here are our own.
Illustrative toy: one state, a 1-D heading and our own log, 35% upper route and 65% lower. Our critic has a false peak at 0.97, where the log has no actions. Gaussians act with spread 0.08. Chapter 0 lists every number.
Chapter 0
Meet the toy log, the three agents, and the part each one adds
A robot drove from a start to a goal many times. A wall stands in the middle. Some runs passed above the wall in about 8 steps. Most passed below it in about 14. You get the log of those runs and nothing else. Offline RL learns the best policy it can from a fixed log, with no new runs.
Homework 5 builds three agents for the same log. SAC+BC and IQL train a Gaussian actor. FQL trains a flow policy that can hold both routes. The site already covers the basics. This page leads with what is new: how to pick the BC weight α, why a Gaussian fails on two routes, and the BPTT problem that FQL removes.
| Already taught | Where | What this page adds |
|---|---|---|
| Constraints, CQL, IQL in theory | Offline RL | SAC+BC's loss and the α sweep (Ch 1, 2) |
| The IQL expectile and weights, in code | CS224R HW3, Ch 6 and 7 | HW5's sign convention, the two knobs on one toy (Ch 3, 4) |
| Flow actors, IDQL, FQL in one chapter | Offline-to-Online RL, Ch 5 | Flow BC, BPTT, the full FQL recipe (Ch 5, 6) |
Each box is a network you train. Arrows carry actions. Choose an agent and see which actions its critic scores.
The networks and loss terms follow the handout. The file names are the starter code's: sacbc_agent.py, iql_agent.py, fql_agent.py in src/agents/.
Every number on this page comes from one toy state, the fork in front of the wall. The action a is the heading at the fork.
What does copying the log do? The mean of the logged actions is 0.35 × 0.6 + 0.65 × (−0.6) = −0.18. That heading drives into the wall. Any actor that pulls toward the log's mean inherits this crash.
Chapter 1
Add one copying term to SAC's actor, and change two things in its critic target
Part 1 fills the TODOs in src/agents/sacbc_agent.py. SAC+BC is SAC from Homework 3 with a BC term: a penalty on the distance between the actor's action and the logged action. The starter code tunes the entropy weight for you.
The critic changes in two ways. The target averages the two target critics instead of taking the smaller one. It also drops SAC's entropy bonus. The handout reports that both work better offline.
y equals r plus gamma times one minus d, times half of Q-bar-one plus Q-bar-two at s-prime and a-prime.
Ask both target critics about the next state and the actor's next action. Average them, discount by gamma, and add the reward r. On the last step use r alone.
With made-up numbers: r = −1, d = 0, the targets say −4 and −6. y = −1 + 0.9 × (−5) = −5.5. The minimum would give −6.4.
With rewards of −1 or 0, every Q-value lies between −1/(1 − γ) and 0. That is −10 on our toy and −100 at the course's γ of 0.99. Log the batch's smallest and largest Q, q_min and q_max, and check both stay inside.
Twelve logged steps lead to the goal. Each bar is Q at one step; the dashed lines are the bounds 0 and −10. Run the backups, then switch off the done mask.
Illustrative. No logged step starts at the goal, so its value stays at an untrained guess of +4. "min" uses two critics with noise 0.6; that lowers each target by 0.34 on average.
The actor loss has three terms. Call the actor's sampled action aπ, the logged action a, and the number of action numbers |A|.
L of pi equals minus Q-hat of s and a-pi, plus alpha times one over the size of A times the squared distance from a to a-pi, plus beta times log pi of a-pi given s.
Sample an action a-pi from the actor. Score it with the critics. Pay alpha for each unit of squared distance from the logged action a. The actor moves to where the score minus the payment is best.
On the toy at α = 1, ignoring β, the best mean action is 0.547: loss 6.60. The false peak, 0.965, costs 6.84, and the log's mean, −0.18, costs 9.09.
q_max settles above 0, at 3.6 in the device, which no −1/0 reward can produce.q_max during training. It must approach 0 from below.q_min = −140 with γ = 0.99 and −1/0 rewards. What does it tell you?javascriptfunction bellmanTarget(r, d, q1n, q2n, gamma) {
return r.map((ri, i) => ri + gamma * (1 - d[i]) * 0.5 * (q1n[i] + q2n[i]));
}
numpyy = r + gamma * (1 - d) * 0.5 * (q1n + q2n)
q_max = +2.8, q_min = −97, and the action MSE falls as α rises. Which line is most likely wrong?Chapter 2
Sweep the BC weight, and find where the actor stops copying and starts improving
The handout calls α the most important knob of SAC+BC, and of behaviour-regularized methods in general. Too small, and the actor climbs the critic's errors. Too large, and it only copies the log. You find the middle by a sweep.
One read-out makes a sweep fast: the action MSE, the mean squared gap between the logged actions and the actor's actions. It falls as α rises, down to a floor: the MSE of pure BC. The handout's rule of thumb is to pick the α whose MSE sits only slightly above that floor.
Why is there a floor? Call the actor's mean action μ and the log's mean action &abar;. The spread of the log, VarD, stays whatever the actor does.
MSE equals mu minus a-bar, squared, plus the variance of the log.
Split each logged action's gap into two parts: the actor's distance from the log's mean, and the action's distance from that mean. Only the first part depends on the actor, so BC drives it to zero and leaves Var-D.
On our two-route log, &abar; = −0.18 and VarD = 0.338. At α = 1 the actor sits at μ = 0.547: MSE = 0.727² + 0.338 = 0.866, more than twice the floor.
Green is the share of runs that reach the goal. Yellow is the action MSE; the dashed line is its BC floor. Drag α, then switch the log.
SAC+BC on the toy fork. The one-route log heads 0.5 with spread 0.1. The device solves the actor loss exactly at each α; illustrative numbers.
On the one-route log, the rule works. From α = 3 up, nearly every run arrives, and at α = 10 the MSE is 0.0131 against a floor of 0.0098. On the two-route log, the floor is the log's mean, the wall. The rule then points at a crash. That failure is the reason for Chapters 5 and 6.
def bc_term(a_data, a_pi, alpha): # both [B, A] diff = a_data - a_pi per_sample = (diff ** 2).sum(axis=1) return alpha * per_sample.mean()
.mean(axis=1).Chapter 3
Fit V high over the logged actions, so Q never needs an action the log lacks
Part 2 fills src/agents/iql_agent.py. CS224R HW3, Chapter 6 builds the expectile loss in code. HW5 differs in four ways. It has two Q-functions, puts the smaller target critic inside the V loss, fixes τ at 0.9, and writes the residual the other way round.
The Q-functions regress onto the reward plus γ times V of the next state, with the done mask. No action from the actor appears. The value V is fit with a lopsided squared loss on the logged actions only.
ell-tau of x equals the absolute value of tau minus the indicator of x above zero, times x squared, where x is V of s minus the smaller target Q at the logged action.
Square the gap x. If V sits below Q, weigh it by tau; if above, by 1 minus tau. With tau 0.9, sitting too low costs nine times more, so V rises toward the best logged actions.
τ = 0.9, V = −7, Q = −5.7: x = −1.3, loss 0.9 × 1.69 = 1.52. With Q = −7.7: x = 0.7, loss 0.1 × 0.49 = 0.049.
Take the toy from Lecture 18: one state, two logged actions, returns −10 and +10, equally often. At the minimum, the two weighted pulls balance: τ(10 − V) = (1 − τ)(V + 10). Solve for V.
V equals ten times two tau minus one.
At tau 0.5, V is the mean, 0. As tau grows, V moves up toward the better return, +10, and reaches it only at tau 1.
τ = 0.9: V = 10 × 0.8 = 8. τ = 0.7: V = 4. V = 9.7 needs 2τ − 1 = 0.97, so τ = 0.985.
Dots are the Q-values of logged actions; bigger dots are more common. The curve is V's loss; its lowest point is V. Drag τ, then switch to the fork's log.
The device solves for V exactly. Lecture 18 marks V = 9.7 on the two-return toy; that value needs τ = 0.985, not 0.9. The fork's values are our critic's.
On the fork, τ = 0.9 gives V = −6.15, between the lower route's −7.71 and the upper route's −5.70. A Q target is then r + γV(s′): with r = −1, that is −1 + 0.9 × (−6.15) = −6.54.
javascriptfunction twoPointExpectile(qa, pa, qb, tau) {
const hiFirst = qa >= qb;
const hi = hiFirst ? qa : qb, lo = hiFirst ? qb : qa;
const ph = hiFirst ? pa : 1 - pa, pl = 1 - ph;
return (tau * ph * hi + (1 - tau) * pl * lo) / (tau * ph + (1 - tau) * pl);
}
def expectile(x, tau): # x = V(s) - Q(s, a) over = (x > 0).astype(float) w = np.abs(tau - (1 - over)) return (w * x ** 2).mean()
np.abs(tau - over).Chapter 4
Copy each logged action in proportion to how much better it is than V
The IQL actor never asks the critic about its own actions. It copies logged actions, weighted by their advantage A = mini Qi(s, a) − V(s). A says how much better a logged action is than the state's value.
L of pi equals minus the smaller of e to the alpha A and M, times log pi of a given s.
For each logged action, compute its advantage A. Turn it into a weight, e to the alpha A, capped at M. Copy the action that much. For a Gaussian, the best mean is the weighted mean of the logged actions.
On the fork with τ = 0.9, the upper route has A = 0.46 and the lower A = −1.56. At α = 3 their weights are 3.93 and 0.0093. The fit lands at 0.595, on the upper route.
Teal bars are the logged actions. Warm bars are the same actions after weighting. The blue line is the Gaussian's mean. Drag α and τ.
Toy fork, our critic, M = 100 as in the handout. Gaussians act with spread 0.08. Illustrative.
The two knobs span four corners. The handout fixes τ at 0.9 and tunes α over 1, 3 and 10.
| Corner | What V means | What the actor does |
|---|---|---|
| τ 0.5, α 0 | the log's own value (SARSA) | plain BC: −0.18, the wall |
| τ 0.5, α large | the log's own value | the best action under the log's values |
| τ → 1, α 0 | the best logged action | still plain BC |
| τ → 1, α → ∞ | the best logged action | greedy among logged actions |
The weights can only move the fit between logged actions. IQL never reaches the false peak at 0.97, so on our toy it is safe for every α above 1.2. Its limit is the mirror image: it cannot leave the log to find a better action.
javascriptfunction awrMean(actions, advs, alpha, M) {
let sw = 0, swa = 0;
actions.forEach((a, i) => { const w = Math.min(Math.exp(alpha * advs[i]), M); sw += w; swa += w * a; });
return swa / sw;
}
numpyw = np.minimum(np.exp(alpha * adv), M)
mu = (w * actions).sum() / w.sum()
Chapter 5
Hold both routes with a flow, then see why climbing the critic through it is hard
A Gaussian has one peak. Our log has two. Any BC pull on a Gaussian aims at the log's mean, the wall. A flow policy fixes this: it turns a noise sample z into an action through many small steps, and different z can land on different routes.
Call the velocity network v. It takes the state s, the current action ak and the time t = k/F. Starting from a0 = z, take F Euler steps.
a-k-plus-one equals a-k plus one over F times v of s, a-k and k over F.
Start at the noise z. Ask v which way to move. Take a step of size one over F. Repeat F times. Where you stop is the action.
With a perfect v, the first velocity is v = &abar; − z. At F = 1, every z lands on &abar; = −0.18, the wall. At F = 10, 35% of z land on the upper route.
Flow matching trains v by plain regression. Mix a noise z and a logged action a at a random time t. The target velocity is the straight line from z to a.
L of v equals one over the size of A times the squared distance from v of s, a-tilde, t to a minus z, where a-tilde is one minus t times z plus t times a.
Pick a logged action a, a noise z and a time t. Go a fraction t of the way from z to a. Teach v to point along a minus z there.
z = 0.3, a = 0.6, t = 0.5: a-tilde = 0.45 and the target velocity is 0.3. If v says 0.2, the loss is 0.01.
FBRAC, the first try in the handout, adds −Q̂(s, πv(s, z)) to the flow's loss. The gradient of that term must pass back through all F Euler steps, and through every layer in each. That is backpropagation through time (BPTT): a product of about F × (layers) Jacobians.
Top: the action each noise z reaches. Bottom: how much the Euler chain multiplies a gradient, da/dz, on a log scale. Drag F.
The exact flow-matching velocity for our log, run with Euler steps. A trained network only approximates it. Illustrative.
The map is steep where it splits the noise between the routes. There, the chain of Jacobians multiplies a gradient by 30 at F = 10 and by about 6,200 at F = 50. For three noise samples in four it shrinks a gradient below 0.2. BPTT gradients are both huge and tiny, and they cost F passes of memory.
javascriptfunction eulerFlow(z, F, vel) {
let x = z; const h = 1 / F;
for (let k = 0; k < F; k++) x += h * vel(x, k * h);
return x;
}
Chapter 6
Train a one-step actor that climbs the critic and copies the flow for the same noise
Part 3 fills src/agents/fql_agent.py. FQL (flow Q-learning) trains three things. The BC flow v learns only by flow matching, with no Q term. A one-step policy πω(s, z) is a plain network from state and noise to an action. The critics bootstrap with the one-step policy.
The one-step policy climbs the critic and copies the flow's action for the same z. Its gradient never enters the flow, so there is no BPTT.
L of omega equals minus Q-hat at pi-omega of s and z, plus alpha times the mean squared distance from pi-omega of s and z to pi-v of s and z.
Draw z. Run the flow to get its action for z, and freeze it. Move the one-step action up the critic, and pay alpha for each squared unit it strays from the frozen action.
If Q-hat rises with slope c near the flow's action, the one-step action settles c/(2α) away. With made-up numbers, c = 1.5 and α = 5 give 0.15.
Purple dots are the flow's actions, one per z. Arrows go to the one-step actions: blue arrive, red crash. The warm curve is Q̂. Drag α, then switch off "same z".
25 noise samples on our toy. The device puts each one-step action at the minimum of its own loss; a trained network only approaches it. Illustrative.
With "same z" on, each z copies a route, never the mean. From α = 4.3 up, at least 90% of runs arrive. With it off, every z copies the same blur of the flow, whose best point is −0.18. The one-step policy then has SAC+BC's problem. The price of safety shows too: at large α, 65% of runs keep the slow route.
Three details from the handout matter in code. Clip flow actions to [−1, 1] before the critic sees them. Act, evaluate and bootstrap with πω, not the flow. Use the mean of the two target critics.
javascriptfunction oneStepLoss(q, aw, av, alpha) {
let s = 0;
q.forEach((qi, i) => {
let d = 0;
aw[i].forEach((x, j) => { d += (x - av[i][j]) ** 2; });
s += -qi + alpha * d / aw[i].length;
});
return s / q.length;
}
numpyloss = (-q + alpha * ((aw - av) ** 2).mean(axis=1)).mean()
def one_step_loss(q, a_w, a_v, alpha): a_w = np.clip(a_w, -1, 1) bc = ((a_w - a_v) ** 2).mean(axis=1) return (-q + alpha * bc).mean()
Chapter 7
Keep the numbers, check what you can build, and pick the next experiment
Three agents, one log. SAC+BC climbs the critic on a BC leash and works in a narrow band of α. IQL never leaves the logged actions, so it is safe but cannot improve on them. FQL copies one route per noise sample and climbs the critic in one step, so it is safe for every large α.
| Term | Meaning | Number to remember |
|---|---|---|
| Q bounds | −1/0 rewards keep Q in [−1/(1 − γ), 0] | −10 at γ 0.9; −100 at 0.99 |
| BC weight α | price of distance from the log | SAC+BC band 0.7 to 4.4 on the toy |
| Action MSE floor | MSE of pure BC, VarD | 0.338 on the two-route log |
| Expectile τ | how high V sits over logged Q | two returns ±10: V = 10(2τ − 1) = 8 at 0.9 |
| AWR cap M | largest weight in IQL's actor | 100; bites above α = 10 on the toy |
| Euler steps F | steps of the flow | 10; F = 1 lands on the mean |
| BPTT gradient | product of Euler-step Jacobians | up to 30× at F = 10, 6,200× at F = 50 |
| FQL band | α with 90% or more runs arriving | 4.3 and up on the toy |
numpy# FQL-lite on one state with a 1-D action (our toy, not the course's code) z = rng.standard_normal(256) # one noise per sample a_flow = euler_flow(z, F=10) # BC flow, trained by flow matching a_w = a_flow.copy() # one-step actions, one per z for _ in range(500): grad = -dq_da(np.clip(a_w, -1, 1)) + 2 * alpha * (a_w - a_flow) a_w -= 0.01 * grad # climb Q-hat, stay near the same z success = np.mean([on_a_route(a) for a in np.clip(a_w, -1, 1)])
q_min.This lesson follows UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine (Spring 2026). See the course page, the Homework 5 handout, the starter code, Lecture 18 on offline RL algorithms and the Section 9 notes. The papers: TD3+BC, IQL, FQL.
Go back to the fork and find each agent's band of α. Then teach it: the Teach pill asks you to explain the BC pull at the whiteboard.