Offline RL

Fit a value to a robot's fixed log, and it guesses high where the log is silent. A greedy policy walks straight to the guess: 10 newtons of grip, worth 12 on paper and −12.7 in truth.

Learn to improve a policy from logged data alone, with no new tries, and see the methods that stop it trusting guesses.

Watch Greedy on Q crush the box. Then pick Add a CQL penalty and drag the penalty, or pick Stay near the log and loosen the leash. Then we build each piece: the backup, stitching, the false peak, AWR, AWAC, CQL and IQL.

You need a little Python and what a probability is. Q-learning helps but is not required. We build the rest from zero.

Re-taught from the offline RL material of Stanford CS 224R: Deep Reinforcement Learning, and the AWR, AWAC, CQL and IQL papers. The explanations, toys and numbers here are our own; every toy number is illustrative.

Pick a grip force from the log

Illustrative toy: one state, one step. The true return is 8 − 0.9 × (force − 5.2)². Operators logged 24 grasps between 3.4 and 5.5 N, with noise of 0.8. Q is a cubic fitted to the log. CQL pushes down Q where the policy looks; the leash multiplies the log's own spread of forces by e to the Q over β.

Chapter 0

Learning From a Fixed Log

Meet the one rule of offline RL, no new tries, and see what a log can and cannot tell you

A hospital has five years of treatment records: what each patient looked like, what the doctor gave, and how it went. You want a better treatment policy. You cannot try random doses on patients to see what happens. You have the records and nothing else.

Offline reinforcement learning learns a policy from a fixed dataset of past experience, with no further contact with the world. The dataset holds steps of the form (state, action, reward, next state). Whoever made those choices is the behavior policy, written πβ (pi-beta). It can be one expert, a mix of people, or an older program. Usually nobody knows it exactly; we only see its data.

DomainThe logWhy no new tries
HealthcarePatient recordsYou cannot experiment on patients
DrivingMillions of miles of drivesExploring on a road is dangerous
RoboticsTeleoperated demosRobots break and data is slow
RecommendersClick historiesBad picks lose users

Online methods such as SAC or DQN collect data, update, and collect again with the better policy. Offline RL removes the second collection. The hero's robot is our running example. Operators gripped boxes with forces between 3.4 and 5.5 newtons, and the log records how well each grasp went.

Ask the log about a force

Warm dots are the 24 logged grasps; the bars below count them. Drag the query and read how many grasps lie within a quarter newton.

4.5 N

The same 24 illustrative grasps as the hero.

At 4.5 N the log holds 8 grasps, averaging a return of 7.59. At 8 N it holds none. The set of actions the log covers is its support. Inside it, the data can answer. Outside it, any number is a guess.

The failure. Train a learner that is free to pick any force, and it picks one the log never tried. The symptom is a policy whose chosen actions sit outside the logged range. Measure it with a histogram of the policy's actions over the logged one. Every method in this lesson is a fix for this.

The road

  1. Values and the Bellman backup: Q, V, the advantage and the TD target.
  2. Stitching: why TD can join two half-trips and copying cannot.
  3. The false peak: why Q over-values unseen actions, and how errors pile up.
  4. Filtered behavior cloning: copy only the best trips.
  5. Advantage-weighted regression: the hero's leash, derived.
  6. AWAC: a TD critic under the same leash.
  7. Conservative Q-learning: the hero's penalty, step by step.
  8. Implicit Q-learning: expectiles, so Q never meets an unseen action.
  9. The field guide: the map of methods, numbers, code and links.
What makes a problem offline RL rather than ordinary RL?

Chapter 1

Values and the Bellman Backup

Score an action by what follows it, and pass that score back one step at a time

A robot stands in a corridor of five cells. The last cell pays 10. Every other step pays 0. How much is it worth to step right from the cell next to the goal? From two cells away?

