CS 285 HW5: Offline RL with Flow Policies

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.

Choose a route from the log

2.0

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.

Workbook progress
0 / 26 exercises (0%)
0
Day streak
Best: 0
26 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser; the matching numpy is shown beside them.

Chapter 0

The Map: What You Build

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 taughtWhereWhat this page adds
Constraints, CQL, IQL in theoryOffline RLSAC+BC's loss and the α sweep (Ch 1, 2)
The IQL expectile and weights, in codeCS224R HW3, Ch 6 and 7HW5's sign convention, the two knobs on one toy (Ch 3, 4)
Flow actors, IDQL, FQL in one chapterOffline-to-Online RL, Ch 5Flow BC, BPTT, the full FQL recipe (Ch 5, 6)

Trace one batch through each agent

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.

The toy fork (illustrative, our numbers) action a in [−1, 1]: the heading at the fork upper route 0.3 < a < 0.85 8 steps at a = 0.6, more away from it lower route −0.85 < a < −0.3 14 steps at a = −0.6 crash |a| ≤ 0.3 hits the wall; |a| ≥ 0.85 hits the side reward −1 per step, 0 on arrival; discount γ = 0.9 the log 35% near 0.6, 65% near −0.6, spread 0.1 the critic right on logged actions; a false peak at 0.97

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.

The road

  1. SAC+BC: the critic target and the actor loss. The hero's SAC+BC.
  2. Pick α: read the action MSE in a sweep. The hero's α slider.
  3. The IQL critic: an expectile over logged actions only.
  4. The IQL actor: weighted copying. The hero's IQL.
  5. Flow policies: two routes, and the BPTT problem.
  6. FQL: distil the flow into one step. The hero's FQL.
  7. Field guide: numbers, checklist, what to run next.
Why does the log's mean action crash on our toy?

Workbook

Exercise 0.1: The mean of a two-route log Derive
A different log at the same fork: 60% of runs head 0.5, and 40% head −0.7. What is the mean logged action?
heading
Show derivation
mean = 0.6 × 0.5 + 0.4 × (−0.7)
= 0.30 − 0.28 = 0.02
0.02 is inside the wall zone |a| ≤ 0.3. A clear majority does not save the mean.
Exercise 0.2: Whose critic stays on the log? Trace
The critic is wrong only at actions the log never tried, such as 0.97. Which agent's critic loss never evaluates Q at such an action?

Chapter 1

SAC+BC: Climb the Critic, Stay Near the Log

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 = r + γ(1 − d) · ½(Q̄1 + Q̄2)(s′, a′)
Say it aloud

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.

y
y the target each critic regresses onto, one number per logged step.
r
r the logged reward: −1 per step, 0 on arrival.
γ
gamma the discount, 0.9 on our toy.
(1 − d)
one minus d the done mask: d is 1 on the step that ends the run, so the target adds nothing after it.
½(Q̄1 + Q̄2)
half of Q-bar-one plus Q-bar-two the mean of the two slow target critics at the next state s′, with a fresh action a′ from the actor.
In plain words

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 numbers

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.

Back up values along one logged run

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(π) = −Q̂(s, aπ) + α · (1/|A|) ‖a − aπ‖² + β log π(aπ|s)
Say it aloud

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.

L(π)
L of pi the actor's loss, averaged over a batch of logged states.
−Q̂(s, aπ)
minus Q-hat the mean of the two critics at the actor's action. Lowering the loss climbs it.
α
alpha the BC weight, the knob of Chapter 2.
(1/|A|)‖a − aπ‖²
the mean squared distance from the logged action to the actor's action, averaged over the |A| action numbers.
β log π
beta log pi SAC's entropy term; the starter code tunes beta.
In plain words

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.

With numbers

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.

The trap: no done mask

symptom
q_max settles above 0, at 3.6 in the device, which no −1/0 reward can produce.
see it
Plot q_max during training. It must approach 0 from below.
fix
Multiply the bootstrap by (1 − d). The handout's equation leaves the mask out; the code must not.
Your SAC+BC run logs q_min = −140 with γ = 0.99 and −1/0 rewards. What does it tell you?

