Offline RL and RL for language models¶
Offline RL asks how to learn a better policy from a fixed log of someone else's decisions, without ever trying anything new. Its central danger, trusting value estimates where the data say nothing, is the same danger that makes reward models get hacked and KL penalties necessary when we train language models. This page is the RL theory behind modern post-training.
10,000 ft
Classic RL assumes you can act, observe and correct. Often you cannot: a hospital cannot try random treatments, a lender cannot approve random loans, a robot fleet's logs are all you have. Offline RL learns from a fixed dataset, and the defining problem is distributional shift: the learned policy wants actions the data rarely or never contain, where value estimates are unchecked guesses. The fixes all add some form of pessimism: stay near the data, or assume the worst where it is thin. Now look at post-training a language model. The pre-trained model is a behaviour policy; preference data is a fixed log; a reward model is a value estimate trusted only near the data it was trained on. RLHF's KL penalty is offline RL's policy constraint, reward hacking is its overestimation, and DPO is an offline RL algorithm. The second half of this page uses that lens on the live questions of 2024–2026: online or offline data, per-token credit assignment, the off-policy corrections that asynchronous training needs, and multi-turn agents. For the algorithms that trained the reasoning models (GRPO and its repairs), read RL with verifiable rewards alongside this page.
2,000 ft
- Offline RL = off-policy RL with no way to collect corrective data.
- The failure: bootstrapped targets take a max over actions, including actions the data never tried; their values are arbitrary, the max picks the most over-estimated, and nothing ever corrects it.
- The fixes: constrain the policy to the data's support (BCQ, TD3+BC, AWR), penalise values of unsupported actions (CQL), never query them at all (IQL), or recast RL as return-conditioned sequence modelling (Decision Transformer).
- Language models: maximise reward minus \(\beta\,\mathrm{KL}(\pi\,\|\,\pi_\text{ref})\). The optimum is \(\pi_\text{ref}\) reweighted by \(e^{r/\beta}\): a policy constraint around the reference model, which is where the reward model can be trusted.
- The design choices: sequence-level bandit or token-level MDP; offline (DPO) or online (PPO, GRPO) data; a learned critic, group baselines, or process rewards for credit; and importance corrections for data generated by stale or numerically different policies.
Ground level¶
Part I: offline RL¶
The setting¶
You are given \(\mathcal D = \{(s_i, a_i, r_i, s'_i)\}\), collected by some behaviour policy \(\pi_\beta\) (a person, an older system, a mixture), and you may not interact further. The goal is still the best policy for the real environment. Three neighbouring problems help place it:
- Behaviour cloning (BC) fits \(\pi_\beta\) by supervised learning. Safe, but at best as good as the data, and it copies the bad decisions along with the good.
- Off-policy RL (DQN, SAC) learns from data generated by other policies, but keeps collecting new data, so when it over-values an action, it tries that action and finds out.
- Offline RL wants RL's ability to improve on the data, in particular to stitch together the good parts of different trajectories, with BC's inability to explore.
Why off-policy algorithms fail offline¶
Fujimoto, Meger and Precup (2019) showed that standard off-policy algorithms such as DQN and DDPG "are incapable of learning with data uncorrelated to the distribution under the current policy". The mechanism is the Q-learning target
For actions \(a'\) that never appear in the data at \(s'\), \(Q(s',a')\) is whatever the network extrapolates, and no gradient ever touches it directly. The \(\max\) selects the largest of these unconstrained values, the maximisation bias at its most extreme, and bootstrapping carries the error to every state upstream. Online, the agent would try \(a'\), see the truth and fix it. Offline, the error is permanent, and the greedy policy ends up choosing exactly those never-tried actions.
The experiment in Build it makes this concrete. A 10-cell corridor: start in cell 3, reward +1 at cell 9, \(\gamma = 0.95\). Four actions: right, left, stay, and a "shortcut" that in reality drops you into a pit (reward \(-1\), episode over). The log has 300 episodes from a mediocre policy (right 40%, left 60%) that never used stay or the shortcut. A table initialised with random values stands in for a network's arbitrary outputs on actions it was never trained on:
11506 transitions, 27 reach the goal; actions seen: [0, 1]
behaviour cloning return +0.000 actions [1 1 1 1 1 1 1 1 1]
naive return -0.441 its own estimate +1.572 states picking unseen actions 16%
cql a=1.0 return +0.000 its own estimate +1.940 states picking unseen actions 0%
cql a=0.1 return +0.774 its own estimate +0.701 states picking unseen actions 0%
cql a=0.01 return -0.291 its own estimate +1.325 states picking unseen actions 12%
iql return +0.774 its own estimate +0.705 states picking unseen actions 0%
optimal (go right) return +0.774
Read it line by line. Behaviour cloning copies the majority action, left, and never reaches the goal. Naive offline Q-learning believes it will earn +1.57, more than the best possible +0.774, and actually earns \(-0.44\): in 16% of states it picks a never-tried action because its random initial value happened to beat the learned ones. CQL depends on its penalty weight \(\alpha\): too small (0.01) and it behaves like naive Q-learning; too large (1.0) and the regulariser swamps the reward signal, so it collapses onto the behaviour's majority action like BC; at 0.1 it finds the optimal policy. IQL finds the optimum without tuning, because it never evaluates an action the data did not contain. Both successes improve on every trajectory's policy in the data: no logged episode went straight right, yet the right-moves in the log were enough to learn that right is better.
Four families of fixes¶
1. Constrain the policy to the data. Only choose actions the behaviour policy would plausibly take. BCQ (Fujimoto et al., 2019) generates candidate actions with a generative model of \(\pi_\beta\) and picks the best of those. TD3+BC (Fujimoto and Gu, 2021) adds one term to TD3's actor loss, maximising \(\lambda Q(s,\pi(s)) - (\pi(s) - a)^2\) over dataset pairs \((s,a)\): behaviour cloning as a regulariser, a few lines of code, competitive with far more complex methods. Advantage-weighted regression (AWR, AWAC) does weighted behaviour cloning, \(\max_\pi \mathbb E_{(s,a)\sim\mathcal D}\big[\exp(A(s,a)/\beta)\log\pi(a\mid s)\big]\), whose optimum is \(\pi \propto \pi_\beta\exp(A/\beta)\): the data's policy, tilted toward better actions. Keep that form in mind; it returns for language models.
2. Be pessimistic about values. Conservative Q-learning (Kumar et al., 2020) adds to the Bellman loss a term that pushes \(Q\) down on actions the current policy would pick and up on actions in the data:
The paper proves that the resulting value of the learned policy lower-bounds its true value, and reports policies with 2–5 times higher final return than prior offline methods on complex, multi-modal datasets. The cost is a hyperparameter whose right value depends on the reward scale and the data, as the experiment shows.
3. Never query unseen actions. Implicit Q-learning (Kostrikov, Nair and Levine, 2021) replaces the \(\max_{a'}\) by an upper expectile of \(Q(s', a')\) over the actions in the data, fitted by asymmetric least squares to a separate value network \(V\). Every target uses only \((s,a)\) pairs that occur in \(\mathcal D\); the policy is then extracted by advantage-weighted regression. As the expectile \(\tau \to 1\) it approaches the best in-data action at each state, which is what stitching needs.
4. Treat RL as sequence modelling. The Decision Transformer (Chen et al., 2021) trains a GPT-style model on trajectories written as (return-to-go, state, action) tokens, and at test time conditions on a high desired return. No Bellman backups, no value function; the abstract reports that it matches or exceeds the state-of-the-art model-free offline RL baselines on Atari, OpenAI Gym and Key-to-Door. It is conditional behaviour cloning, which is its strength (stability, scale) and its limit: it can only recombine behaviour it has seen associated with high returns.
Model-based offline RL (MOPO, MOReL) is the fifth branch: learn a dynamics model from the data and plan in it, with a penalty wherever the model is uncertain, the model-based version of the same pessimism.
Pessimism is exploration with the sign flipped
Online, an optimistic agent adds an uncertainty bonus (UCB): if it is wrong, trying the action reveals the truth and costs a little. Offline, nothing reveals the truth, so you subtract the bonus instead (a lower confidence bound). Jin, Yang and Wang (2021) made this precise: pessimistic value iteration, which "simply flips the sign of the bonus function", is minimax optimal for offline RL in linear MDPs, with a guarantee that does not assume the data sufficiently cover every policy.
Evaluating without acting¶
Before deploying an offline policy you want to know its value, which is off-policy evaluation: importance sampling over logged trajectories (unbiased, with variance exploding in horizon) or fitted Q-evaluation (lower variance, biased by the same extrapolation problem). Benchmarks such as D4RL (Fu et al., 2020) report online returns precisely because offline evaluation is unreliable, and real deployments use conservative rollouts and A/B tests.
Logs are a behaviour policy
An assistant that suggests financial actions, like Jarvis, accumulates logs of what advisers and users chose and what followed. Learning a better suggestion policy from those logs is offline RL, and estimating a new policy's value from them is off-policy evaluation. The page's warning applies directly: the log says nothing about suggestions nobody made, so any model that scores them is extrapolating.
Part II: RL for language models¶
Text generation as a decision process¶
A language model \(\pi_\theta(y_t\mid x, y_{<t})\) is a policy. Two framings are in use.
- Token-level MDP. State: the prompt plus the tokens so far. Action: the next token, from a vocabulary of order \(10^5\). Transition: deterministic, append the token. Reward: usually zero until the end-of-sequence token, then \(r(x,y)\) from a reward model or verifier. Horizon: hundreds to tens of thousands of steps.
- Sequence-level contextual bandit. Context \(x\), a single action \(y\) (the whole response), reward \(r(x,y)\), with \(\log\pi(y\mid x) = \sum_t\log\pi(y_t\mid x, y_{<t})\).
The bandit view is what DPO, RLOO and GRPO's advantages use; the MDP view is what PPO's per-token critic and process rewards use. Language is an unusual environment: the dynamics are known and deterministic, so you can restart from any prefix for free, but the action space is huge, the horizon long, and the policy starts with an enormously informative prior from pre-training. Exploration means sampling from that prior.
The KL-regularised objective¶
RLHF maximises, for each prompt,
and its exact maximiser (The maths) is
This is AWR's form again, with \(\pi_\text{ref}\) as the behaviour policy and \(r\) as the advantage. Three readings, each from a different part of this track:
- A policy constraint. The reward model was trained on responses near \(\pi_\text{ref}\)'s distribution. The KL keeps the policy where those judgements were learned, exactly as TD3+BC keeps an offline actor near the data.
- Maximum-entropy RL relative to a prior. SAC's soft-optimal policy is \(\propto\exp(Q/\alpha)\) relative to the uniform distribution (actor-critic); here the prior is the reference model and \(\beta\) is the temperature.
- The door to DPO. Invert it: \(r(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_\text{ref}(y\mid x)} + \beta\log Z(x)\). Substitute into the Bradley–Terry preference model, and \(Z(x)\) cancels from the difference between two responses to the same prompt. You can then fit \(\pi\) directly to preference pairs by maximum likelihood, with no reward model and no sampling: DPO is offline RL on a fixed log of comparisons. Rafailov et al. (2024) show the same derivation works in the token-level MDP, where DPO becomes "a general inverse Q-learning algorithm" and does a form of per-token credit assignment.
In PPO-based RLHF the KL is usually applied per token, folded into the reward: each token gets \(-\beta\big(\log\pi_\theta(y_t\mid\cdot) - \log\pi_\text{ref}(y_t\mid\cdot)\big)\) and the last token also gets \(r(x,y)\). Summed over a sampled response, these penalties are an unbiased estimate of the sequence-level KL.
Reward overoptimisation is offline RL's overestimation¶
A reward model is a function fitted to a fixed dataset of comparisons. Push a policy hard against it and the policy moves into regions the reward model never saw, where its scores are extrapolations, and the optimiser finds the ones that are too high. Gao, Schulman and Hilton (2022) measured this with a synthetic "gold" reward model standing in for humans. As optimisation proceeds the proxy score rises monotonically, while the gold score rises, peaks and falls. As functions of \(d = \sqrt{D_\mathrm{KL}(\pi\,\|\,\pi_\text{init})}\) they found \(R_\text{BoN}(d) = d(\alpha_\text{bon} - \beta_\text{bon}d)\) for best-of-\(n\) sampling and \(R_\text{RL}(d) = d(\alpha_\text{RL} - \beta_\text{RL}\log d)\) for RL, with coefficients that scale smoothly with reward-model size. They also found that, in their setup, a KL penalty raised the proxy score reachable at a given KL but did not improve the gold-versus-KL frontier: the KL budget, not how you spend it, set the outcome.
The second experiment in Build it reproduces the shape exactly, with the closed-form optimum. There are 5,000 possible responses; the proxy is the gold reward plus noise, except that 1% of responses are "exploits" that the proxy scores +4.5 and humans would score \(-2\):
beta KL(pi||ref) proxy reward gold reward mass on exploits
10.00 0.01 +0.244 +0.122 1.6%
3.00 0.09 +0.625 +0.284 4.0%
2.00 0.23 +0.947 +0.346 7.4%
1.50 0.45 +1.330 +0.336 13.0%
1.00 1.25 +2.282 +0.020 32.0%
0.50 4.01 +4.279 -1.567 88.3%
0.20 4.98 +4.641 -1.995 99.9%
0.05 8.32 +4.922 -2.000 100.0%
reference: proxy +0.095, gold +0.036
best-of-4 KL 0.64 proxy +1.318 gold +0.830
best-of-16 KL 1.84 proxy +2.354 gold +1.028
best-of-64 KL 3.17 proxy +3.506 gold +0.063
best-of-256 KL 4.55 proxy +4.501 gold -1.715
Gold reward peaks near \(\beta = 2\) (KL 0.23) and best-of-16 (KL 1.84), then falls to \(-2\) as the optimiser concentrates on the exploits, while the proxy reward rises all the way. The exploits are 1% of the reference distribution, and the exponential reweighting \(e^{r/\beta}\) turns a small blind spot into the whole policy. The remedies are the offline-RL remedies: a KL budget (constraint), ensembles of reward models (an uncertainty estimate, as in PETS and MOPO), refreshing the reward model on the current policy's outputs (new data where the policy now lives), and, where possible, rewards that cannot be wrong: verifiers.
Offline or online data?¶
DPO's appeal is that it needs no sampling during training. The RL lens predicts its weakness: an offline method can only reweight responses that are in the dataset, and it never learns about the responses the current policy produces. The evidence leans the same way. Xu et al. (2024) found that a well-tuned PPO surpassed DPO and other alignment methods on every testbed they tried, from dialogue to competitive programming. Tajwar et al. (2024) found that methods using on-policy sampling or a negative gradient (explicitly pushing down the likelihood of bad responses) outperform offline maximum-likelihood objectives, and explained it by mode-seeking behaviour. The middle path, used in many recipes, is online or iterative DPO: sample fresh pairs from the current policy, label them with a reward model or judge, and apply the DPO loss.
Credit assignment: which tokens earned the reward?¶
With one reward per response, every method must decide how to share it among thousands of tokens.
- A learned critic (PPO's value network) estimates \(V(s_t)\) for every prefix, giving per-token advantages through GAE. Kazemnejad et al. (VinePPO, 2024) found that in reasoning tasks such value networks "barely outperform a random baseline when comparing alternative steps". Because the environment is deterministic and restartable, they replaced the critic by Monte Carlo rollouts from intermediate prefixes and reported better accuracy in up to 3.0 times less wall-clock time.
- Group baselines (RLOO, GRPO) give every token in a response the same advantage. Worked example: four sampled answers to one maths problem score \((1, 0, 0, 1)\). The group mean is 0.5 and the standard deviation 0.5, so GRPO's advantages are \((+1, -1, -1, +1)\); every token of each correct answer is pushed up equally, including a wrong intermediate step the model later corrected, and every token of each wrong answer is pushed down, including its correct first half. Over many samples the right steps win on average: credit assignment by statistics rather than by a critic.
- Process rewards score each step. Lightman et al. (2023) found process supervision "significantly outperforms" outcome supervision on MATH (their process-supervised reward model solved 78% of a representative test subset) and released 800,000 step-level labels (PRM800K). DeepSeek, by contrast, listed a process reward model among its unsuccessful attempts for R1: steps are hard to define, step correctness is hard to judge automatically, and a learned PRM "inevitably leads to reward hacking" during large-scale RL.
Off-policy corrections inside "on-policy" training¶
Large-scale LLM RL is almost never exactly on-policy, and the corrections come straight from the actor-critic literature.
- Several updates per batch. After the first minibatch step, the data are from an older policy. PPO's per-token ratio \(\rho_t = \pi_\theta(y_t\mid\cdot)/\pi_\text{old}(y_t\mid\cdot)\) and its clip are the correction.
- Asynchronous generation. Generating long responses is slow; trainers keep the GPUs busy by training on responses produced by weights one or more steps old. Noukhovitch et al. (2024) found online DPO the most robust of the methods they tested to this off-policyness, and trained a LLaMA 3.1 8B chatbot about 40% faster than a synchronous run at matched final performance.
- Training–inference mismatch. Rollouts come from an inference engine (such as vLLM) and gradients from a training framework (such as FSDP). Even with identical weights, different kernels and precision give "significantly different token probabilities", which silently makes on-policy RL off-policy (Yao et al., 2025). Their fix is truncated importance sampling: weight each token's gradient by \(\min\big(\pi_\text{train}(y_t)/\pi_\text{infer}(y_t),\ C\big)\), the same bias-for-bounded-variance trade as IMPALA's V-trace. They report that it keeps 8-bit rollouts as good as BF16 ones.
Multi-turn and agentic RL¶
An agent that calls tools, browses or edits code acts over many turns, and the environment's responses (tool outputs, test results) enter the context without being generated by the policy. Two consequences: those tokens must be masked out of the policy loss, and the problem becomes a genuine long-horizon MDP again, where a single success at the end of a 50-turn episode must be credited to the right turns. Hierarchical methods such as ArCHer (Zhou et al., 2024) use an utterance-level off-policy critic with a token-level policy. Exploration, reward design and safe environment construction are the open problems here. Silver and Sutton's essay Welcome to the Era of Experience (2025) argues that agents will increasingly learn from long "streams" of their own experience, with rewards grounded in the environment rather than in human pre-judgement, which, if right, makes the offline-to-online questions on this page the central ones.
History¶
Batch RL is old: fitted Q-iteration (Ernst et al., 2005) and Neural Fitted Q (Riedmiller, 2005) learned from fixed datasets. The modern offline RL problem was named and diagnosed in 2019 (Fujimoto et al.'s extrapolation error; BEAR), surveyed in Levine, Kumar, Tucker and Fu's 2020 tutorial, benchmarked with D4RL (2020), and answered by CQL (2020), IQL and the Decision Transformer (2021). On the language side, Ranzato et al. trained sequence models with REINFORCE in 2015 and Bahdanau et al. used actor-critic for sequence prediction in 2016. Jaques et al. introduced KL-control from a pre-trained prior for music and dialogue (2017–2019), and their dialogue system was explicitly an offline RL agent trained on logged human interaction. Ziegler et al. (2019) and Stiennon et al. (2020) set up RLHF with PPO and a KL penalty; InstructGPT (Ouyang et al., 2022) scaled it, reporting that its 1.3B-parameter model's outputs were preferred to the 175B GPT-3's. DPO (2023) turned the KL-regularised optimum into a supervised loss; GRPO (2024) and DeepSeek-R1 (2025) moved the frontier to online RL against verifiers.
First principles¶
Why offline RL is fundamentally limited. A dataset is evidence about the actions it contains. For any action outside it, there is an environment consistent with the data in which that action is excellent, and one in which it is catastrophic. No algorithm can tell them apart. So an offline learner can at best find the best policy the data support, and its guarantees depend on how well the data cover that policy (concentrability, in the theory). Pessimism is the rational response to that ambiguity: among the environments consistent with the data, plan for a bad one.
Why online optimism and offline pessimism are the same principle. Both use a confidence interval around each value estimate. Online, choosing by the upper end is self-correcting: trying an over-valued action shrinks its interval. Offline nothing shrinks, so the upper end stays wrong forever and you must choose by the lower end.
Why the KL penalty, not just the reward. If the reward model were perfect, you would drop the KL. It is not, and its errors are smallest where its training data were. The KL is the cheapest available proxy for "stay where the reward model knows what it is talking about", and the closed-form optimum shows its effect precisely: every response is reweighted by a factor \(e^{r/\beta}\), so a reward error of \(\Delta\) multiplies a response's probability by \(e^{\Delta/\beta}\). A small \(\beta\) turns small errors into large distortions.
Why on-policy samples teach more. The gradient signal from a response is largest where the policy currently puts mass. A preference pair from an older model can be far from anything the current policy would say; pushing its likelihood around changes little that matters, and leaves the current policy's own mistakes untouched. On-policy samples aim the update at the policy's actual behaviour.
Why deterministic dynamics change credit assignment. In most RL problems, estimating the value of a prefix requires a learned critic, because you cannot return to the same state. In text you can: the state is just the prefix. That makes Monte Carlo value estimation from any intermediate point possible and unbiased, and turns credit assignment into a compute trade-off rather than a learning problem.
The maths¶
Offline objective. Maximise \(J(\pi)\) in the true MDP using only \(\mathcal D \sim d^{\pi_\beta}\).
CQL (the \(\mathcal H\) variant, as above): Bellman error plus \(\alpha\,\mathbb E_{s\sim\mathcal D}\big[\log\sum_a\exp Q(s,a) - \mathbb E_{a\sim\mathcal D}Q(s,a)\big]\). For a table, the regulariser's gradient with respect to \(Q(s,\cdot)\) is \(\alpha\big(\operatorname{softmax}(Q(s,\cdot)) - \hat\pi_\beta(\cdot\mid s)\big)\): it lowers actions the soft-max policy likes more than the data do, and raises the data's actions.
IQL. With \(u = Q(s,a) - V(s)\) for \((s,a)\in\mathcal D\), fit \(V\) by the expectile loss \(L^\tau_2(u) = |\tau - \mathbb 1(u < 0)|\,u^2\); fit \(Q\) to \(r + \gamma V(s')\); extract \(\pi\) by maximising \(\mathbb E_{\mathcal D}\big[\exp(\beta(Q(s,a) - V(s)))\log\pi(a\mid s)\big]\). With \(\tau = 0.5\), \(V\) is the mean (SARSA-like evaluation of \(\pi_\beta\)); as \(\tau\to1\), \(V(s)\to\max\) of \(Q\) over actions in the data's support.
Derivation: the optimum of the KL-regularised objective
Fix \(x\) and drop it from the notation. For any distribution \(\pi\) over responses,
with \(Z = \sum_y\pi_\text{ref}(y)e^{r(y)/\beta}\). The last term does not depend on \(\pi\), and a KL divergence is non-negative and zero only when its arguments are equal. So the maximum is attained uniquely at \(\pi^* = \pi_\text{ref}e^{r/\beta}/Z\), and the maximum value is \(\beta\log Z\) (a "soft maximum" of the reward under \(\pi_\text{ref}\), which tends to \(\max_y r(y)\) over the reference's support as \(\beta\to0\)).
DPO from here. Rearranging, \(r(y) = \beta\log\frac{\pi^*(y)}{\pi_\text{ref}(y)} + \beta\log Z\). Under the Bradley–Terry model, \(P(y_w \succ y_l) = \sigma(r(y_w) - r(y_l))\), and \(\beta\log Z\) cancels in the difference. Replacing \(\pi^*\) by the trainable \(\pi_\theta\) and maximising the likelihood of observed preferences gives the DPO loss
Per-token KL-shaped reward (PPO-RLHF): \(\tilde r_t = -\beta\log\frac{\pi_\theta(y_t\mid x,y_{<t})}{\pi_\text{ref}(y_t\mid x,y_{<t})} + \mathbb 1[t = T]\,r(x,y)\). Since \(\mathbb E_{y\sim\pi_\theta}\big[\sum_t\log\frac{\pi_\theta(y_t\mid\cdot)}{\pi_\text{ref}(y_t\mid\cdot)}\big] = D_\mathrm{KL}(\pi_\theta(\cdot\mid x)\|\pi_\text{ref}(\cdot\mid x))\) by the chain rule of KL, the expected return of \(\tilde r\) is exactly \(J(\pi_\theta)\).
Best-of-\(n\). Sampling \(n\) responses from \(\pi_\text{ref}\) and keeping the highest-scoring one defines a policy with \(D_\mathrm{KL}(\pi_\text{BoN}\|\pi_\text{ref}) = \log n - \frac{n-1}{n}\) (the analytic formula used by Gao et al., from Stiennon et al., 2020, appendix).
Importance-corrected policy gradient for data sampled from \(\mu\) (an older policy or a different inference engine): \(\hat g = \sum_t \min(\rho_t, C)\,\hat A_t\,\nabla_\theta\log\pi_\theta(y_t\mid\cdot)\) with \(\rho_t = \pi_\theta(y_t\mid\cdot)/\mu(y_t\mid\cdot)\). With \(C = \infty\) this is unbiased per-token importance sampling, which ignores the effect of earlier tokens on the state distribution (the same approximation PPO makes); a finite \(C\) bounds the variance at the cost of bias toward \(\mu\).
Build it¶
NumPy. Part 1 is the offline corridor: naive offline Q-learning, behaviour cloning, CQL and IQL on the same logged data. Part 2 computes the KL-regularised optimum in closed form for a range of \(\beta\) and compares it with best-of-\(n\), under a reward model with a blind spot.
import numpy as np
rng = np.random.default_rng(0)
# A 10-cell corridor. Start in cell 3; cell 9 pays +1 and ends the episode; gamma = 0.95.
# Actions: 0 right, 1 left, 2 stay, 3 "shortcut" (really: fall into a pit, reward -1, episode ends).
# The logging policy goes right 40% / left 60% and NEVER uses actions 2 or 3.
N, START, GOAL, G = 10, 3, 9, 0.95
def step(s, a):
if a == 3: return s, -1.0, True
s2 = min(N - 1, max(0, s + (1, -1, 0)[a]))
return s2, float(s2 == GOAL), s2 == GOAL
data = []
for _ in range(300): # the fixed dataset: 300 logged episodes
s = START
for _ in range(40):
a = 0 if rng.random() < 0.4 else 1
s2, r, done = step(s, a); data.append((s, a, r, s2, done)); s = s2
if done: break
S, A, R, S2, D = map(np.array, zip(*data))
print(f"{len(data)} transitions, {int(D.sum())} reach the goal; actions seen: {sorted(set(A.tolist()))}")
def fit(method, iters=300, lr=0.5, alpha=1.0, tau=0.9):
Q = rng.normal(0, 1, (N, 4)) # arbitrary values, as an untrained network has
V = np.zeros(N)
for _ in range(iters):
if method == "iql": # in-sample: V = upper expectile of Q(s, a_data)
u = Q[S, A] - V[S]; w = np.where(u > 0, tau, 1 - tau)
V += lr * np.bincount(S, w * u, N) / np.maximum(np.bincount(S, minlength=N), 1)
target = R + G * (1 - D) * V[S2] # never evaluates an unseen action
else:
target = R + G * (1 - D) * Q[S2].max(1) # max over ALL actions, seen or not
grad = np.zeros((N, 4)); np.add.at(grad, (S, A), target - Q[S, A])
if method == "cql": # push down soft-max of Q, push up data actions
P = np.exp(Q[S] - Q[S].max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
np.add.at(grad, S, -alpha * P); np.add.at(grad, (S, A), alpha)
Q += lr * grad / np.maximum(np.bincount(S, minlength=N), 1)[:, None]
return Q
def true_return(policy): # roll the greedy policy out in the real MDP
s, ret, disc = START, 0.0, 1.0
for _ in range(100):
s, r, done = step(s, policy[s]); ret += disc * r; disc *= G
if done: break
return ret
seen = np.zeros((N, 4), bool); seen[S, A] = True
bc = np.array([np.bincount(A[S == s], minlength=4).argmax() for s in range(N)])
print(f"{'behaviour cloning':18s} return {true_return(bc):+.3f} actions {bc[:9]}")
for m, alpha in (("naive", 0), ("cql", 1.0), ("cql", 0.1), ("cql", 0.01), ("iql", 0)):
res = []
for _ in range(20):
Q = fit(m, alpha=alpha)
pol = Q.argmax(1) if m != "iql" else np.where(seen, Q, -np.inf).argmax(1)
est = Q[START].max() if m != "iql" else Q[START, seen[START]].max()
res.append((true_return(pol), est, np.mean(np.isin(pol[:9], (2, 3)))))
r, est, frac = np.mean(res, 0); name = m + (f" a={alpha}" if m == "cql" else "")
print(f"{name:18s} return {r:+.3f} its own estimate {est:+.3f} states picking unseen actions {frac:4.0%}")
print(f"{'optimal (go right)':18s} return {G ** 5:+.3f}")
11506 transitions, 27 reach the goal; actions seen: [0, 1]
behaviour cloning return +0.000 actions [1 1 1 1 1 1 1 1 1]
naive return -0.441 its own estimate +1.572 states picking unseen actions 16%
cql a=1.0 return +0.000 its own estimate +1.940 states picking unseen actions 0%
cql a=0.1 return +0.774 its own estimate +0.701 states picking unseen actions 0%
cql a=0.01 return -0.291 its own estimate +1.325 states picking unseen actions 12%
iql return +0.774 its own estimate +0.705 states picking unseen actions 0%
optimal (go right) return +0.774
import numpy as np
rng = np.random.default_rng(0)
# 5,000 possible responses to one prompt. The reference model's probabilities are log-normal-ish.
# Gold reward (what humans really want) ~ N(0, 1). The learned reward model sees gold + noise,
# and has a blind spot: 1% of responses (an "exploit") score +4.5 with the proxy but -2 in reality.
K = 5000
logp_ref = rng.normal(0, 1.5, K); p_ref = np.exp(logp_ref - logp_ref.max()); p_ref /= p_ref.sum()
gold = rng.normal(0, 1, K)
proxy = gold + rng.normal(0, 0.5, K)
hack = rng.random(K) < 0.01; proxy[hack] = 4.5 + rng.normal(0, 0.3, hack.sum()); gold[hack] = -2.0
def optimum(beta): # argmax E[proxy] - beta * KL(pi || p_ref)
logits = np.log(p_ref) + proxy / beta # pi* = p_ref * exp(r / beta) / Z
pi = np.exp(logits - logits.max()); return pi / pi.sum()
print(" beta KL(pi||ref) proxy reward gold reward mass on exploits")
for beta in (10, 3, 2, 1.5, 1, 0.5, 0.2, 0.05):
pi = optimum(beta); kl = np.sum(pi * np.log(pi / p_ref + 1e-300))
print(f"{beta:6.2f} {kl:9.2f} {pi @ proxy:+9.3f} {pi @ gold:+9.3f} {pi[hack].sum():6.1%}")
print(f"reference: proxy {p_ref @ proxy:+.3f}, gold {p_ref @ gold:+.3f}")
# Best-of-n against the same proxy: KL(BoN || ref) = log n - (n-1)/n (Stiennon et al., 2020).
for n in (4, 16, 64, 256):
picks = [max(rng.choice(K, n, p=p_ref), key=lambda i: proxy[i]) for _ in range(4000)]
print(f"best-of-{n:<3d} KL {np.log(n) - (n - 1) / n:5.2f} proxy {proxy[picks].mean():+.3f} gold {gold[picks].mean():+.3f}")
beta KL(pi||ref) proxy reward gold reward mass on exploits
10.00 0.01 +0.244 +0.122 1.6%
3.00 0.09 +0.625 +0.284 4.0%
2.00 0.23 +0.947 +0.346 7.4%
1.50 0.45 +1.330 +0.336 13.0%
1.00 1.25 +2.282 +0.020 32.0%
0.50 4.01 +4.279 -1.567 88.3%
0.20 4.98 +4.641 -1.995 99.9%
0.05 8.32 +4.922 -2.000 100.0%
reference: proxy +0.095, gold +0.036
best-of-4 KL 0.64 proxy +1.318 gold +0.830
best-of-16 KL 1.84 proxy +2.354 gold +1.028
best-of-64 KL 3.17 proxy +3.506 gold +0.063
best-of-256 KL 4.55 proxy +4.501 gold -1.715
A per-token RLHF loss with the KL folded into the reward and truncated importance weights for rollouts from a separate inference engine (PyTorch, standard code, not run here; the advantage computation is the GAE of the previous page, or a group baseline):
import torch
def shaped_rewards(logp_policy, logp_ref, final_reward, mask, beta=0.05):
"""All (B, T); mask is 1 on generated tokens, 0 on prompt, padding and tool-output tokens."""
r = (-beta * (logp_policy - logp_ref) * mask).detach() # per-token KL penalty, no grad
last = mask.cumsum(1).argmax(1) # index of each response's last token
r[torch.arange(len(r)), last] += final_reward # sequence reward at the end
return r
def pg_loss(logp_new, logp_rollout, adv, mask, clip_is=2.0):
"""logp_rollout: log-probs reported by the inference engine when sampling (no grad)."""
w = torch.exp(logp_new.detach() - logp_rollout).clamp(max=clip_is) # truncated IS weight
return -(w * adv * logp_new * mask).sum() / mask.sum()
Things to try
- Part 1: give the behaviour policy a 2% chance of the stay action. How do naive Q-learning and CQL change once every action has a little data?
- Part 1: replace the random initialisation by zeros. Naive Q-learning now looks fine. Why is that misleading about neural networks?
- Part 1: implement TD3+BC's idea in the table: choose \(\arg\max_a\,[\lambda Q(s,a) + \log\hat\pi_\beta(a\mid s)]\), and sweep \(\lambda\).
- Part 2: make the exploit's proxy score 3.0 instead of 4.5. Why does gold reward then recover at small \(\beta\)? (Look at the honest responses in the proxy's upper tail.)
- Part 2: average three proxies with independent noise and independent blind spots. How much later does gold reward peak?
Check yourself¶
Why does Q-learning that works with a replay buffer fail on a fixed dataset?
Online, an over-valued action gets tried and its value corrected. Offline, values of actions the data never contain are never corrected, the max in the target selects the most over-valued of them, and bootstrapping propagates that error. The greedy policy then prefers exactly the untested actions.
Name the four families of offline RL methods and the single idea behind all of them.
Policy constraints (BCQ, TD3+BC, AWR), conservative values (CQL), in-sample learning (IQL), and sequence modelling (Decision Transformer); plus model-based with uncertainty penalties. All avoid acting on value estimates for actions the data do not support: pessimism, or staying in distribution.
State the optimum of the KL-regularised RLHF objective and explain what β does.
\(\pi^* \propto \pi_\text{ref}\exp(r/\beta)\). \(\beta\) is a temperature: large \(\beta\) keeps the policy near the reference, small \(\beta\) concentrates it on the highest-reward responses. A reward error \(\Delta\) changes a response's probability by a factor \(e^{\Delta/\beta}\), so small \(\beta\) amplifies reward-model errors.
In what sense is DPO an offline RL algorithm?
It fits the closed-form optimum of the KL-regularised objective directly to a fixed dataset of preference pairs, without sampling from the policy during training. Like any offline method, it can only reweight responses represented in its data and never sees the current policy's own outputs unless you add online sampling.
Why does gold reward eventually fall as you optimise a learned reward model harder?
The reward model is accurate only near its training distribution. Optimisation moves the policy toward responses the model over-scores, including out-of-distribution ones. Proxy reward keeps rising while true reward peaks and declines: Goodhart's law, measured by Gao et al. as a function of \(\sqrt{\mathrm{KL}}\).
GRPO assigns the same advantage to every token of a response. What is lost, and how do VinePPO and process rewards try to recover it?
Per-token credit: a wrong step inside a correct answer is reinforced, a right step inside a wrong answer is penalised; only averaging over many samples sorts them out. VinePPO estimates values of intermediate prefixes by Monte Carlo rollouts, possible because text is a restartable environment; process reward models score each step directly, at the cost of defining steps and of reward hacking.
Hard: why does training on rollouts from vLLM with an FSDP trainer need importance weights even when the weights are identical?
The policy gradient's expectation is over samples from the policy being differentiated. Different kernels and precisions make the inference engine's token probabilities differ from the trainer's, so the samples come from a slightly different distribution \(\mu\). Weighting by \(\pi/\mu\) corrects this; truncating the weight at \(C\) bounds the variance when the two disagree a lot on rare tokens.
Hard: why can an offline learner improve on every trajectory in its dataset, and what limits that?
Bellman backups combine pieces of different trajectories (stitching): if one trajectory goes A→B well and another B→goal well, the values connect them. The limit is coverage: improvement is only possible through state–action pairs the data contain; beyond them nothing distinguishes a good action from a catastrophic one.
Go deeper¶
Papers: offline RL
- Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — Levine, Kumar, Tucker and Fu, 2020. The map of the field; start here.
- Off-Policy Deep Reinforcement Learning without Exploration — Fujimoto, Meger and Precup, 2019. Extrapolation error and BCQ.
- Conservative Q-Learning for Offline RL — Kumar, Zhou, Tucker and Levine, 2020.
- Offline RL with Implicit Q-Learning — Kostrikov, Nair and Levine, 2021 · A Minimalist Approach to Offline RL — Fujimoto and Gu, 2021 (TD3+BC).
- Decision Transformer — Chen et al., 2021 · Advantage-Weighted Regression — Peng et al., 2019.
- Is Pessimism Provably Efficient for Offline RL? — Jin, Yang and Wang, 2021 · D4RL — Fu et al., 2020.
Papers: RL for language models
- Fine-Tuning Language Models from Human Preferences — Ziegler et al., 2019 · Training language models to follow instructions with human feedback — Ouyang et al., 2022.
- Way Off-Policy Batch Deep RL of Implicit Human Preferences in Dialog — Jaques et al., 2019 · ILQL — Snell et al., 2022. Offline RL for language, before and after ChatGPT.
- Scaling Laws for Reward Model Overoptimization — Gao, Schulman and Hilton, 2022.
- Direct Preference Optimization — Rafailov et al., 2023 · From r to Q* — Rafailov et al., 2024.
- Is DPO Superior to PPO for LLM Alignment? — Xu et al., 2024 · Preference Fine-Tuning of LLMs Should Leverage Suboptimal, On-Policy Data — Tajwar et al., 2024.
- Let's Verify Step by Step — Lightman et al., 2023 · VinePPO — Kazemnejad et al., 2024. Two answers to credit assignment.
- Asynchronous RLHF — Noukhovitch et al., 2024 · On the Rollout-Training Mismatch in Modern RL Systems — Yao et al., NeurIPS 2025 workshop.
- ArCHer: Training Language Model Agents via Hierarchical Multi-Turn RL — Zhou et al., 2024.
Videos, books and essays
- Offline RL Tutorial (NeurIPS 2020) — Kumar and Levine. Slides and talk for the tutorial paper above.
- CS 285: Deep Reinforcement Learning — Sergey Levine, UC Berkeley. The offline RL lectures.
- Reinforcement Learning from Human Feedback — Nathan Lambert. A free book on the full post-training stack (arXiv).
- Illustrating RLHF — Hugging Face. The pipeline in pictures.
- Welcome to the Era of Experience — Silver and Sutton, 2025. The case that agents will learn mainly from their own experience.
Where this leads¶
- RL with verifiable rewards — GRPO, DeepSeek-R1, and what RL with an exact reward actually changes in a model.
- DPO and direct preference optimisation — the offline branch in full, with its variants.
- RLHF with PPO — the online pipeline with a learned reward model.
- Reasoning models and test-time compute — what these training methods produce.
- Computer-use and long-horizon agents — where multi-turn RL is heading.