The worth of taking action a in state s, then acting well, is the action value Q(s, a). The worth of the state itself is the state value V(s). Later rewards count less: a discount γ (gamma), between 0 and 1, shrinks them once per step of delay. We learn Q from one step of data with a target.

Say it aloud

y equals r plus gamma times the max over a-prime of Q of s-prime, a-prime.

y
y the TD target: the number that training pulls Q(s, a) toward.
r
r the reward this step paid, read from the log.
γ
gamma the discount, here 0.9.
maxa′
the max over a-prime try every next action and keep the largest value.
Q(s′, a′)
Q of s-prime, a-prime the current guess of the value of action a-prime in the next state s-prime.
In plain words

Take the reward r. Look at the next state s-prime, find its best action by Q, and shrink that value by gamma. Add the two. That is the target y.

With numbers

With made-up numbers: r = 0, gamma 0.9, and Q(s′, right) = 10, Q(s′, left) = 7.29. The max is 10, so y = 0 + 0.9 × 10 = 9.

This one-step target is temporal difference (TD) learning. The other way, Monte Carlo (MC), adds up the real rewards that followed in the logged trip. MC needs whole trips and is noisy. TD needs one step, and it reuses its own guesses.

Back up the corridor

Each circle shows V, the best Q of its cell. Press Back up once and watch the goal's value move one cell to the left.

0.90

Illustrative corridor. Moving right from cell 3 into the goal pays 10; all other moves pay 0.

The advantage says how much better one action is than the policy's usual choice.

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: positive if action a beats the usual choice in state s.
Q(s, a)
Q of s, a the value of taking action a in state s.
V(s)
V of s the average of Q over the actions the policy takes in s.
In plain words

Average Q over the actions the policy takes. That is V of s. Subtract it from the Q of one action. The gap is that action's advantage.

With numbers

With made-up numbers: Q(s, right) = 9 and Q(s, left) = 7, and the log picks each half the time. V(s) = 8, so A(s, right) = +1 and A(s, left) = −1.

The failure. Set gamma to 0.5 and back up four times. The far cell's value is 10 × 0.53 = 1.25, so a goal four steps away barely registers. The symptom is an agent that ignores far rewards. Measure the horizon as the steps until gamma to the step falls below 0.1. The fix is a gamma near 1, and Chapter 3 shows what that costs offline.

A logged step pays r = 2. In the next state, Q is 5 for one action and 8 for another. Gamma is 0.5. What is the TD target?

Chapter 2

Stitching: Joining Half-Trips

See how TD values join pieces of different logged trips into a route no trip took

Why not copy the best trips in the log? Because the best route may not be in the log at all. It may exist only as pieces of different trips.

Here is a log of three trips, with gamma 0.9 and a reward only at the end:

  1. Trip A: s1 → s3 → s5 → s7, a dead end that pays 3.
  2. Trip B: s4 → s3 → s6 → s9, the goal that pays 10.
  3. Trip C: s1 → s2 → s8, a side exit that pays 5.

From s1, no trip reaches the goal. But A passes through s3, and B leaves s3 for the goal. A route that starts like A and ends like B pays 10. Joining pieces of different trips this way is stitching.

Leave s1 three ways

Warm edges show the logged moves. The numbers on the two edges out of s1 are each method's Q. Pick a method and watch the route it takes.

Illustrative graph. Rewards come only at the end of each trip.

Work the numbers. Monte Carlo can only average what followed s1 inside logged trips. After the move to s3, only trip A continues, so MC gives 0.81 × 3 = 2.43. Going to s2 gives 0.9 × 5 = 4.5. MC picks s2 and earns 5.

TD uses the target from Chapter 1 instead. From s6, Q is 10. So V(s3) = 0.9 × 10 = 9, using trip B's move. Then Q(s1, to s3) = 0.9 × 9 = 8.1, using trip A's move. TD picks s3 and earns 10. The backup carried trip B's value into trip A's start.

The failure. A method without TD tops out at the best whole trip in the log. The symptom is a policy that matches, but never beats, the log's best trip. Measure it by comparing the policy's return with the best logged return from the same start. The fix is a TD critic, and the next chapter shows its price.

