Offline RL
Learning from a fixed dataset: distribution shift and pessimism.
A hospital has ten years of treatment records, a warehouse has millions of logged robot grasps, a website has every recommendation it ever made and every click that followed. None of them can run trial-and-error experiments on patients, robots or customers. Offline RL asks whether the logs alone are enough to learn a policy better than the one that produced them. Often they are, but the off-policy algorithms of the earlier topics fail badly on them, for a reason you can see in one step and that is surprisingly hard to remove.
What you’ll learn
- State the offline RL problem and distinguish it from online off-policy RL and from imitation learning.
- Explain extrapolation error: why a maximum over actions selects overestimated values that the data cannot correct, and why bootstrapping spreads them.
- Compare the main families of offline methods (policy constraints, value pessimism, in-sample learning, model-based penalties) by what each assumes and how each fails.
- Implement the actor update of TD3+BC and the value updates of implicit Q-learning, and compute an expectile.
- Use the D4RL benchmark and the analysis of Kumar et al. (2022) to decide when offline RL should beat behavior cloning.
Learning from a fixed dataset
In offline RL (also called batch RL) the agent receives a dataset collected by a behavior policy and must output a policy with a high return , without interacting with the environment at all. The behavior policy is usually unknown and often a mixture: several clinicians, an old controller, earlier versions of a learning agent, human teleoperators. Write for the distribution of state–action pairs in the data.
Three settings are easy to confuse:
| Aspect | Online off-policy RL (e.g. DQN) | Imitation learning | Offline RL |
|---|---|---|---|
| Data | a replay buffer, refreshed by the learner's own actions | expert demonstrations, usually without rewards | fixed logs with rewards, of any quality |
| Goal | the best policy | behave like the expert | the best policy the data can support |
| Can it beat the data? | yes, by exploring | not in general | yes, by reweighting and recombining what was logged |
| Who corrects a wrong value estimate? | new data, from acting on it | no values to correct | nobody |
How can a policy learned from logs beat the policy that produced them? In two ways. Selection: in a given state the data contain several actions with different outcomes, and choosing the better ones improves on , which averaged over all of them. Stitching: dynamic programming can join the first half of one logged trajectory to the second half of another at a state both pass through, producing a route that no logged episode took. Both work only where the data say something, and that caveat is the whole subject.
Think first Suppose the dataset contains every action in every state many times, for example from a uniformly random behavior policy run for a long time. Is offline RL hard then?
Not especially. With full coverage, offline RL is batch RL with good data: fitted Q-iteration converges to near-optimal values with polynomially many samples, under conditions on the function class (Fitted Q-Iteration & Its Guarantees). The difficulty is partial coverage. Realistic logs cover the behavior policy's habits, not every alternative, and the learned policy will be drawn to precisely the alternatives the data lack.
Why off-policy RL breaks offline: extrapolation error
Take the Q-learning target . The maximum ranges over all actions, including actions the dataset never shows in states like . There is pure extrapolation by the function approximator, constrained by no data. Fujimoto, Meger and Precup (2019) named the resulting error extrapolation error: the error of value estimates at state–action pairs the data do not cover.
The maximum does not sample these errors at random; it picks the largest. Errors at out-of-distribution actions that happen to be positive win the max, enter the regression target, and are copied backward by bootstrapping into every state that leads to . Online, the agent would act on the inflated value, observe what really happens, and the estimate would come down. Offline, that data never arrives.
At a next state , ten actions are absent from the data. Their true values are all 0, and the network's extrapolated estimates behave like independent standard normal errors. By how much does overestimate the true maximum, on average?
Show the answer
1.54
The expected maximum of 10 independent standard normals is about 1.54 (for 2 it is 0.56, for 50 it is 2.25). That error enters the target of every transition into . If every backup adds a bias , the fixed point sits above the truth: 154 at . And because extrapolation errors offline are systematic rather than fresh noise, inflated values can feed on themselves and grow without bound. The same mechanism causes maximization bias online, where new data keep correcting it.
Fujimoto et al. demonstrated the effect on continuous control. DDPG trained on a fixed buffer collected by another DDPG agent did far worse than that agent, even when the two learned concurrently from the identical buffer; trained on data from an expert, it failed to learn at all while its value estimates diverged. The expert data were plentiful. What they lacked was coverage: one action per state, and nothing about the alternatives the maximum kept asking about.
Which dataset makes naive offline Q-learning, with a maximum over all actions in its target, least likely to fail?
- Ten million transitions from a single deterministic expert policy
- Human demonstrations of mixed quality, with rewards
- A modest dataset in which a uniformly random policy tried every action in every state many times
- Transitions from a near-optimal policy that takes a random action 1% of the time
Show the answer
C. A modest dataset in which a uniformly random policy tried every action in every state many times
The maximum in the target is safe only if every action it can select has data behind it. A uniformly random behavior policy covers every action everywhere. The size of a single-policy dataset does not help, because it never shows the alternatives.
Four ways to stay on the data
Every offline method answers one question: what should the learner believe about actions the data do not show? There are four main answers.
| Family | Idea | Examples | Main knob | Typical failure |
|---|---|---|---|---|
| Policy constraint | keep close to , in distribution or in support, so the maximum never reaches unseen actions | BCQ (Fujimoto et al., 2019); BEAR (Kumar et al., 2019); TD3+BC (Fujimoto & Gu, 2021) | how close: a divergence bound, a perturbation range, a cloning weight | on poor data, too tight to improve much |
| Value pessimism | lower the values of unsupported actions so that the maximum avoids them | CQL (Kumar et al., 2020); critic ensembles (An et al., 2021) | penalty weight , ensemble size | too strong: retreats to the most common action |
| In-sample learning | never evaluate an action outside the data; improve only by reweighting logged actions | IQL (Kostrikov et al., 2022); one-step methods (Brandfonbrener et al., 2021) | how greedy the reweighting is | cannot propose an action no one logged |
| Model-based penalties | learn a dynamics model and penalize rewards where it is uncertain | MOPO (Yu et al., 2020); MOReL (Kidambi et al., 2020) | penalty weight | uncertainty estimates that are wrong |
The model-based penalties make pessimism concrete. MOPO optimizes the policy inside an ensemble of learned models with the reward , where estimates the model's uncertainty (in practice, the largest predicted standard deviation among the ensemble's members), and shows that this maximizes a lower bound on the true return under its assumptions. MOReL builds a pessimistic MDP instead: wherever the members disagree beyond a threshold, the state–action pair leads to an absorbing HALT state with a large negative reward.
The policy-constraint family can be strikingly simple. TD3+BC changes one line of an online algorithm:
import torch.nn.functional as F
def td3_bc_actor_loss(actor, critic, s, a, alpha=2.5):
"""Actor loss on a minibatch (s, a) drawn from the dataset."""
pi = actor(s) # deterministic action in [-1, 1]^k
q = critic(s, pi) # Q(s, pi(s))
lam = alpha / q.abs().mean().detach() # makes alpha independent of reward scale
return -lam * q.mean() + F.mse_loss(pi, a)TD3+BC (Fujimoto & Gu, 2021): TD3's actor loss plus a behavior-cloning term , with the Q term rescaled by the average so that one works across tasks; states are also normalized by the dataset's mean and standard deviation. The critic is TD3's, unchanged. The cloning term keeps near logged actions, so the critic is rarely asked about actions far from the data. This matched the more complex methods of its time on D4RL at less than half the run time.
Learning without querying unseen actions: IQL
The cleanest way to avoid extrapolation is never to ask. SARSA-style evaluation of the behavior policy, with the logged next action, uses only data. Brandfonbrener, Whitney, Ranganath and Bruna (2021) found that a single step of constrained policy improvement on top of it, with no further iteration, matched or beat the iterative offline methods on much of the D4RL benchmark, and traced the iterative methods' trouble to the variance of repeatedly evaluating new policies off-policy. But one step cannot stitch: it improves on only through , the value of continuing to act like the data.
Implicit Q-learning (Kostrikov, Nair & Levine, 2022) keeps the in-sample discipline and still approximates a maximum, using expectile regression.
IQL fits a state-value network and an action-value network, on dataset tuples only:
becomes an upper expectile of over the logged actions in , a soft maximum over what the data support, and bootstraps from it. No step evaluates at an action outside the dataset. A policy is extracted at the end by advantage-weighted regression, maximizing : behavior cloning that copies the better logged actions more strongly (the weights are clipped at 100). The paper used on the locomotion tasks and on AntMaze, where stitching matters most.
In some state, 20% of the logged actions have and the other 80% have . With , what value does IQL's converge to (the 0.9-expectile of these Q-values)?
Show the answer
0.69
For the expected loss is . Setting its derivative to zero gives . At the answer is the mean, 0.2: plain SARSA on the behavior policy. At it is 0.96, close to the best logged action's value. Unlike a hard maximum, the expectile never jumps to an action without data; unlike the mean, it is not dragged down by the 80% of poor actions.
import torch
import torch.nn.functional as F
def iql_value_losses(q_net, q_target, v_net, s, a, r, s2, done, gamma=0.99, tau=0.7):
with torch.no_grad():
q_sa = q_target(s, a) # Q at the logged action only
u = q_sa - v_net(s)
v_loss = (torch.abs(tau - (u < 0).float()) * u**2).mean() # expectile regression
with torch.no_grad():
target = r + gamma * (1.0 - done) * v_net(s2) # bootstrap from V, never max_a Q
q_loss = F.mse_loss(q_net(s, a), target)
return v_loss, q_lossEvery quantity is evaluated at dataset pairs and dataset next states ; the only maximization is the implicit one inside the expectile. Policy extraction is a separate weighted behavior-cloning step, so IQL can improve on the data only by reweighting actions someone logged.
Benchmarks, and when offline RL beats behavior cloning
Most deep offline RL papers report results on D4RL (Fu et al., 2020): MuJoCo locomotion datasets of graded quality (random, medium, medium-replay, medium-expert, expert), AntMaze, where the data are undirected walks through a maze and reaching the goal requires stitching, Adroit hand manipulation from a few human demonstrations, and a Franka kitchen. Scores are normalized so that a random policy gets 0 and an expert 100: . The first years of results taught three things.
- Naive off-policy methods do poorly on narrow data. Constraint, pessimism and in-sample methods do far better, and simple ones (TD3+BC, IQL, one-step methods) compete with complicated ones.
- AntMaze separates methods that propagate value across trajectories, such as IQL and CQL, from one-step methods and behavior cloning, which cannot stitch.
- Results often depend on hyperparameters chosen by running the policies in the environment, which a truly offline user cannot do. Choosing them from the data alone is itself an off-policy evaluation problem (Off-Policy Evaluation).
When should you use offline RL rather than behavior cloning, which is simpler and stable? Kumar, Hong, Singh and Levine (2022) compared the two in tabular theory and in experiments. With clean expert data and no distribution shift, cloning is hard to beat: the error bound they prove for it falls like in the number of samples, while their bound for a conservative offline RL method has a term. Offline RL wins when:
- the data are noisy or suboptimal. On long-horizon tasks, offline RL trained on noisy expert data can beat behavior cloning trained on the same amount of clean expert data, because rewards tell it which logged actions to keep;
- rewards are sparse, so a few decisions decide the outcome;
- only a few states are critical: a doorway, a grasp, where one action is right and the rest are costly, while elsewhere many actions are fine. Rewards let offline RL learn which action matters at the critical states; cloning must match the demonstrator everywhere and cannot tell the critical states apart.
You have 5,000 trajectories from one skilled, consistent operator on a short task with dense rewards, and deployment conditions match the data. Which is the safer default?
- Offline RL with a strong pessimism penalty
- Behavior cloning
- Naive off-policy Q-learning on the logs
- Offline RL without pessimism, since it can use the rewards
Show the answer
B. Behavior cloning
Clean expert data without distribution shift is cloning's best case: its error bound falls like , while the bound for conservative offline RL has a term, and offline RL adds hyperparameters that must be tuned without online evaluation. Offline RL earns its keep with noisy or suboptimal data, sparse rewards, long horizons and few critical states.
Key takeaways
- Offline RL learns from a fixed dataset with no interaction. It can beat the behavior policy by selecting better logged actions and stitching trajectories, but only where the data say something.
- Extrapolation error: the maximum in bootstrapped targets selects overestimated values at unseen actions, bootstrapping spreads them, and offline nothing corrects them. Dataset size is not coverage.
- Four responses: constrain the policy (BCQ, BEAR, TD3+BC), penalize unsupported values (CQL, critic ensembles), never query unseen actions (IQL, one-step methods), or penalize model uncertainty (MOPO, MOReL).
- With clean expert data, behavior cloning is hard to beat; offline RL wins with noisy or suboptimal data, sparse rewards, long horizons and few critical states.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In offline Q-learning, what turns extrapolation error into a systematic overestimate rather than noise that averages out?
- Offline datasets have noisier rewards than online interaction
- The discount factor is too close to 1
- The maximum in the target selects the actions whose extrapolated values are highest, bootstrapping copies them backward, and no new data ever correct them
- Target networks are updated too slowly
Show the answer
C. The maximum in the target selects the actions whose extrapolated values are highest, bootstrapping copies them backward, and no new data ever correct them
Unseen actions have estimates no data constrain; the maximum preferentially selects the overestimated ones, and the error propagates through every bootstrapped target. Online, acting on the inflated values would produce corrective data. A large amplifies the effect, but it is not the cause.
How can an offline RL method end up better than the behavior policy that collected its data?
- By choosing the better logged actions in each state, and by stitching pieces of different trajectories together at shared states
- It cannot: offline methods can only recover the behavior policy
- By trusting at actions far from the data, where it is most optimistic
- By training for more gradient steps than the behavior policy did
Show the answer
A. By choosing the better logged actions in each state, and by stitching pieces of different trajectories together at shared states
The behavior policy averages over its own good and bad choices. Selection keeps the good ones; dynamic programming stitches trajectories through states they share. Both stay where the data are informative.
Q-learning's target evaluates at actions the data may not contain. What does implicit Q-learning use instead?
- , with the current policy's action
- , a pessimistic minimum over all actions
- times the average of over uniformly random actions
- , where is fitted to an upper expectile of over the logged actions
Show the answer
D. , where is fitted to an upper expectile of over the logged actions
is fitted only to at dataset pairs, and only to targets built from . The expectile makes a soft maximum over the actions the data contain, so no step queries an unseen action.
According to Kumar et al. (2022), in which situation is offline RL most likely to beat behavior cloning?
- A short task with clean, consistent expert data and dense rewards
- A long-horizon task with noisy demonstrations, sparse rewards and only a few states where the action really matters
- Any task, as long as rewards are logged
- Only when the data come from a uniformly random policy
Show the answer
B. A long-horizon task with noisy demonstrations, sparse rewards and only a few states where the action really matters
With clean expert data and no distribution shift, behavior cloning's error bound falls like and is hard to beat. Rewards let offline RL decide which noisy actions to keep and which matter, an advantage that grows with the horizon and with sparse rewards and few critical states.
Go deeper
- Conservative Offline RL: BCQ, CQL & IQL · Constraining the policy, penalizing unseen actions, or never querying them.
- Pessimism: The Theory of Offline RL · Coverage, concentrability, and why pessimism is provably efficient.
- RL as Sequence Modeling · Decision Transformer, return conditioning, and when it works.
Further reading
- S. Levine, A. Kumar, G. Tucker & J. Fu, "Offline reinforcement learning: Tutorial, review, and perspectives on open problems," arXiv:2005.01643 (2020).
- S. Fujimoto, D. Meger & D. Precup, "Off-policy deep reinforcement learning without exploration," Proceedings of the 36th International Conference on Machine Learning (ICML) (2019).
- I. Kostrikov, A. Nair & S. Levine, "Offline reinforcement learning with implicit Q-learning," International Conference on Learning Representations (ICLR) (2022).
- A. Kumar, J. Hong, A. Singh & S. Levine, "When should we prefer offline reinforcement learning over behavioral cloning?" International Conference on Learning Representations (ICLR) (2022).
- J. Fu, A. Kumar, O. Nachum, G. Tucker & S. Levine, "D4RL: Datasets for deep data-driven reinforcement learning," arXiv:2004.07219 (2020).