Workbook

Exercise 1.1: The lower bound on Q Derive
Rewards are −1 or 0, and γ = 0.95. What is the lowest Q-value any policy can have?
Q
Show derivation
worst case: −1 at every step, forever
−(1 + γ + γ² + ...) = −1/(1 − γ) = −1/0.05 = −20
The best case is 0, a run that has already arrived. So q_min and q_max must stay in [−20, 0].
Exercise 1.2: One actor loss by hand Derive
A two-number action. The critics say −5.6 and −5.9 at the actor's action aπ = (0.5, 0.1). The logged action is a = (0.6, −0.2), and α = 10. Leave out the β term. What is the loss?
loss
Show derivation
−Q̂ = −(−5.6 − 5.9)/2 = 5.75
squared gaps: 0.1² = 0.01 and 0.3² = 0.09; mean over |A| = 2: 0.05
loss = 5.75 + 10 × 0.05 = 6.25
Exercise 1.3: The critic target Build
A neighbouring version on plain arrays, one entry per logged step.
  1. Average the two target critics' values at the next step.
  2. Multiply by gamma and by (1 − d).
  3. Add the reward. Return the array of targets.
Show solution
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)
Exercise 1.4: Read a broken run Trace
After 50k steps on a −1/0 task with γ = 0.99: q_max = +2.8, q_min = −97, and the action MSE falls as α rises. Which line is most likely wrong?

Chapter 2

Pick the BC Weight: Read the Action MSE

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 = (μ − &abar;)² + VarD
Say it aloud

MSE equals mu minus a-bar, squared, plus the variance of the log.

MSE
M-S-E the mean over logged steps of (a − μ)² at one state.
(μ − &abar;)²
mu minus a-bar, squared how far the actor's action sits from the log's mean. α shrinks it.
VarD
the variance of the log the spread of the logged actions. No actor can remove it.
In plain words

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.

With numbers

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.

Sweep α and read two curves

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.

10

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.

The trap: a sum where the handout means a mean

symptom
Every α in the suggested grid looks too strong: the MSE sits on the floor and the run copies the log.
see it
Check the BC term's reduction over the action axis. A sum is |A| times a mean.
fix
Average over action numbers, or divide the grid by |A|. With 5 action numbers, α = 100 with a mean equals α = 20 with a sum.
On a two-route log the action MSE at the best α is far above the BC floor. Why?

Workbook

Exercise 2.1: The BC floor of the toy log Derive
The toy log: 35% of actions near 0.6 and 65% near −0.6, each with spread (standard deviation) 0.1. What is VarD, the floor of the action MSE? Give 4 decimals.
MSE
Show derivation
variance of a mixture = spread inside the routes + spread between them
inside: 0.1² = 0.01
between: p(1 − p)(gap)² = 0.35 × 0.65 × 1.2² = 0.3276
VarD = 0.01 + 0.3276 = 0.3376
Almost all of it is the gap between routes. The device's 0.338 matches.
Exercise 2.2: Move α between conventions Derive
A colleague's code sums the BC term over 6 action numbers and finds α = 50 best. Your code takes the mean. Which α gives you the same loss?
α
Show derivation
sum = 6 × mean, so 50 × sum = 50 × 6 × mean
αmean = 300
Exercise 2.3: Plan a sweep Design
Tap the chips in the order you should do them.
?
→
?
→
?
→
?
→
?
pick the α just above the floor test the losses on tiny arrays run α on a log grid (×3 apart) check q_min and q_max stay in bounds plot MSE and success against α
Exercise 2.4: Find the factor of |A| Debug
A neighbouring numpy helper. You tuned α with the handout's grid, which assumes a mean over action numbers. Click the line that breaks that.
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()
Show why
Line 3 sums over the A action numbers, so the term is |A| times too large. Use .mean(axis=1).

Chapter 3

The IQL Critic: An Expectile of Logged Actions

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.

ℓτ(x) = |τ − 1(x > 0)| x²,   x = V(s) − mini Q̄i(s, a)
Say it aloud

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.