Why can TD stitch trip A's start to trip B's ending when Monte Carlo cannot?

Chapter 3

Distribution Shift: The False Peak

See why a learned Q rises where the log is silent, and how backups pile those errors up

Go back to the hero and pick Greedy on Q. The cubic fits the 24 logged grasps well. Past 5.5 N there are no grasps, so nothing holds the curve down. It keeps rising to 12 at 10 N, while the truth falls to −12.7.

An action the behavior policy almost never takes is out of distribution (OOD). For OOD actions, Q has no training signal. A neural network fills that gap with a smooth guess, and the guess can go either way. But we choose the policy to maximize Q, so it finds the guesses that went up. Picking the highest of many noisy guesses favors the ones with errors upward.

Online, this fixes itself: the policy tries 10 N, sees the crushed box, and Q learns. Offline, no try ever comes. A gap between the actions the policy takes and the actions in the log is distribution shift.

Backups pile the error up

Now add TD. Each target takes the max over next actions, so each backup can inherit an upward error from the next state. Call the largest extrapolation error at one step ε (epsilon). Call the largest error in Q after k backups Ek.

Say it aloud

E-sub-k-plus-one equals epsilon plus gamma times E-sub-k.

Ek+1
E-sub-k-plus-one the worst error in Q after one more backup.
ε
epsilon the new error one backup can add, from the max picking a guess on an OOD action.
γ
gamma the discount, which shrinks the inherited error once.
Ek
E-sub-k the worst error after k backups, carried in from the next state.
In plain words

Each backup adds a fresh error epsilon and keeps gamma times the old error E-k. Repeat. The error grows toward epsilon divided by one minus gamma.

With numbers

With made-up numbers: epsilon 1 and gamma 0.9. E-0 = 1, E-1 = 1.9, E-2 = 2.71, and the limit is 1 / 0.1 = 10. With gamma 0.99 the limit is 100.

This is a worst case, not a forecast. It says a small error of 1 can become an error of 100 when gamma is 0.99. The same gamma that lets TD see far ahead also lets errors travel far.

Feed the error back

Each purple bar is the worst error in Q after one more backup. The pink dashed line is the limit. Press Play, then raise gamma and play again.

1.0
0.90

The worst case of the recursion above, with a true Q of 5 everywhere. Real errors are often smaller, but they point up.

The failure. The symptom is Q values that keep climbing as training goes on, far above any return in the log. Measure it by plotting the average Q on logged actions next to the average logged return. Training longer makes it worse, so it is not slow convergence. Three fixes organize the rest of this lesson. Keep the policy near the log, push Q down off the log, or never ask Q about unseen actions.

Why do Q errors on unseen actions tend to come out too high, not too low?

Chapter 4

Filtered Behavior Cloning

Copy only the best logged trips, and see the ceiling that comes with it

The safest fix never asks Q anything. Behavior cloning (BC) trains a policy to copy the logged actions, by raising the log-probability of each logged action in its state. It never picks an unseen action, so it never meets a false peak. Filtered behavior cloning copies only the good trips:

  1. Add up each trip's rewards into its return.
  2. Sort the trips by return. Keep the top share, for example the top 25%.
  3. Train the policy to copy the actions in the kept trips, and ignore the rest.

Keep the best trips

Each bar is a logged trip, labelled with its start state. Solid bars are the ones you copy. Drag the slider and watch the average and the coverage.

3

Illustrative log: 12 trips from four starts, three trips each. We score a cloned policy by the average return of the trips it copies.

Work it. The returns add to 60, so copying all 12 trips scores 5.0 on average. Keep the top 3, worth 10, 9 and 8, and the average is 9.0. But those three start at only two of the four starts. At S2 and S4 the cloned policy has no example to copy.

