Offline Reinforcement Learning

Dive into Deep Learning · §15.7

Offline Reinforcement Learning: Distribution Shift and Pessimism
fixed datasets · trajectory stitching · out-of-distribution extrapolation · lower confidence bounds · CQL & policy constraints

Learning When No New Action May Be Tried

Motivation

  • Purely Offline Settings: Clinical logs, recommenders, and robot teleoperation logs provide a fixed dataset \mathcal{D} with zero further environment interaction.
  • Unchecked Maximization Bias: On 100 narrow FrozenLake episodes (V^*(s_0) = 0.180), naive offline Q-learning predicts 0.25 while earning only 0.10 because no rollout ever refutes lucky thin-support actions.

Three Data Regimes: On-Policy, Off-Policy, and Offline

Data & Target Compatibility

  • On-Policy (REINFORCE, A2C, PPO): Requires trajectories from the current policy \pi_\theta; ratios \rho_t stretch a batch for only a few epochs.
  • On-Policy TD (\delta_{\textrm{SARSA}} = r + \gamma Q(s', a') - Q(s, a)): Because a' \sim \pi_e(\cdot \mid s'), SARSA on a fixed log converges to Q^{\pi_e} (evaluating the collector, not improving on it).
  • Off-Policy Optimality (r + \gamma \max_{a'} Q(s', a')): Does not depend on \pi_e, targeting Q^*—provided \mathcal{D} satisfies the coverage condition over all pairs visited by the greedy policy.

Two Fixed Logs on the Slippery FrozenLake

Experimental Benchmark

On the 4 \times 4 slippery FrozenLake (11 nonterminal cells \times 4 actions = 44 live pairs, exact optimal start value V^*(s_0) = 0.180), we generate 40 datasets each of two contrasting behavior policies:

uniform: 3,997 transitions, 44/44 pairs tried, median support 42; behavior earns 0.008
 narrow: 1,897 transitions, 42/44 pairs tried, median support 8; behavior earns 0.087
  • Coverage vs. Competence Trade-off:
    • Uniform Log (500 random episodes): Terrible behavior return (0.008), but tries all 44/44 live pairs with median support n(s, a) = 42.
    • Narrow Log (100 \epsilon-greedy expert episodes, \epsilon = 0.2): Strong behavior return (0.087), but concentrates 85\% of its actions on \pi^*, leaving median support at just 8 samples per pair.

Sweeping Tabular Q-Learning Over a Fixed Log

Incremental Offline Q

We can run standard tabular Q-learning (offline_q_sweeps) over a fixed log \mathcal{D} by shuffling the recorded transitions for 200 epochs with decaying step size \alpha_n = 1/(1 + 0.1 n(s, a)):

def offline_q_sweeps(batch, gamma, num_sweeps=200, shape=(16, 4), seed=0):
    """The Q-learning loop of d2l.q_learning, step 1 / (1 + 0.1 n(s, a)),
    swept over the fixed log in a fresh random order each time."""
    Q, visits = np.zeros(shape), np.zeros(shape)
    rng = np.random.default_rng(seed)
    for _ in range(num_sweeps):
        for i in rng.permutation(len(batch)):
            s, a, s2 = batch.obs[i], batch.act[i], batch.next_obs[i]
            visits[s, a] += 1
            Q[s, a] += (batch.rew[i] + gamma * (1 - batch.term[i])
                        * Q[s2].max() - Q[s, a]) / (1 + 0.1 * visits[s, a])
    return Q

Certainty Equivalence: Solving the Empirical MDP

The Empirical Fixed Point

Because every sweep revisits the exact same logged transitions, incremental Q-learning converges to the optimal value table of the log’s empirical MDP (\hat{P}(s' \mid s, a) = n(s, a, s')/n(s, a), \hat{r}(s, a) = \sum r / n(s, a)):

def offline_q(batch, gamma, kappa=0.0, num_iters=500, shape=(16, 4)):
    """Where offline Q-learning with decaying steps converges: value
    iteration on the log's empirical MDP. kappa > 0 subtracts
    kappa / sqrt(n(s, a)) inside every backup, distrusts untried pairs
    entirely, and clips at zero, the floor this environment guarantees."""
    n = count(batch, shape)
    P, r = np.zeros(shape + shape[:1]), np.zeros(shape)
    np.add.at(P, (batch.obs, batch.act, batch.next_obs), 1)
    np.add.at(r, (batch.obs, batch.act), batch.rew)
    m = np.maximum(n, 1)                         # untried: rows of zeros
    mdp_hat = d2l.TabularMDP(P / m[..., None], r / m, gamma)
    penalty = np.where(n > 0, kappa / np.sqrt(m),
                       np.inf if kappa > 0 else 0.0)
    Q = np.zeros(shape)
    for _ in range(num_iters):
        Q = np.maximum(mdp_hat.backup(Q.max(axis=1)) - penalty, 0.0)
    return Q

Certainty Equivalence: Solving the Empirical MDP (check)

The Empirical Fixed Point

On a 500-transition log from the uniform policy, the incremental sweeps and the direct solve agree:

batch = make_log(env, uniform, 500, seed=0)
Q_loop, Q_solve = offline_q_sweeps(batch, gamma), offline_q(batch, gamma)
print(f'largest difference between the two tables: '
      f'{np.abs(Q_loop - Q_solve).max():.3f}')
print(f'their greedy policies earn {mdp.policy_value(greedy(Q_loop))[0]:.3f}'
      f' and {mdp.policy_value(greedy(Q_solve))[0]:.3f}')
largest difference between the two tables: 0.006
their greedy policies earn 0.137 and 0.137

Behavior Cloning and Trajectory Stitching

Stitching Sub-Trajectories

  • Behavior Cloning (clone_policy): Copies empirical frequencies \hat{\pi}_e(a \mid s) = n(s, a)/n(s) without improvement.
  • Trajectory Stitching: Bellman backups propagate Episode 2’s goal continuation at cell 10 backward along Episode 1’s fast prefix.
def clone_policy(batch, shape=(16, 4)):
    """Behavior cloning on a table: the log's empirical action
    distribution, uniform wherever the log is silent."""
    n = count(batch, shape)
    total = n.sum(axis=1, keepdims=True)
    return np.where(total > 0, n / np.maximum(total, 1), 1 / shape[1])

Naive Offline Q-Learning vs. Behavior Cloning

Empirical Comparison

Comparing what each learner predicts at the start cell (\max_a \hat{Q}(s_0, a)) against what its policy actually earns (V^\pi(s_0) solved exactly in the true MDP) across 40 uniform and 40 narrow logs:

uniform clone: predicts 0.01, earns 0.01; above V* on  0, above own value on 17
uniform naive: predicts 0.20, earns 0.14; above V* on 28, above own value on 36
        the naive table beats the clone on 40 of 40 logs
 narrow clone: predicts 0.09, earns 0.09; above V* on  0, above own value on 18
 narrow naive: predicts 0.25, earns 0.11; above V* on 39, above own value on 39
        the naive table beats the clone on 27 of 40 logs
  • Trajectory Stitching on Uniform Logs: Behavior cloning copies a random walk and earns 0.01, whereas naive Q-learning stitches good segments from different random episodes to earn 0.14 (beating the clone on 40/40 logs).
  • Overestimation on Narrow Logs: Naive Q-learning predicts 0.25 > V^* = 0.18 on 39/40 narrow logs while earning only 0.10 (barely edging out the clone’s 0.09 on 27/40 logs).

Where the Inflated Predictions Come From

Out-of-Distribution Picks

  • Plotting the estimation error \hat{Q}(s, a) - Q^*(s, a) against the pair’s sample count n(s, a) on the first narrow log reveals why naive Q-learning fails:
  • For thinly sampled pairs (n \le 10), empirical transitions have huge variance, spreading errors from -0.15 to +0.26.
  • The greedy operator \operatorname{argmax}_a \hat{Q}(s, a) systematically picks the thinly supported pairs (n = 2 or n = 5) that suffered lucky positive errors.

picks with n <= 5: cell 2 (n = 2, +0.09), cell 10 (n = 5, +0.20), cell 14 (n = 2, +0.26)

Pooling Greedy Picks Across All 40 Narrow Logs

Distribution Shift Measured

Pooling the greedy policy’s chosen state-action pairs across all 40 narrow datasets confirms that the \max_a operator acts as a selection filter for thin, overestimated actions:

greedy picks resting on 1 to 5 samples: 23% of picks
their median error +0.22; all pairs with 1 to 5 samples +0.08

Offline Distribution Shift: Fully 23\% of the greedy policy’s picks rest on 1 to 5 logged transitions, carrying a median upward error of +0.22 (larger than the true optimal value V^*(s_0) = 0.180 itself). Because the log is fixed, no online rollout ever refutes these phantom values.

Pessimism Under Uncertainty: A Two-Armed Bandit

Lower Confidence Bounds

\hat{r}_{\textrm{LCB}}(a) = \hat{r}(a) - \sqrt{\frac{\log(2K/q)}{2\,n(a)}}

  • Naive empirical argmax: Tricked by 1 lucky draw of Arm 2 (\hat{r}(2) = 1.0, true mean 0.25), earning expected return 0.4375.
  • Lower Confidence Bound (LCB): Subtracts uncertainty radius b(1) = 0.136 vs. b(2) = 1.358, safely selecting well-supported Arm 1 (+0.364 > -0.358).

Pessimistic Value Iteration on the Lake

Tabular Pessimism

In an MDP, Pessimistic Value Iteration (Jin, Yang, & Wang, 2021) subtracts an inverse-square-root count penalty \kappa / \sqrt{n(s, a)} inside every Bellman backup (clipping at the environment’s known floor 0):

Q(s, a) \leftarrow \max\Big(\hat{r}(s, a) + \gamma \sum_{s'} \hat{P}(s' \mid s, a) \max_{a'} Q(s', a') - \frac{\kappa}{\sqrt{n(s, a)}},\ 0\Big)

  • Mirror Image of UCB Exploration (§14.4): Online UCB adds +\kappa \sqrt{\log t / n(s, a)} to entice the agent to visit uncertain pairs and gather corrective data; offline LCB subtracts -\kappa / \sqrt{n(s, a)} to repel the policy from unsupported pairs where no new data will ever arrive.

When Pessimism Helps—and When It Hurts

Narrow vs. Uniform Logs

Running pessimistic value iteration at \kappa = 0.1 across all 40 narrow and 40 uniform logs demonstrates the exact theoretical boundary of offline pessimism (Rashidinejad et al., 2021):

uniform kappa 0.1: predicts 0.05, earns 0.10; above V* on  0, above own value on  3
        against naive: better on 4, worse on 28, tied on 8; beats the clone on 40
 narrow kappa 0.1: predicts 0.13, earns 0.14; above V* on  4, above own value on 15
        against naive: better on 29, worse on 1, tied on 10; beats the clone on 39
  • On Narrow Expert Logs (\kappa = 0.1 Wins): Eliminates overestimation (0.25 \to 0.13), beats naive Q-learning on 29/40 logs (losing on only 1), and beats behavior cloning on 39/40 logs.
  • On Uniform Random Logs (\kappa = 0.1 Hurts): When every pair is already well-covered (n \approx 42), there are no thin lucky outliers to prune, and uneven count penalties distort valid value differences (losing to naive Q on 28/40 logs).

Over-Pessimism and the Offline Model-Selection Dilemma

Choosing Kappa

What happens if we crank the penalty up to \kappa = 0.3 on the 100-episode narrow logs?

uniform kappa 0.3: predicts 0.00, earns 0.02; against naive better on 0, worse on 40
 narrow kappa 0.3: predicts 0.00, earns 0.05; against naive better on 4, worse on 36
  • Cumulative Horizon Charge: Because -\kappa/\sqrt{n(s,a)} is subtracted at every backup step, penalties accumulate along a trajectory up to \sim \frac{\kappa}{\sqrt{n}(1 - \gamma)} = 20 \frac{\kappa}{\sqrt{n}}, driving start values to 0.00 at \kappa = 0.3.
  • Why Tuning \kappa Offline Is Hard: Without a simulator, off-policy evaluation via trajectory importance weights \prod_t \frac{\pi(a_t \mid s_t)}{\pi_e(a_t \mid s_t)} assigns weight 0 to most episodes under a deterministic policy and explodes in variance on the rest.

Deep Offline RL: Policy Constraints and Value Penalties

Beyond Tabular Counts

  • 1. Policy Constraints (TD3+BC, IQL, DPO): Keep \pi(\cdot \mid s) close to the behavior policy \pi_e(\cdot \mid s) via KL or L_2 action penalties.
  • 2. Conservative Q-Learning (CQL; Kumar et al., 2020): Adds \alpha_{\textrm{c}}\mathbb{E}_s[\log\sum_{a'} e^{Q_w(s,a')} - Q_w(s, a_{\textrm{log}})] to push down all action values (suppressing OOD peaks) while pulling up logged actions in proportion to \hat{\pi}_e(a \mid s).

Return-Conditioned Sequence Modeling and Its Traps

Return Conditioning

Decision Transformer (Chen et al., 2021) bypasses Bellman backups and \max_{a'} entirely by training an autoregressive sequence model on (g_0, s_0, a_0, g_1, s_1, a_1, \dots) to predict a_t given a desired return-to-go g_t:

  • Advantage (No Deadly Triad): Pure supervised cross-entropy/MSE loss on logged sequences—no bootstrapping and no out-of-distribution value divergence.
  • Limitation 1 (Weak Stitching): Conditioned on a high return g, the model imitates whole trajectories that achieved g rather than stitching sub-trajectories across failed episodes.
  • Limitation 2 (The Stochastic Luck Trap): In a 1-step bandit where Action A pays 1 with probability 0.5 (0 otherwise, mean 0.5) and Action B deterministically pays 0.6:
    • Every logged episode with return g = 1.0 took Action A.
    • Conditioning on the maximum return g = 1.0 therefore selects Action A (0.50) instead of optimal Action B (0.60).

Concept Check: Stitching, LCB Thresholds, and CQL

Check Your Understanding

Test your grasp of offline RL fundamentals:

  1. Calibration vs. Return: On the uniform random FrozenLake logs, why is Behavior Cloning perfectly calibrated (\text{pred } 0.01 \approx \text{earned } 0.01) yet more than ten times worse than naive offline Q-learning (\text{earned } 0.14)?
  2. Minimum Support for LCB: In our 2-armed bandit (b(a) = \sqrt{\log 40 / (2n(a))}, Arm 1 LCB = 0.364), if Arm 2 has empirical mean \hat{r}(2) = 0.70, why does LCB reject Arm 2 at n(2) = 10 pulls and accept it at n(2) = 17 pulls?
  3. Tabular CQL Fixed Point: In tabular CQL, one step sets \hat{Q}(s, a) = \hat{\mathcal{T}}\hat{Q}(s, a) - \alpha_{\textrm{c}}\big(\frac{\mu(a \mid s)}{\hat{\pi}_e(a \mid s)} - 1\big). Which state-action pairs have their values lowered, and which have their values raised?

Answers:

  1. Behavior cloning estimates the average return of the random collector without any \max_a bias; offline Q-learning stitches a random episode that reached an intermediate cell with a different episode that reached the goal from that cell.
  2. At n(2) = 10, 0.70 - \sqrt{\log 40 / 20} = 0.70 - 0.430 = \mathbf{0.270 < 0.364}; at n(2) = 17, 0.70 - \sqrt{\log 40 / 34} = 0.70 - 0.329 = \mathbf{0.371 > 0.364}.
  3. Actions chosen by \mu more often than by the behavior log (\mu(a \mid s) > \hat{\pi}_e(a \mid s)) are pushed down, while actions common in the log (\mu(a \mid s) < \hat{\pi}_e(a \mid s)) are pushed up.

Summary: Offline Reinforcement Learning Methods

Key Takeaways

Method What It Optimizes Stitching Capability Protection Against OOD Actions Behavior on Narrow vs. Uniform Logs
Behavior Cloning (BC) Supervised \max_\pi \mathbb{E}_{\mathcal{D}}[\log \pi(a \mid s)] None Complete (stays on \hat{\pi}_e) Strong on narrow expert logs (0.09), fails on uniform (0.01)
Offline SARSA On-policy TD r + \gamma Q(s', a'_{\textrm{log}}) None Evaluates Q^{\pi_e} only Converges to collector’s value without improvement
Naive Offline Q Empirical Bellman \max_{a'} \hat{Q}(s', a') High None (picks thin lucky pairs) Excels on uniform (0.14), overestimates on narrow (0.25 vs. 0.10)
Pessimistic Q / CQL Penalizes backup by -\kappa/\sqrt{n} or log-sum-exp High Strong (suppresses thin pairs) Wins on narrow logs (0.14, beats BC on 39/40); hurts if over-applied
Return Conditioning (DT) Autoregressive \pi(a_t \mid s_{\le t}, g_{\le t}) Limited Avoids \max_{a'} operator Vulnerable to stochastic “lucky trajectory” bias