ℓτ(x)
ell-tau of x the loss of one logged step; V's loss is its batch mean.
|τ − 1(x > 0)|
tau minus the indicator, in absolute value the weight: 1 − τ when V is above Q, τ when V is below.
x²
x squared the ordinary squared error.
x
x V minus Q: the handout's sign. HW3 used Q minus V.
In plain words

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.

With numbers

τ = 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 = 10(2τ − 1)
Say it aloud

V equals ten times two tau minus one.

V
V the expectile value of the state.
10
ten half the gap between the two returns, −10 and +10.
(2τ − 1)
two tau minus one 0 at τ = 0.5, rising to 1 as τ nears 1.
In plain words

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.

With numbers

τ = 0.9: V = 10 × 0.8 = 8. τ = 0.7: V = 4. V = 9.7 needs 2τ − 1 = 0.97, so τ = 0.985.

Slide τ and watch V climb

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.

0.900

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.

The trap: the indicator for the wrong sign

symptom
V sits below the mean of the logged Q-values: −7.10 is the mean on the fork, and a flipped weight gives −7.67.
see it
Feed one positive and one negative x. With x = V − Q, the positive one must get weight 1 − τ.
fix
Match the indicator to your residual. HW3's code flags u < 0 for u = Q − V; HW5's formula flags x > 0 for x = V − Q. Same loss.
Why does IQL's Q target never ask about an action outside the log?

Workbook

Exercise 3.1: The two-return expectile Derive
Returns −10 and +10, equally often. What is V at τ = 0.75?
V
Show derivation
0.75(10 − V) = 0.25(V + 10)
7.5 − 0.75V = 0.25V + 2.5, so V = 5
check: 10 × (2 × 0.75 − 1) = 5
Exercise 3.2: Which τ gives 9.7? Derive
Same toy. Which τ puts V at 9.7?
τ
Show derivation
10(2τ − 1) = 9.7, so 2τ − 1 = 0.97
τ = 1.97 / 2 = 0.985
At the handout's τ = 0.9, V is 8.
Exercise 3.3: The expectile of two values Build
Value qa occurs with probability pa, value qb with 1 − pa. Return the τ-expectile in closed form.
  1. Find the higher value and its probability; the other is the lower.
  2. Weigh the higher by τ times its probability, the lower by (1 − τ) times its probability.
  3. Return the weighted mean of the two values.
Show solution
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);
}
It comes from τphi(hi − V) = (1 − τ)plo(V − lo), solved for V.
Exercise 3.4: The weight that pulls V down Debug
A neighbouring numpy helper in HW5's sign convention. With τ = 0.9 it fits V below the mean. Click the buggy line.
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()
Show why
Line 3 flags x ≤ 0, the HW3 rule for u = Q − V. With x = V − Q it gives weight τ when V is too high. Use np.abs(tau - over).

Chapter 4

The IQL Actor: Weighted Copying with Two Knobs

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(π) = −min(eαA(s,a), M) log π(a|s)
Say it aloud

L of pi equals minus the smaller of e to the alpha A and M, times log pi of a given s.

L(π)
L of pi the actor's loss, averaged over logged pairs (s, a).
min(eαA, M)
the smaller of e to the alpha A and M the weight. α is the inverse temperature; M = 100 caps it.
log π(a|s)
log pi of a given s how likely the actor finds the logged action. Raising it is copying.
In plain words

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.

With numbers

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.

Reweight the log and refit

Teal bars are the logged actions. Warm bars are the same actions after weighting. The blue line is the Gaussian's mean. Drag α and τ.

1.0
0.90

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.

CornerWhat V meansWhat the actor does
τ 0.5, α 0the log's own value (SARSA)plain BC: −0.18, the wall
τ 0.5, α largethe log's own valuethe best action under the log's values
τ → 1, α 0the best logged actionstill plain BC
τ → 1, α → ∞the best logged actiongreedy 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.

The trap: no cap on the weights

symptom
The actor loss jumps by orders of magnitude, and the policy chases a few samples.
see it
Log the largest weight per batch. At α = 30 and A = 0.46, eαA is about 106.
fix
Clip at M = 100. In the device, α = 30 caps the weights of 30% of the logged actions, and the fit stays put.
At α = 0, where does the IQL actor go on our toy?