Filtered BC has a hard ceiling: it cannot beat the best trip it copies, and it cannot stitch. It also throws away what the bad trips teach. Still, it is a strong baseline, and many complex methods fail to beat it.

The failure. Keep too few trips, and the policy learns from a handful of examples and has none for whole regions of states. The symptom is good behavior from familiar starts and random behavior elsewhere. Measure the share of starts, or of state clusters, that the kept set covers. The fix is to weight trips instead of cutting them, which is the next chapter.

Why can filtered BC never beat the best trip in the log?

Chapter 5

Advantage-Weighted Regression

Weight each logged action by how much better than usual it did, so the policy stays on a leash to the log

Filtered BC keeps a trip or drops it. Advantage-weighted regression (AWR; Peng et al., 2019) gives every logged action a weight that grows with its advantage.

We want a policy π with a high average advantage that stays close to πβ. The KL divergence measures closeness: it is 0 when two distributions match and grows as they differ. A temperature α (alpha) sets the price of moving away. The best trade has a closed form.

Say it aloud

Pi-star of a given s is proportional to pi-beta of a given s, times e to the A of s, a over alpha.

π*(a|s)
pi-star of a given s the best policy's chance of action a in state s, under the leash.
∝
is proportional to equal after you divide by the total, so the chances add to 1.
πβ(a|s)
pi-beta of a given s how often the log took action a in state s.
exp(A / α)
e to the A over alpha the boost: large for a positive advantage, near 0 for a negative one. Alpha is the temperature.
In plain words

Start from how often the log took each action. Multiply each by e to its advantage over alpha. Divide by the total. An action the log never took stays at 0, whatever its advantage.

With numbers

With made-up numbers: the log took three actions equally, with returns 3, 7 and 1. V = 3.67, so A = −0.67, +3.33 and −2.67. At alpha 1 the boosts are 0.51, 28.0 and 0.07, so pi-star is 1.8%, 98.0% and 0.2%.

Where the exponential comes from

Maximize the average advantage minus α times the KL divergence, with the chances adding to 1. Set the derivative for each π(a) to zero:

A(a) − α [log(π(a) / πβ(a)) + 1] − λ = 0

Lambda holds the add-to-1 rule. So log π(a) is log πβ(a) + A(a) / α plus a constant. Take e of both sides; the constant becomes the divide-by-the-total.

We do not know πβ, but the log samples it. So we fit the network πθ to the logged actions, each weighted by its boost.

Say it aloud

L of theta equals minus the sum over s, a in D, of e to the A over alpha, times log pi-theta of a given s.

L(θ)
L of theta the loss we minimize over the policy's weights theta.
Σ(s,a)∈D
the sum over s, a in D one term for each logged state and action.
exp(A / α)
e to the A over alpha the weight of that logged action, fixed during this step.
log πθ(a|s)
log pi-theta of a given s how likely the network makes the logged action, on a log scale.
In plain words

This is behavior cloning with weights. Raise each logged action's log-probability with a pull of e to A over alpha.

With numbers

Same three actions at alpha 5: the weights are 0.88, 1.95 and 0.59, or 25.7%, 57.1% and 17.2% of the pull. The best action pulls 2.2 times as hard as the first.

Turn the temperature

Warm bars show the logged returns; yellow is V, their average. Teal bars are each action's share of the pull. Drag alpha.

1.00

Illustrative numbers. The slider steps alpha from 0.1 to 10.

The hero's Stay near the log mode is this formula, with the log's spread of forces as πβ and β as the temperature. Original AWR gets the advantage from Monte Carlo returns, so it cannot stitch.

The failure. Set alpha near 0.1 and nearly all the weight lands on one logged action. The policy fits one sample, noise and all. Measure the effective sample size, the squared sum of weights over the sum of squared weights. If it falls near 1, raise alpha.

What happens to AWR as alpha grows large?

Chapter 6

AWAC: A TD Critic on a Leash

Swap AWR's Monte Carlo returns for a TD-learned Q, gain stitching, and watch where the policy still leaks

