Offline / Batch RL
You have a petabyte of logs (driving data, recommendation impressions, medical records) but you can't run a live experiment. Welcome to offline RL: the setting where standard Q-learning fails catastrophically because the network hallucinates high values for actions it's never seen. CQL and IQL tamed it with a small regularization term, and offline RL ideas now matter for recommenders, robotics, and driving research.
After this lesson, you will be able to:
- Explain why naive Q-learning on offline data fails, the distributional shift problem and out-of-distribution Q-value over-estimation
- Use Conservative Q-Learning (CQL) and Implicit Q-Learning (IQL) as the standard, well-tested offline RL algorithms
- Frame RL as supervised sequence prediction with Decision Transformers and the return-conditioning trick
- Pick offline RL when interaction is expensive, dangerous, or impossible, and know when offline-then-online finetuning beats either alone
Before you start
Don't worry if "offline RL" sounds intimidating, it's just RL where you can't interact with the environment, only learn from a fixed dataset. The challenge isn't conceptual; it's that standard RL algorithms break in this setting and you need specific fixes.
#The Setting: Fixed Dataset, No Interaction
#The Fundamental Problem: OOD Action Overestimation
This isn't a small bug, it's catastrophic. In the D4RL paper's benchmark table (Fu et al., 2020), SAC trained purely offline on the Walker2d-medium data scores a normalized 0.9 (a raw return of about 44 against an expert reference of 4592.3), while the offline-specific methods BEAR and CQL score 59.1 and 79.2. The agent confidently picks actions it's never seen.
The next derivation shows the failure on the smallest possible example, and shows how the error is amplified by bootstrapping, not just added once.
Two families of fixes
- Constrain the policy to behave like the data (BCQ, BEAR, AWAC): the "behavior-regularized" family
- Constrain the Q-values to be conservative for OOD actions (CQL, IQL): the "value-regularized" family
The standard recipe today: value-regularized methods, specifically CQL and IQL.
#CQL: Conservative Q-Learning
CQL improves strongly over BCQ and naive DQN on D4RL benchmarks (see the CQL paper for per-task scores).
The code above uses the log-sum-exp form of the penalty. It comes from letting the penalty choose the distribution mu that makes the Q-values look best, which is the Gibbs argument derived in SAC & TD3: Continuous Control RL (the maximum of the average of Q plus the entropy of mu equals the log-sum-exp of Q). The two derivations below use the simpler form written in the formula, with the tabular case that the CQL paper analyses.
The shift above is what makes the learned value a lower bound. Averaging it under the policy shows by how much.
#IQL: Implicit Q-Learning
IQL achieves comparable performance to CQL with simpler implementation. IQL is a popular choice when you want something simple to tune.
The policy extraction step at the end, weighting dataset actions by the exponential of their advantage, is the optimum of a KL-regularised problem that is derived in RLHF & DPO: Aligning LLMs with Human Preferences. The part that is new here is the expectile loss.
#Decision Transformer: RL as Sequence Modeling
Decision Transformer simplifies the algorithmic stack, no Q networks, no value bootstrap, no conservative penalties, and works well on Atari and locomotion benchmarks. The 2023+ "Trajectory Transformer" and "Gato" papers extended this to multi-task generalist agents.
#Decision Rubric: When to Use What
You have logged data from a recommender system: 100M (user_features, recommended_item, watch_time) tuples. The data is from a previous deployed model. What's the right offline RL algorithm?
The answer: CQL or IQL are the right call. BC ignores reward signal entirely. Naive DQN will overestimate Q for never-shown items. Decision Transformer can work but requires careful return conditioning. CQL/IQL are designed for exactly this setting.
| Method | Best for | Avoid when |
|---|---|---|
| CQL | Discrete or continuous actions; need strong OOD safety | Hyperparameter α is hard to tune |
| IQL | Continuous actions, simpler ops | Can underperform CQL on noisy datasets |
| Decision Transformer | Long-horizon tasks where sequence modeling is natural | Short episodic tasks where Q-learning dominates |
| AWAC / AWR | Online finetuning after offline pretraining | Pure offline (use CQL/IQL instead) |
| BC | Expert data, no reward signal | Suboptimal data, BC just clones it |
#Offline-to-Online Finetuning
- Train CQL/IQL offline on logs to get a good initial policy
- Deploy briefly online with low LR + KL constraint to behavior policy (so you don't crash)
- Collect fresh data, mix with offline buffer
- Anneal the conservative penalty α → 0 as online data grows
This is the pattern robotic manipulation research and recommender systems use to combine offline pretraining with safe online improvement.
#Hands-On
torch, which this page does not have, so it is read-only. Copy it to Google Colab to run it.# Copy to Colab: needs torch, so it cannot run on this page.
# Minimal IQL-style offline RL on a toy gridworld
# (Real production uses d3rlpy or CleanRL implementations)
import torch
import torch.nn as nn
import torch.optim as optim
import random
import numpy as np
torch.manual_seed(42); random.seed(42); np.random.seed(42)
# Toy 4x4 gridworld: agent at (0,0), goal at (3,3), reward +1 only at goal
# Actions: 0=up, 1=right, 2=down, 3=left
def step(state, action):
r, c = state
if action == 0: r = max(0, r-1)
elif action == 1: c = min(3, c+1)
elif action == 2: r = min(3, r+1)
elif action == 3: c = max(0, c-1)
next_s = (r, c)
reward = 1.0 if next_s == (3, 3) else 0.0
done = next_s == (3, 3)
return next_s, reward, done
# Generate offline dataset from a partially-trained behavior policy
# (here: 70% greedy toward goal, 30% random — "medium" quality)
def collect_offline_data(num_episodes=500):
data = []
for _ in range(num_episodes):
s = (0, 0)
for _ in range(20): # max 20 steps per episode
if random.random() < 0.3:
a = random.randint(0, 3)
else:
# Greedy heuristic toward goal
a = 1 if s[1] < 3 else 2 # right or down
s_next, r, done = step(s, a)
data.append((s, a, r, s_next, done))
if done: break
s = s_next
return data
dataset = collect_offline_data(500)
print(f"Collected {len(dataset)} offline transitions")
# IQL implementation: V-net, Q-net, policy extracted via AWR
def encode(state):
r, c = state
return torch.tensor([r/3.0, c/3.0], dtype=torch.float32)
V = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 1))
Q = nn.Sequential(nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, 1)) # state + one-hot action
def encode_sa(state, action):
sa = torch.zeros(6); sa[:2] = encode(state); sa[2 + action] = 1.0
return sa
opt_v = optim.Adam(V.parameters(), lr=1e-3)
opt_q = optim.Adam(Q.parameters(), lr=1e-3)
GAMMA = 0.99
TAU = 0.7 # expectile parameter — higher pushes V toward max
print("Training IQL offline...")
for step_i in range(2000):
batch = random.sample(dataset, 64)
states = torch.stack([encode(b[0]) for b in batch])
sa = torch.stack([encode_sa(b[0], b[1]) for b in batch])
rewards = torch.tensor([b[2] for b in batch])
next_states = torch.stack([encode(b[3]) for b in batch])
dones = torch.tensor([b[4] for b in batch], dtype=torch.float32)
# 1. Train V via expectile regression of Q over dataset actions
with torch.no_grad():
q_dataset = Q(sa).squeeze()
v_pred = V(states).squeeze()
diff = q_dataset - v_pred
expectile_w = torch.where(diff > 0, TAU, 1 - TAU)
v_loss = (expectile_w * diff ** 2).mean()
opt_v.zero_grad(); v_loss.backward(); opt_v.step()
# 2. Train Q with V bootstrap (no max over OOD actions!)
with torch.no_grad():
v_next = V(next_states).squeeze()
target = rewards + GAMMA * (1 - dones) * v_next
q_pred = Q(sa).squeeze()
q_loss = ((q_pred - target) ** 2).mean()
opt_q.zero_grad(); q_loss.backward(); opt_q.step()
if step_i % 200 == 0:
print(f"step {step_i}: V_loss={v_loss.item():.4f} Q_loss={q_loss.item():.4f}")
# 3. Extract policy: greedy on Q for each state
print("\nLearned Q-values (best action per cell):")
action_names = ["↑", "→", "↓", "←"]
for r in range(4):
row = ""
for c in range(4):
s = (r, c)
q_vals = [Q(encode_sa(s, a)).item() for a in range(4)]
best_a = np.argmax(q_vals)
row += f"{action_names[best_a]} "
print(row)
print("\nExpect a policy that flows toward (3,3) — bottom-right.")
print("\nCHALLENGE: Add CQL conservative penalty to Q-loss; compare result.")The block that follows runs here, because it uses only the Python standard library. It learns from a fixed log on a 4x4 grid. The log never contains one action, which is exactly the situation where a naive learner trusts a number nobody ever checked.
Tests: Check that the naive learner reaches the goal in far fewer runs than the learner that maxes only over logged actions, and that its arrows point left in most cells.
#Key Takeaways
- Naive Q-learning fails offline because of OOD action overestimation. Q networks confidently extrapolate to high values on actions never seen in the data, and bootstrapping amplifies the error
- CQL adds one conservative penalty that pushes Q-values down for OOD actions and up for in-data actions; α controls strength
- IQL avoids the OOD problem entirely by using expectile regression on V(s) over dataset actions only: never queries Q at OOD actions during target computation
- Decision Transformer reframes RL as supervised sequence modeling. Train a GPT on (return-to-go, state, action) tuples, condition on high target return at inference
- Offline-to-online finetuning is the production pattern, pretrain offline on logs, briefly finetune online with safe constraints; a pattern used in recommender systems and robotics research
#Quick Check
Why does standard Q-learning-style training offline on D4RL Walker2d-medium fail catastrophically (SAC-off scores 0.9 normalized, against 79.2 for CQL)?