Workbook

Exercise 4.1: One weight Derive
α = 3 and a logged action has A = 0.45. What is its weight? Give 3 decimals.
weight
Show derivation
αA = 3 × 0.45 = 1.35
e1.35 = 3.857, below M = 100, so no clip
Exercise 4.2: When the cap starts to bite Derive
The best logged action has A = 0.46. Above which α does its weight hit M = 100? Give 2 decimals.
α
Show derivation
eα × 0.46 = 100
α = ln 100 / 0.46 = 4.605 / 0.46 = 10.01
Above that, all good actions get the same weight, 100, and the cap acts like a copy of the good part of the log.
Exercise 4.3: The weighted mean Build
For 1-D actions, a Gaussian that minimizes the weighted loss has its mean at the weighted mean of the logged actions. Build it.
  1. For each action, compute w = min(eαA, M).
  2. Return the sum of w × a divided by the sum of w.
Show solution
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()
Exercise 4.4: Read the corners Trace
On the fork you set τ = 0.5 and α = 3. In the device the fit lands at 0.595, the same as at τ = 0.9. Why does τ barely matter here?

Chapter 5

Flow Policies and the BPTT Problem

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.

ak+1 = ak + (1/F) v(s, ak, k/F)
Say it aloud

a-k-plus-one equals a-k plus one over F times v of s, a-k and k over F.

ak+1
a-k-plus-one the action after step k + 1; aF is the policy's action πv(s, z).
ak
a-k the action so far; a0 is the noise z, drawn from a standard normal.
1/F
one over F the step size. The handout uses F = 10 steps.
v(s, ak, k/F)
v of s, a-k, k over F the velocity: which way, and how fast, to move the action now.
In plain words

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 numbers

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(v) = (1/|A|) ‖v(s, ã, t) − (a − z)‖²,   ã = (1 − t)z + ta
Say it aloud

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.

L(v)
L of v the flow's BC loss, averaged over logged pairs, noise z and times t from 0 to 1.
1/|A|
one over the size of A a mean over action numbers.
v(s, ã, t)
v at a-tilde the network's velocity at the mixed point.
a − z
a minus z the target: the direction from the noise to the logged action.
ã
a-tilde the point a fraction t of the way from z to a.
In plain words

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.

With numbers

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.

Unroll the flow and measure the gradient

Top: the action each noise z reaches. Bottom: how much the Euler chain multiplies a gradient, da/dz, on a log scale. Drag F.

10

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.

The trap: FBRAC that trains for a while, then blows up

symptom
Spikes in the flow's gradient norm, and Q-values that jump.
see it
Log the gradient norm of the Q term per batch. Spikes come from samples near the split.
fix
Keep the Q term off the flow. FQL in Chapter 6 does this.
Why can a flow policy hold both routes when a Gaussian cannot?

Workbook

Exercise 5.1: Count the Jacobians Derive
The velocity network has 3 layers, and the flow uses F = 10 Euler steps. How many layer Jacobians does one BPTT gradient of −Q̂(s, πv) multiply?
Jacobians
Show derivation
each Euler step runs the 3-layer network once
10 steps × 3 layers = 30
A one-step policy with 3 layers multiplies 3.
Exercise 5.2: One Euler step Derive
A perfect velocity field at t = 0 is v = &abar; − z, with &abar; = −0.18 on our log. With F = 1, which action does z = 1.3 reach?
action
Show derivation
a1 = z + 1 × (&abar; − z) = &abar;
= −0.18, for every z
One step is a straight jump to the mean. The flow needs several steps to bend each z toward its own route.
Exercise 5.3: The Euler loop Build
A 1-D flow. The velocity is a function vel(x, t) passed in.
  1. Start at x = z, with step h = 1 / F.
  2. For k from 0 to F − 1, add h × vel(x, k × h) to x.
  3. Return x.
Show solution
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;
}
Exercise 5.4: Read the gradient curve Trace
In the device the largest da/dz is 30 at F = 10 and about 6,200 at F = 50. What makes it grow?

Chapter 6