AWR cannot stitch because its advantages come from whole logged trips. AWAC, the advantage-weighted actor-critic (Nair et al., 2020), keeps AWR's weighted copying for the policy, the actor. It learns Q with TD instead, in a network called the critic. Then A(s, a) = Q(s, a) − V(s) comes from the critic, and TD values can stitch.

The critic needs a target. The next action a′ is not in the log for every next state, so AWAC samples it from the current policy.

Say it aloud

y equals r plus gamma times Q of s-prime, a-prime, with a-prime drawn from pi-theta given s-prime.

y
y the critic's target for a logged step (s, a, r, s-prime).
r
r the logged reward.
γ
gamma the discount.
Q(s′, a′)
Q of s-prime, a-prime the critic's value of the sampled next action.
a′ ~ πθ
a-prime drawn from pi-theta a next action sampled from the policy we are learning, not from the log.
In plain words

Read r and s-prime from the log. Ask the policy pi-theta for an action a-prime at s-prime. Ask the critic for Q of that pair, shrink it by gamma, and add r. That is y.

With numbers

With the hero's Q as the next state's Q, r = 0 and gamma 0.9: if a-prime is 5.0 N, Q = 8.26 and y = 7.43. If a-prime is 6.5 N, outside the log, Q = 10.13 and y = 9.12. The truth at 6.5 N is 6.48, so the true target is 0.9 × 6.48 = 5.83, and this target is 3.3 too high.

The leash is AWAC's defense. Its policy fits only logged actions, so a′ usually lands near the log. But the policy is a smooth network, such as a Gaussian, and its tails can reach past the logged band.

Tighten the actor, watch it leak

The teal curve is the AWAC policy, a Gaussian fitted to the logged forces with weights e to A over alpha. Red is the share of it outside the log. Drag alpha down.

1.00

The hero's 24 illustrative grasps and fitted Q; V is the average Q over the logged forces. The policy's mean and spread are the weighted average and spread of the logged forces. The slider steps alpha from 0.05 to 5.

At alpha 1 the policy's mean is 4.85 N and 5.9% of its chance lies outside the log. At alpha 0.3 the mean moves to 5.34 N, the edge of the data, and 24.5% lies outside. Those samples become a′, and the critic backs up its guesses there.

The failure. The symptom is Q on logged actions creeping above the logged returns as training runs. Measure the share of sampled a′ that fall outside the logged range, as the red share above. The fix is a looser leash, or the next two chapters, which stop Q's guesses at the source.

AWAC can stitch and AWR cannot. What is the one change that makes the difference?

Chapter 7

Conservative Q-Learning

Push Q down wherever the policy looks and up on the logged actions, so the false peak sinks

The leash fixes the actor. Conservative Q-learning (CQL; Kumar et al., 2020) fixes the critic. It adds a term to Q's loss: push down Q on the actions the policy favors, push up Q on the logged actions. On logged actions TD pulls Q back to its targets. Off the log, nothing pulls back, so those values sink.

Call the distribution the penalty looks at μ (mu); in practice it is the policy, or a soft max over actions. Call the logged data D, and the penalty strength α.

Say it aloud

L of Q equals alpha times, E over mu of Q minus E over D of Q, plus one half E over D of Q minus y, squared.

L(Q)
L of Q the critic's loss; training makes it small.
α
alpha the penalty strength. Zero gives plain TD.
Ea~μ[Q]
E over mu of Q Q averaged over the actions the policy favors. The loss pushes it down.
Ea~D[Q]
E over D of Q Q averaged over the logged actions. The minus sign pushes it up.
½ ED[(Q − y)2]
one half E over D of Q minus y, squared the usual TD loss on logged steps.
In plain words

Average Q over the actions mu favors. Subtract the average Q over the logged actions. Scale the gap by alpha, and add the TD loss. Lowering this loss sinks Q where the policy looks but the log does not.

With numbers

