Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

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 D={(si,ai,ri,si′)}i=1n\data = \{(s_i, a_i, r_i, s_i')\}_{i=1}^n collected by a behavior policy πβ\pi_\beta and must output a policy with a high return J(π)=ES0∼μ[Vπ(S0)]J(\pi) = \E_{S_0\sim\mu}[V^\pi(S_0)], 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 dD(s,a)d^\data(s,a) for the distribution of state–action pairs in the data.

Three settings are easy to confuse:

AspectOnline off-policy RL (e.g. DQN)Imitation learningOffline RL
Dataa replay buffer, refreshed by the learner's own actionsexpert demonstrations, usually without rewardsfixed logs with rewards, of any quality
Goalthe best policybehave like the expertthe best policy the data can support
Can it beat the data?yes, by exploringnot in generalyes, by reweighting and recombining what was logged
Who corrects a wrong value estimate?new data, from acting on itno values to correctnobody
Imitation learning is the subject of Imitation Learning; the last row is the subject of this lesson.

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 πβ\pi_\beta, 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 y=r+γmax⁡a′Qθ(s′,a′)y = r + \gamma\max_{a'}Q_{\boldsymbol\theta}(s', a'). The maximum ranges over all actions, including actions the dataset never shows in states like s′s'. There QθQ_{\boldsymbol\theta} 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 s′s'. Online, the agent would act on the inflated value, observe what really happens, and the estimate would come down. Offline, that data never arrives.

Predict before you look

At a next state s′s', 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 max⁡a′Q(s′,a′)\max_{a'}Q(s',a') 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 s′s'. If every backup adds a bias bb, the fixed point Q=TQ+bQ = \mathcal T Q + b sits b/(1−γ)b/(1-\gamma) above the truth: 154 at γ=0.99\gamma = 0.99. 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.

Check your understanding

Which dataset makes naive offline Q-learning, with a maximum over all actions in its target, least likely to fail?

  1. Ten million transitions from a single deterministic expert policy
  2. Human demonstrations of mixed quality, with rewards
  3. A modest dataset in which a uniformly random policy tried every action in every state many times
  4. 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.

FamilyIdeaExamplesMain knobTypical failure
Policy constraintkeep π\pi close to πβ\pi_\beta, in distribution or in support, so the maximum never reaches unseen actionsBCQ (Fujimoto et al., 2019); BEAR (Kumar et al., 2019); TD3+BC (Fujimoto & Gu, 2021)how close: a divergence bound, a perturbation range, a cloning weighton poor data, too tight to improve much
Value pessimismlower the values of unsupported actions so that the maximum avoids themCQL (Kumar et al., 2020); critic ensembles (An et al., 2021)penalty weight α\alpha, ensemble sizetoo strong: retreats to the most common action
In-sample learningnever evaluate an action outside the data; improve only by reweighting logged actionsIQL (Kostrikov et al., 2022); one-step methods (Brandfonbrener et al., 2021)how greedy the reweighting iscannot propose an action no one logged
Model-based penaltieslearn a dynamics model and penalize rewards where it is uncertainMOPO (Yu et al., 2020); MOReL (Kidambi et al., 2020)penalty weightuncertainty estimates that are wrong
A fifth family, return-conditioned sequence models such as the Decision Transformer, avoids value functions altogether (RL as Sequence Modeling).

The model-based penalties make pessimism concrete. MOPO optimizes the policy inside an ensemble of learned models with the reward r~(s,a)=r^(s,a)−λ u(s,a)\tilde r(s,a) = \hat r(s,a) - \lambda\,u(s,a), where uu 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:

python
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 (π(s)−a)2(\pi(s) - a)^2, with the Q term rescaled by the average ∣Q∣\abs{Q} so that one α\alpha 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 π(s)\pi(s) 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, Q(s,a)←r+γQ(s′,a′)Q(s,a)\leftarrow r + \gamma Q(s',a') with a′a' 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 πβ\pi_\beta only through QπβQ^{\pi_\beta}, 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.

L2τ(u)=∣τ−1(u<0)∣ u2,mτ(X)=arg min⁡m E[L2τ(X−m)]L_2^\tau(u) = \abs{\tau - \mathbb{1}(u < 0)}\,u^2,\qquad m_\tau(X) = \argmin_m\ \E\big[L_2^\tau(X - m)\big]
The τ\tau-expectile of a random variable XX. At τ=0.5\tau = 0.5 the loss is half the squared error and mτm_\tau is the mean. For τ\tau near 1, undershooting a value of XX costs far more than overshooting it, so mτm_\tau climbs toward the largest value XX can take.

IQL fits a state-value network and an action-value network, on dataset tuples only:

LV(ψ)=E(s,a)∼D[L2τ(Qθ^(s,a)−Vψ(s))],LQ(θ)=E(s,a,r,s′)∼D[(r+γVψ(s′)−Qθ(s,a))2].L_V(\psi) = \E_{(s,a)\sim\data}\Big[L_2^\tau\big(Q_{\hat\theta}(s,a) - V_\psi(s)\big)\Big],\qquad L_Q(\theta) = \E_{(s,a,r,s')\sim\data}\Big[\big(r + \gamma V_\psi(s') - Q_\theta(s,a)\big)^2\Big].

Vψ(s)V_\psi(s) becomes an upper expectile of QQ over the logged actions in ss, a soft maximum over what the data support, and QQ bootstraps from it. No step evaluates QQ at an action outside the dataset. A policy is extracted at the end by advantage-weighted regression, maximizing E(s,a)∼D[eβ(Q(s,a)−V(s))log⁡πϕ(a∣s)]\E_{(s,a)\sim\data}\big[e^{\beta(Q(s,a) - V(s))}\log\pi_\phi(a\mid s)\big]: behavior cloning that copies the better logged actions more strongly (the weights are clipped at 100). The paper used τ=0.7\tau = 0.7 on the locomotion tasks and τ=0.9\tau = 0.9 on AntMaze, where stitching matters most.

Predict before you look

In some state, 20% of the logged actions have Q=1Q = 1 and the other 80% have Q=0Q = 0. With τ=0.9\tau = 0.9, what value does IQL's V(s)V(s) converge to (the 0.9-expectile of these Q-values)?

Show the answer

0.69

For 0<m<10 < m < 1 the expected loss is 0.2⋅0.9 (1−m)2+0.8⋅0.1 m20.2\cdot0.9\,(1-m)^2 + 0.8\cdot0.1\,m^2. Setting its derivative to zero gives m=0.18/(0.18+0.08)≈0.69m = 0.18/(0.18 + 0.08) \approx 0.69. At τ=0.5\tau = 0.5 the answer is the mean, 0.2: plain SARSA on the behavior policy. At τ=0.99\tau = 0.99 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.

python
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_loss

Every quantity is evaluated at dataset pairs (s,a)(s, a) and dataset next states s′s'; 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: 100⋅(score−random)/(expert−random)100\cdot(\text{score} - \text{random})/(\text{expert} - \text{random}). 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 1/N1/N in the number of samples, while their bound for a conservative offline RL method has a 1/N1/\sqrt N term. Offline RL wins when:

  1. 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;
  2. rewards are sparse, so a few decisions decide the outcome;
  3. 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.
Check your understanding

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?

  1. Offline RL with a strong pessimism penalty
  2. Behavior cloning
  3. Naive off-policy Q-learning on the logs
  4. 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 1/N1/N, while the bound for conservative offline RL has a 1/N1/\sqrt N 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.

Question 1

In offline Q-learning, what turns extrapolation error into a systematic overestimate rather than noise that averages out?

  1. Offline datasets have noisier rewards than online interaction
  2. The discount factor is too close to 1
  3. The maximum in the target selects the actions whose extrapolated values are highest, bootstrapping copies them backward, and no new data ever correct them
  4. 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 γ\gamma amplifies the effect, but it is not the cause.

Question 2

How can an offline RL method end up better than the behavior policy that collected its data?

  1. By choosing the better logged actions in each state, and by stitching pieces of different trajectories together at shared states
  2. It cannot: offline methods can only recover the behavior policy
  3. By trusting Q^\hat Q at actions far from the data, where it is most optimistic
  4. 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.

Question 3

Q-learning's target r+γmax⁡a′Q(s′,a′)r + \gamma\max_{a'}Q(s',a') evaluates QQ at actions the data may not contain. What does implicit Q-learning use instead?

  1. r+γQ(s′,π(s′))r + \gamma Q(s', \pi(s')), with the current policy's action
  2. r+γmin⁡a′Q(s′,a′)r + \gamma\min_{a'}Q(s',a'), a pessimistic minimum over all actions
  3. r+γr + \gamma times the average of Q(s′,a′)Q(s',a') over uniformly random actions
  4. r+γV(s′)r + \gamma V(s'), where VV is fitted to an upper expectile of QQ over the logged actions
Show the answer

D. r+γV(s′)r + \gamma V(s'), where VV is fitted to an upper expectile of QQ over the logged actions

VV is fitted only to QQ at dataset pairs, and QQ only to targets built from VV. The expectile makes VV a soft maximum over the actions the data contain, so no step queries an unseen action.

Question 4

According to Kumar et al. (2022), in which situation is offline RL most likely to beat behavior cloning?

  1. A short task with clean, consistent expert data and dense rewards
  2. A long-horizon task with noisy demonstrations, sparse rewards and only a few states where the action really matters
  3. Any task, as long as rewards are logged
  4. 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 1/N1/N 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

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