FQL: Distil the Flow into One Step

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(ω) = −Q̂(s, πω(s, z)) + α (1/|A|)‖πω(s, z) − πv(s, z)‖²
Say it aloud

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.

L(ω)
L of omega the one-step policy's loss, averaged over logged states and fresh noise z.
−Q̂(s, πω)
minus Q-hat at pi-omega the mean of the two critics at the one-step action.
α
alpha the distillation weight, tuned per task like SAC+BC's.
‖πω − πv‖²
the squared distance to pi-v from the one-step action to the flow's action for the same z. No gradient flows into πv.
In plain words

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.

With numbers

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.

Distil one step per noise sample

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

10

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.

The trap: clipping the one-step action in the distillation term

symptom
Some one-step actions drift past ±1 and stay there; the action MSE stops falling.
see it
Log the share of one-step actions outside [−1, 1].
fix
Compare the raw one-step action with the flow's. A clip has zero gradient outside the range, so the pull back cannot act.
Which policy does FQL use to act and to compute the critic target?

Workbook

Exercise 6.1: How far one z moves Derive
Near the flow's action a0, take Q̂(a) ≈ q0 + c(a − a0) with c = 1.5. With α = 5 and one action number, how far from a0 is the minimum of −Q̂(a) + α(a − a0)²?
action units
Show derivation
d/da [−q0 − c(a − a0) + α(a − a0)²] = −c + 2α(a − a0) = 0
a − a0 = c / (2α) = 1.5 / 10 = 0.15
Double α and the step halves. That is the leash.
Exercise 6.2: Distil without the same z Derive
Suppose the distillation target is a flow action for a fresh noise z′, not the same z. For large α, the one-step action minimizes the average of (a − πv(s, z′))² over z′. On our log, where does it settle?
action
Show derivation
the average of (a − X)² is smallest at a = mean of X
the flow copies the log, so its mean is the log's: 0.35 × 0.6 + 0.65 × (−0.6) = −0.18
Every z then gives the same action, the wall. Sharing z is what keeps the two routes apart.
Exercise 6.3: The distillation loss Build
A neighbouring version on arrays. You get the critic's value at each one-step action, the one-step actions and the flow's actions for the same z.
  1. For each sample, take the mean over action numbers of (aw − av)². Do not clip aw.
  2. The sample's loss is −q + α times that mean.
  3. Return the mean over the batch.
Show solution
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()
Exercise 6.4: The pull that cannot act Debug
A neighbouring numpy helper. One-step actions that leave [−1, 1] never come back. Click the buggy line.
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()
Show why
Line 2 clips the one-step action. At 1.3 the clip outputs 1.0 and passes zero gradient back, so the distance term cannot pull it in. Clip only where the action goes to the critic or the robot.

Chapter 7

The Field Guide

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

TermMeaningNumber 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 logSAC+BC band 0.7 to 4.4 on the toy
Action MSE floorMSE of pure BC, VarD0.338 on the two-route log
Expectile τhow high V sits over logged Qtwo returns ±10: V = 10(2τ − 1) = 8 at 0.9
AWR cap Mlargest weight in IQL's actor100; bites above α = 10 on the toy
Euler steps Fsteps of the flow10; F = 1 lands on the mean
BPTT gradientproduct of Euler-step Jacobiansup to 30× at F = 10, 6,200× at F = 50
FQL bandα with 90% or more runs arriving4.3 and up on the toy

What you can now build

The core, on the toy fork

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

Experiments worth running next

  1. Sweep α for SAC+BC and FQL on one task, and plot the success band of each.
  2. Swap the mean of two target critics for the minimum, and watch q_min.
  3. Run IQL at τ 0.7, 0.9 and 0.99 with α fixed, and compare the spread of results.
  4. Pick the best of N one-step samples by Q̂ at test time, as IDQL does with a flow.

Keep going

The takeaway. Offline RL is a pull between the critic and the log. Make the pull aim at a logged route, not at the log's mean, and α stops being a knife edge.

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.

CS 285 HW5: Offline RL with Flow Policies (UC Berkeley)
Course page · Homework 5 handout · Back to Gleams