With the device's starting values: mu puts 93% on the unseen action E, so the mu-average is 10.76. The logged average is 7.10. At alpha 1 the penalty is 1 × (10.76 − 7.10) = 3.66.

Step the conservative critic

Purple bars are Q. Warm ticks are the logged targets for B, C and D; A and E were never logged. Teal dots show mu. Press Play.

1.0

Illustrative table: one state, five actions, logged shares 0.3, 0.4 and 0.3 for B, C and D. Mu is the softmax of Q. Each step is gradient descent with step size 0.5.

On the first step at alpha 1, E's gradient is 1 × 0.93, so Q(E) drops by 0.47 to 10.53. C's gradient is 1 × (0.05 − 0.40) = −0.35, so Q(C) rises to 8.18. After 9 steps Q(E) falls below Q(C), and the policy picks C. In the hero, the same push moves the choice from 10 N back to 5.2 N at alpha 0.6.

The failure. Too much alpha makes Q pessimistic everywhere, and the policy stops improving on the log. The symptom is average Q on logged actions far below the average logged return. Measure that gap during training. The fix is a smaller alpha, or a version that tunes alpha to hold the gap at a set size.

In CQL, why does Q on an unseen action keep sinking while Q on a logged action settles?

Chapter 8

Implicit Q-Learning

Replace the max with an expectile of logged values, so Q never has to judge an unseen action

Every trouble so far came from one word in the TD target: the max, or a sample from the policy. Both ask Q about actions the log may not have. Implicit Q-learning (IQL; Kostrikov, Nair and Levine, 2021) asks only about logged actions.

The idea: learn V(s) as a high value among the logged actions' Q values, not the average. Then use V(s′) where the max used to be. The tool is expectile regression, a squared loss that charges more for being too low than for being too high. Call the gap u = Q(s, a) − V(s), and the tilt τ (tau), between 0.5 and 1.

Say it aloud

L-tau of u equals the absolute value of tau minus one-if-u-is-below-zero, times u squared.

Lτ(u)
L-tau of u the expectile loss for one logged pair.
|τ − 1(u < 0)|
tau minus one-if-u-is-below-zero, absolute the weight: tau when V is too low (u positive), one minus tau when V is too high.
u2
u squared the squared gap between Q(s, a) and V(s).
In plain words

Square the gap u. If V sits below Q, multiply by tau. If V sits above Q, multiply by one minus tau. With tau above 0.5, V pays more for sitting low, so it rises toward the top of the logged Q values.

With numbers

With tau 0.9: a gap of +2 costs 0.9 × 4 = 3.6, and a gap of −2 costs 0.1 × 4 = 0.4. For logged Q values 3, 5 and 8, the loss is smallest at V = 7.27, near the best logged value.

Tilt the loss

Purple dots are Q for three logged actions in one state. The yellow line is V, the tau expectile. The right panel draws the tilted loss. Drag tau.

0.90

Illustrative Q values 3, 5 and 8, each logged once.

IQL then runs three updates on each batch of logged steps:

  1. V: fit V(s) to Q(s, a) on logged pairs with the expectile loss.
  2. Q: fit Q(s, a) to the target y = r + γ V(s′) where V(s′) is the next state's expectile value. No max, and no action from the policy.
  3. Policy: extract it with AWR weights e to (Q − V) over alpha, on logged actions only.

With r = 0, gamma 0.9 and V(s′) = 7.27, the Q target is 6.55. The paper used tau 0.7 on locomotion tasks and 0.9 on the harder maze tasks.

The failure. Set tau to 0.5 and V becomes the plain average of logged Q. Then the target evaluates the behavior policy, and nothing improves on it. Set tau near 1 and V chases the single luckiest logged value, noise included. The symptom of the first is a policy no better than BC; of the second, V far above the logged returns. Measure V against both. The fix is a tau between, tuned per task.

IQL is run with tau = 0.5. What does it learn?

Chapter 9

The Field Guide

Keep the map of methods, the numbers, a checklist and the core code on one page

Offline RL learns from a fixed log. TD values let it stitch pieces of trips into routes better than any trip. The same TD values guess on unseen actions, the policy hunts for high guesses, and backups pile the errors up. Every method answers one question: how do we stop the policy from trusting Q where the log is silent?

The map of methods

MethodHow it handles unseen actionsValue learningStitches?
Filtered BCCopies logged actions onlyNoneNo
AWRWeighted copying of logged actionsMonte Carlo returnsNo
AWACWeighted copying; the critic samples a′ from the policyTD, Q at a′ ~ πθYes, with some risk
CQLPushes Q down where the policy looksTD plus a penaltyYes
IQLNever queries Q off the logTD with an expectile VYes

The numbers from this page

WhatNumberWhy it matters
Hero, greedy on Q10 N; Q 12.0, truth −12.7The false peak, outside the log
Hero, CQL at α 0.65.2 N; truth 8.0The penalty sinks the peak
Stitching at s1MC 2.43 vs TD 8.1TD carries trip B's goal into trip A
Error limit, ε 110 at γ 0.9; 100 at 0.99A long horizon amplifies guesses
AWR weights, α 11.8%, 98.0%, 0.2%A cold temperature copies one action
AWAC leak, α 0.324.5% of the policy off the logThe critic backs up guesses there
Expectile of 3, 5, 85.33, 6.15, 7.27 at τ 0.5, 0.7, 0.9Tau slides V from mean toward max

Before you trust an offline RL run

The core code: one IQL step

Three losses, each on logged pairs only. Note where the code stops gradients: targets and weights are fixed numbers.

pythonimport torch

def iql_losses(batch, q_net, q_targ, v_net, policy, tau=0.7, alpha=3.0, gamma=0.99):
    s, a, r, s2, done = batch['s'], batch['a'], batch['r'], batch['s2'], batch['done']
    # s [B, obs], a [B, act], r [B], done [B]
    with torch.no_grad():
        q_sa = q_targ(s, a)                                # [B], Q on LOGGED actions only
    u = q_sa - v_net(s)                                  # the gap Q - V
    w = torch.where(u > 0, tau, 1 - tau)                  # tilt: V too low costs tau
    v_loss = (w * u ** 2).mean()

    with torch.no_grad():
        y = r + gamma * (1 - done) * v_net(s2)            # no max, no policy action
    q_loss = ((q_net(s, a) - y) ** 2).mean()

    with torch.no_grad():
        adv = q_sa - v_net(s)
        wts = torch.exp(adv / alpha).clamp(max=100.0)     # AWR weights, capped
    pi_loss = -(wts * policy.log_prob(s, a)).mean()
    return v_loss, q_loss, pi_loss

def cql_penalty(q_net, s, a_data, a_pi, alpha=1.0):
    # add to the TD loss: push Q down at policy actions, up at logged actions
    return alpha * (q_net(s, a_pi).mean() - q_net(s, a_data).mean())

Where it sits

Fine-tuning a language model from human preferences has the same shape. The data is fixed and the reward is a learned guess. A KL penalty keeps the model near a reference model, as AWR's leash keeps the policy near the log. A model that drifts off the reference finds text the reward model over-values, the same false peak.

Keep going

The takeaway. A Q function is trustworthy only where the log covers it. Keep the policy there, sink Q outside it, or never ask Q about outside at all.
Which method never evaluates Q on an action outside the log?

Now press Present or Teach and explain the false peak from memory. Say why Q rises off the log, why the policy finds it, and how CQL and IQL each stop it. Then go back to the hero, crush the box once, and save it twice.

Credit and source

This lesson re-teaches the offline RL material of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it: Peng et al. (2019), AWR; Nair et al. (2020), AWAC; Kumar et al. (2020), CQL; Kostrikov, Nair and Levine (2021), IQL. The toys and numbers here are our own.

CS 224R: Offline RL
The course site · CQL · IQL · Back to Gleams