Reinforcement Learning, from Bellman to Agents

Deep dive · Reinforcement Learning · LLM Agents

Reinforcement Learning, from Bellman to Agents

The fundamentals of reinforcement learning, the line of ideas that runs from dynamic programming to RLHF and reasoning models, and how agentic RL for LLMs is researched, built and run in practice.

Reinforcement LearningRLHFReasoningAgentsML Systems

Summary

  • RL optimizes behavior from a scalar reward through trial and error. Every method here is a way to estimate the Bellman quantities (values, advantages) or the policy gradient with less bias, less variance or less compute.
  • The LLM lineage is short. Preference learning (2017) led to RLHF with PPO (2022) and then to DPO (2023). Verifiable rewards and critic-free GRPO (2024) led to reasoning models (o1, DeepSeek-R1). Multi-turn agentic RL on tools, code and the web followed (2025–26).
  • Most modern LLM RL is REINFORCE with a good baseline. PPO learns a critic; GRPO and RLOO replace it with statistics of several samples per prompt; DPO skips sampling altogether. Variants such as DAPO, Dr. GRPO, GSPO and CISPO mostly fix normalization, clipping and length biases.
  • Agentic RL changes the unit of work from one answer to a long trajectory in a stateful environment. Credit assignment, environment scaling (thousands of executable repos, browsers, VMs), tool-output masking and async rollout infrastructure become the main problems.
  • The systems side is about the generator–trainer gap: inference engines (vLLM, SGLang) in the loop, weight sync, async pipelines and the importance-sampling corrections they require. veRL, OpenRLHF, TRL, SkyRL, slime and AReaL are the common open stacks.
  • Rewards are evaluations, so everything that breaks evals breaks training: reward hacking, overoptimization, spurious rewards, contamination. Report pass@k curves, held-out environments and several seeds.
  • Whether RL teaches new skills or just sharpens what the base model already knows is still open, and so are long-horizon credit assignment and rewards for work that has no verifier.

Key Concepts

The core ideas of this book, one card each: a definition, an explanation from basics, why it matters, a common misconception and a diagram. Click a card, or any dotted-underlined term with a badge in the text, to open it in the side panel. To add your own, highlight any phrase and choose Key Concept.

Introduction

Reinforcement learning (RL) is learning to act from consequences. An agent takes actions in an environment, receives scalar rewards, and adjusts its behavior to collect more reward over time.

Supervised learning is told the right answer. An RL agent is only told how good its answer was, often much later. It has to work out for itself which of its many decisions deserve the credit.

For a decade, RL's public successes were games and robots: Atari from pixels, Go, a robot hand solving a Rubik's cube. Since 2022 its center of gravity has moved to language models:

  • Chat. RL from human feedback made chat assistants usable.
  • Reasoning. RL on verifiable rewards produced reasoning models that think for thousands of tokens before answering.
  • Agents. In 2025–2026, RL became the main tool for training agents: models that search, run code, edit repositories and drive browsers over dozens to hundreds of turns.

The algorithms are mostly old, but the scale and the systems around them are new.

This post starts from the fundamentals and climbs:

  • Foundations covers the lineage, MDPs and a taxonomy of RL settings.
  • Classic RL derives the algorithms LLM RL still borrows from.
  • RL for LLMs covers RLHF, reward models and DPO.
  • Reasoning RL covers verifiable rewards, GRPO and its relatives, and the debate about what RL adds.
  • Agentic RL covers multi-turn, tool-use, coding and web agents.
  • Systems covers frameworks, inference engines and async training.
  • Failure Modes covers reward hacking and evaluation protocols.
  • Practice gives a reference architecture, a challenges-to-solutions table, a playbook and applications.
  • Outlook lists open problems.

The structure follows Lilian Weng's long-form notes. Her post on reward hacking is a good companion.

Notation

\(s_t, a_t, r_t\): state, action, reward at step \(t\). \(\pi_\theta(a\mid s)\): policy with parameters \(\theta\). \(\gamma \in [0,1]\): discount. \(G_t\): return. \(V^\pi, Q^\pi, A^\pi\): state value, action value, advantage.

For LLMs, \(x\) is a prompt, \(y\) a response and \(y_t\) its \(t\)-th token. \(\pi_{\text{ref}}\) is a frozen reference policy and \(r_\phi\) a learned reward model. \(G\) (or \(K\)) is the number of samples per prompt.

Lineage: Where Modern RL Comes From

Agentic RL for LLMs looks new, but it descends from six threads that are each decades old. Knowing them turns the alphabet soup of 2025 (GRPO, DAPO, RLOO, GSPO) into a handful of recognizable moves.

Six lineages of reinforcement learning converging on agentic RL for LLMs, 1950 to 2026.
Fig. Six threads that converge on agentic RL for LLMs. Each lane runs from its root to its LLM-era descendant; the time axis is compressed before 2012. Years are first public release (arXiv or journal).
  1. Dynamic programming and value learning. Bellman's equation (1950s) breaks a sequential decision into "reward now plus value of what comes next". The Markov decision process made it a standard model. Sutton (1988) showed how to learn values from experience by bootstrapping (TD learning). Watkins & Dayan (1992) analyzed off-policy Q-learning, and DQN (Mnih et al. 2013) scaled it to Atari pixels.
  2. Policy gradients. REINFORCE (Williams 1992) follows the gradient of expected reward directly. The policy gradient theorem (Sutton et al. 1999) made it rigorous with function approximation. TRPO (2015) and PPO (2017) made it stable, and PPO became the default optimizer of RLHF.
  3. Search and self-play. AlphaGo (2016), AlphaZero (2017) and MuZero (2019) paired learned policies and values with tree search. They are the template for "spend compute at test time, then distill it into the policy", an idea reasoning models revived.
  4. Learning from human feedback. Christiano et al. (2017) learned a reward model from pairwise human preferences. Summarization (2020) and InstructGPT (2022) turned it into the RLHF recipe. Constitutional AI (2022) replaced many human labels with AI feedback, and DPO (2023) removed the RL loop entirely.
  5. Verifiable rewards and reasoning. The thread runs from process-versus-outcome supervision (Uesato et al. 2022; Lightman et al. 2023) to GRPO (2024), o1 (2024) and DeepSeek-R1 (2025). The core move: reward the model when a checker says the answer is right, and long chains of thought emerge.
  6. Agentic, multi-turn RL. Language agents became RL agents again. Key works include ArCHer (2024) for multi-turn credit assignment, Search-R1 (2025) for tool use, SWE-Gym and DeepSWE for coding agents, and frameworks such as SkyRL-Agent (2025) for long-horizon training at scale.

The LLM era (2022 onward) uses all six threads:

  • the MDP formalism and advantage estimation from value learning;
  • PPO from policy gradients;
  • test-time search from AlphaZero;
  • reward models from human feedback;
  • checkers from software testing and math;
  • environments from classic RL.

A seventh thread runs underneath all of them as a warning. Goodhart's law (1975) says that a measure stops measuring once it becomes a target.

The RL Problem

A Markov decision process (MDP) is a tuple \((\mathcal{S}, \mathcal{A}, P, R, \gamma)\): states, actions, a transition kernel \(P(s'\mid s,a)\), a reward function \(R(s,a)\), and a discount \(\gamma\). "Markov" means the next state depends only on the current state and action.

Often the agent cannot see the full state: a web page hides the server, a repository hides the test suite. The problem is then a partially observable MDP, and the agent conditions on its history of observations instead.

The agent-environment loop: the agent sends an action, the environment returns the next state and a reward. Agent policy π(a | s) (an LLM + scaffold) Environment P(s′ | s, a), R(s, a) (game · repo · browser · user) action aₜ next state sₜ₊₁, reward rₜ₊₁ trajectory τ = (s₀, a₀, r₁, s₁, a₁, r₂, …) · objective: maximize 𝔼[Σ γᵗ rₜ₊₁]
Fig. The agent–environment loop. For an LLM agent, an "action" can be a token, a tool call or a whole turn, and the environment can be a math checker, a container or a simulated user.

Returns, Values and Advantages

The agent maximizes the expected return, the discounted sum of future rewards. Value functions summarize expected return so that a decision can be judged without waiting for the episode to end.

\[ G_t = \sum_{k=0}^{\infty} \gamma^k r_{t+k+1}, \qquad V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s], \qquad Q^\pi(s,a) = \mathbb{E}_\pi[G_t \mid s_t = s, a_t = a]. \]

\(V^\pi(s)\) is how good it is to be in state \(s\) and follow \(\pi\) afterwards. \(Q^\pi(s,a)\) is how good it is to take action \(a\) first.

Their difference is the advantage, \(A^\pi(s,a) = Q^\pi(s,a) - V^\pi(s)\). It says how much better \(a\) is than the policy's average action. Almost every policy-gradient method in this post, from PPO to GRPO, is a different estimator of \(A\).

Bellman Equations

Bellman equations express a value as an immediate reward plus the discounted value of the successor state. This recursive structure is what makes RL tractable: values can be learned from one-step transitions instead of whole episodes.

\[ V^\pi(s) = \sum_a \pi(a\mid s)\Big[R(s,a) + \gamma \sum_{s'} P(s'\mid s,a)\, V^\pi(s')\Big], \qquad Q^*(s,a) = R(s,a) + \gamma \sum_{s'} P(s'\mid s,a)\, \max_{a'} Q^*(s',a'). \]

The first is the expectation equation for a fixed policy. The second is the optimality equation; its solution \(Q^*\) gives the optimal policy \(\pi^*(s) = \arg\max_a Q^*(s,a)\). With a known model, value iteration and policy iteration solve them by dynamic programming. RL solves them from samples when the model is unknown, which is the normal case.

Exploration vs. Exploitation

An agent only learns about actions it tries, so it must balance exploiting what it knows against exploring to learn more. The cleanest version is the multi-armed bandit, solved by strategies such as ε-greedy, upper confidence bounds and Thompson sampling.

For LLMs, exploration is mostly inherited. The pretrained model defines which responses are likely. Sampling temperature and the number of samples per prompt decide how widely the policy searches.

This makes exploration in LLM RL unusual. A prompt whose answer the model never samples gives no learning signal at all. That is why three topics matter so much:

A Taxonomy of RL Settings

"RL" covers very different training setups, and most confusion in interviews comes from mixing them up. Five distinctions do most of the work:

  • Data source. Where the data comes from.
  • Policy match. Whether the data matches the current policy.
  • World model. Whether the agent learns a model of the world.
  • What is learned. Values, policies or both.
  • Episode shape. For LLMs, whether an episode is one response or many turns.
AxisOptionsWhat changesLLM-era examples
Data sourceOnline vs. offlineOnline collects fresh rollouts; offline learns from a fixed dataset and must avoid actions the data never coveredGRPO with live sampling vs. DPO on a fixed preference set
Policy matchOn-policy vs. off-policyOn-policy needs data from the current policy; off-policy reuses old or foreign data with correctionsPPO/GRPO (nearly on-policy) vs. async RL with stale rollouts, replay buffers
World modelModel-free vs. model-basedModel-based learns or is given \(P\) and plans with itMost LLM RL is model-free; MCTS-style search and world-model agents are model-based
What is learnedValue-based, policy-based, actor-criticLearn \(Q\) and act greedily; learn \(\pi\) directly; or learn bothPPO (actor-critic) vs. GRPO/RLOO (policy-only with sampled baselines)
Episode shapeSingle-turn vs. multi-turnSingle-turn is a contextual bandit over whole responses; multi-turn interleaves model actions with environment observationsMath RLVR (single-turn) vs. SWE, search and GUI agents (multi-turn)
Reward sourceVerifiable, learned, judgedProgrammatic checkers are precise but narrow; reward models and judges are broad but hackableUnit tests, exact match; Bradley–Terry RMs; rubric-based LLM judges

Table. Six axes for classifying RL setups. A typical 2026 agentic run is online, mildly off-policy (async), model-free, policy-only, multi-turn, and uses mostly verifiable rewards.

A two-by-two map of RL settings by data source and episode horizon. DATA SOURCE → fixed dataset (offline) live interaction (online) HORIZON → multi-step single-step Offline RL · imitation CQL, behavior cloning, filtered SFT on logged agent trajectories; rejection-sampled agent traces risk: actions the data never covered Online multi-turn RL DQN/PPO on games and robots; AlphaZero self-play; agentic RL on search, SWE, web and GUI tasks risk: credit assignment, cost of environments Offline preference learning reward-model training; DPO and other direct alignment methods on fixed (chosen, rejected) pairs risk: distribution shift from the data policy Online single-turn RL contextual bandits; RLHF with PPO; GRPO/RLOO with verifiable rewards on math and code answers risk: reward hacking, overoptimization
Fig. Four regions of the RL design space. LLM post-training moved clockwise from the bottom-left (offline preferences) through the bottom-right (single-turn RLVR) to the top-right (online multi-turn agents) between 2023 and 2026.

One point is a common interview question. Single-turn LLM RL is a contextual bandit when the whole response is treated as one action and the reward arrives only at the end.

It becomes a genuine multi-step MDP when each token is treated as an action. The state is then the prompt plus the tokens so far, and transitions are deterministic. The two views give the same optimum but different estimators. That difference explains most of the PPO-versus-GRPO debate.

Value-Based Methods

Value-based methods learn \(V\) or \(Q\) from experience and derive behavior from it. Their key trick is bootstrapping: updating an estimate toward another estimate, instead of waiting for the true return. Bootstrapping lowers variance and allows learning from incomplete episodes, at the cost of bias when the estimates are wrong.

Temporal-Difference Learning

Sutton (1988) introduced temporal-difference (TD) learning, which updates a prediction toward the next prediction rather than toward the final outcome. The one-step TD error is the workhorse quantity of all of RL:

\[ \delta_t = r_{t+1} + \gamma V(s_{t+1}) - V(s_t), \qquad V(s_t) \leftarrow V(s_t) + \alpha\, \delta_t. \]

Here \(\alpha\) is a step size. If \(V\) were exact, \(\delta_t\) would be zero on average.

Monte Carlo methods use the full return \(G_t\) instead of \(r_{t+1} + \gamma V(s_{t+1})\). That target is unbiased but noisy. TD(\(\lambda\)) interpolates between the two with eligibility traces. This is the same interpolation that GAE later applies to advantages. The standard reference for all of this is Sutton & Barto (2018).

Q-Learning and DQN

Q-learning learns the optimal action-value function directly, using the max over next actions as its target. Watkins introduced it in his 1989 thesis and Watkins & Dayan (1992) proved convergence for tabular cases:

\[ Q(s_t,a_t) \leftarrow Q(s_t,a_t) + \alpha\big[r_{t+1} + \gamma \max_{a'} Q(s_{t+1},a') - Q(s_t,a_t)\big]. \]

Because the target uses \(\max_{a'}\) rather than the action the agent actually took, Q-learning is off-policy: it can learn the greedy policy from data collected by any exploratory policy.

Mnih et al. (2013) scaled this to Atari with a convolutional network (DQN). The 2015 Nature version stabilized it with two ideas still used everywhere:

  • Experience replay: store transitions in a buffer and sample minibatches at random, breaking temporal correlation.
  • Target networks: compute the bootstrap target with a slowly updated copy of the network, so the target does not chase itself.

Value-based methods dominate when actions are few and discrete. They are awkward for LLMs: the action space is a 100k-token vocabulary per step, and maximizing over whole responses is intractable. That is why LLM RL is almost entirely policy-gradient based, with values appearing only as baselines.

Policy Gradients and Actor-Critic

Policy-gradient methods parameterize the policy \(\pi_\theta\) and do gradient ascent on expected return \(J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[G_0]\). They handle huge or continuous action spaces naturally, because they never maximize over actions. They only need to sample actions and compute log-probabilities, which is exactly what a language model does.

The Policy Gradient Theorem

The policy gradient theorem says the gradient of expected return can be estimated from samples, without differentiating through the environment:

\[ \nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\Big[\sum_{t} \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, \Psi_t \Big], \]

where \(\Psi_t\) can be the return \(G_t\) (REINFORCE, Williams 1992), \(Q^\pi(s_t,a_t)\), the advantage \(A^\pi(s_t,a_t)\), or the TD error \(\delta_t\). The version with function approximation is due to Sutton et al. (1999). Intuitively, it pushes up the log-probability of actions in proportion to how good they turned out to be.

Deeper Deriving the policy gradient (the log-derivative trick)

Write the objective as an integral over trajectories: \(J(\theta) = \int p_\theta(\tau)\, R(\tau)\, d\tau\), where \(p_\theta(\tau) = p(s_0)\prod_t \pi_\theta(a_t\mid s_t) P(s_{t+1}\mid s_t,a_t)\) and \(R(\tau) = \sum_t \gamma^t r_{t+1}\).

Step 1, log-derivative trick. Since \(\nabla p = p\,\nabla \log p\),

\[ \nabla_\theta J = \int p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau)\, R(\tau)\, d\tau = \mathbb{E}_{\tau}\big[\nabla_\theta \log p_\theta(\tau)\, R(\tau)\big]. \]

Step 2, dynamics drop out. \(\log p_\theta(\tau) = \log p(s_0) + \sum_t \log \pi_\theta(a_t\mid s_t) + \sum_t \log P(s_{t+1}\mid s_t,a_t)\). Only the middle sum depends on \(\theta\), so \(\nabla_\theta \log p_\theta(\tau) = \sum_t \nabla_\theta \log \pi_\theta(a_t\mid s_t)\). The environment can be a black box: a compiler, a browser, a human.

Step 3, causality. An action at time \(t\) cannot affect rewards before \(t\). Terms pairing \(\nabla \log \pi(a_t\mid s_t)\) with earlier rewards have zero expectation, so \(R(\tau)\) can be replaced by the reward-to-go \(G_t\). This is the first variance reduction.

Step 4, baselines. For any \(b(s_t)\) that does not depend on \(a_t\), \(\mathbb{E}_{a_t \sim \pi}[\nabla_\theta \log \pi_\theta(a_t\mid s_t)\, b(s_t)] = b(s_t)\nabla_\theta \sum_a \pi_\theta(a\mid s_t) = b(s_t) \nabla_\theta 1 = 0\).

Subtracting a baseline therefore leaves the gradient unbiased. With \(b \approx V^\pi\), it can cut variance a lot. Using \(G_t - V(s_t)\) gives an advantage estimate. Every critic-free LLM method (RLOO, GRPO) is a choice of \(b\) built from other samples of the same prompt.

For an LLM with a single terminal reward \(r(x,y)\) and \(\gamma = 1\), every token gets the same \(\Psi_t = r(x,y) - b(x)\), and the estimator reduces to \(\big(r(x,y) - b(x)\big)\nabla_\theta \log \pi_\theta(y\mid x)\).

Actor-Critic and Advantage Estimation

Actor-critic methods learn a value function (the critic) alongside the policy (the actor), and use it to build low-variance advantage estimates. The critic turns a sparse, delayed reward into a dense per-step signal, which is useful exactly when episodes are long.

Mnih et al. (2016) showed that asynchronous actor-learners running in parallel (A3C) stabilize training without replay. The actor-critic variant was the best of the four algorithms they parallelized. The critic is trained by regression toward bootstrapped targets, and the actor follows \(\nabla \log \pi \cdot \hat{A}\).

Generalized Advantage Estimation

Schulman et al. (2015b) proposed generalized advantage estimation (GAE), an exponentially weighted sum of TD errors that trades bias for variance with one parameter \(\lambda\):

\[ \hat{A}^{\text{GAE}(\gamma,\lambda)}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}, \qquad \delta_t = r_{t+1} + \gamma V(s_{t+1}) - V(s_t). \]

With \(\lambda = 0\) the advantage is the one-step TD error: low variance, but biased if \(V\) is wrong. With \(\lambda = 1\) it is the Monte Carlo return minus the baseline: unbiased, high variance.

RLHF implementations commonly use \(\gamma = 1\) and \(\lambda\) near 0.95 or even 1. Two reasons drive this choice: responses are short relative to Atari episodes, and the critic is weak early in training.

Weight that GAE places on the TD error l steps ahead, for several values of lambda.
Fig. How far GAE looks ahead. The weight on \(\delta_{t+l}\) is \((\gamma\lambda)^l\), shown for \(\gamma = 0.99\). Small \(\lambda\) trusts the critic after a step or two; \(\lambda = 1\) sums all future TD errors, which telescopes to the Monte Carlo return. Drawn from the formula.

GAE is computed in one backward pass over a trajectory. The snippet below is the version used, with small differences, in most PPO implementations:

import numpy as np

def gae(rewards, values, dones, gamma=0.99, lam=0.95):
    """rewards[t], dones[t] for t=0..T-1; values has length T+1 (bootstrap V(s_T))."""
    T = len(rewards)
    adv = np.zeros(T, dtype=np.float32)
    last = 0.0
    for t in reversed(range(T)):
        nonterminal = 1.0 - dones[t]
        delta = rewards[t] + gamma * values[t + 1] * nonterminal - values[t]
        last = delta + gamma * lam * nonterminal * last
        adv[t] = last
    returns = adv + values[:-1]          # regression targets for the critic
    return adv, returns

Trust Regions and PPO

Vanilla policy gradients are fragile. One large step can collapse the policy. Because the policy generates its own data, a bad policy produces bad data and may never recover. Trust-region methods limit how far each update can move the policy, measured in KL divergence or likelihood ratio rather than parameter distance.

TRPO

Schulman et al. (2015a) proposed trust region policy optimization (TRPO), which maximizes a surrogate objective subject to a KL constraint:

\[ \max_\theta\; \mathbb{E}_t\!\left[\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_{\text{old}}}(a_t\mid s_t)}\hat{A}_t\right] \quad \text{s.t.}\quad \mathbb{E}_t\big[D_{\mathrm{KL}}(\pi_{\theta_{\text{old}}}(\cdot\mid s_t)\,\|\,\pi_\theta(\cdot\mid s_t))\big] \le \delta. \]

The ratio \(\rho_t = \pi_\theta/\pi_{\theta_{\text{old}}}\) is an importance weight that lets data from the old policy estimate the gradient of the new one. Solving the constrained problem needs conjugate gradients and a line search, which is expensive and hard to combine with large networks.

PPO and the Clipped Objective

Schulman et al. (2017) replaced the constraint with clipping. Proximal policy optimization (PPO) takes several minibatch epochs over each batch of rollouts and maximizes

\[ L^{\text{CLIP}}(\theta) = \mathbb{E}_t\Big[\min\big(\rho_t(\theta)\hat{A}_t,\; \text{clip}(\rho_t(\theta), 1-\epsilon, 1+\epsilon)\,\hat{A}_t\big)\Big], \]

with \(\epsilon\) typically 0.2. The clip works in both directions:

  • Positive advantage. The objective stops rewarding increases of the action's probability beyond \(1+\epsilon\) times the old one.
  • Negative advantage. It stops rewarding decreases below \(1-\epsilon\).

The min makes the objective a pessimistic bound: clipping can only remove incentive, never add it. The full PPO loss adds a value-function regression term and usually an entropy bonus.

The PPO clipped surrogate objective as a function of the probability ratio, for positive and negative advantage.
Fig. The PPO clipped surrogate for a single token, with \(\epsilon = 0.2\) and \(\hat A = \pm 1\). Solid: the clipped objective; dashed: the unclipped \(\rho \hat A\). The flat regions have zero gradient, so tokens that have already moved far enough stop contributing. Drawn from the formula; the shape follows Fig. 1 of Schulman et al. 2017.
import torch

def ppo_policy_loss(logp_new, logp_old, adv, mask, eps_low=0.2, eps_high=0.2):
    """Token-level PPO loss. All tensors are [batch, seq]; mask is 1 on trained tokens.
    eps_high > eps_low gives DAPO-style 'clip-higher'."""
    ratio = torch.exp(logp_new - logp_old)
    unclipped = ratio * adv
    clipped = torch.clamp(ratio, 1 - eps_low, 1 + eps_high) * adv
    per_token = -torch.minimum(unclipped, clipped)
    # token-level mean over the whole batch (DAPO); per-sequence means reintroduce length bias
    loss = (per_token * mask).sum() / mask.sum().clamp(min=1)
    clip_frac = (((ratio < 1 - eps_low) | (ratio > 1 + eps_high)).float() * mask).sum() / mask.sum()
    return loss, clip_frac.detach()

PPO's empirical success depends on many details beyond the objective. Andrychowicz et al. (2020) implemented more than 50 design choices in one on-policy framework. They trained over 250,000 agents to measure which choices matter.

Henderson et al. (2017) showed how much reported deep RL results vary with implementation and evaluation choices. Both lessons transferred directly to LLM RL, where "the same algorithm" in two frameworks can behave very differently.

Off-Policy, Max-Entropy and Offline RL

On-policy methods throw data away after one or a few updates. Off-policy methods reuse it, and offline methods learn from a fixed dataset with no interaction at all. Three ideas from this branch matter for LLM agents: entropy regularization, importance-weighted corrections for stale data, and conservatism when the data does not cover the policy.

  • Maximum entropy RL. Haarnoja et al. (2018) introduced soft actor-critic (SAC), which maximizes reward plus policy entropy with an off-policy actor-critic. It became the default for continuous control. The idea that entropy is a resource to preserve reappears as entropy collapse in reasoning RL.
  • Importance-weighted off-policy correction. Espeholt et al. (2018) built IMPALA, which decouples many actors from a central learner and corrects for the lag between them with V-trace, a truncated importance-sampling estimator. This is the direct ancestor of async LLM RL corrections.
  • Offline RL. Levine et al. (2020) surveyed learning from fixed datasets. They identified distribution shift as the core problem: the learned policy picks actions the data never covered, and value estimates there are wrong. Conservative Q-learning (Kumar et al. 2020) addresses it by pushing down Q-values on unseen actions. DPO and rejection-sampling fine-tuning are offline methods in this sense, and they inherit the same weakness.

Search, Self-Play and Planning

The AlphaGo line showed that RL becomes much stronger when combined with search. The policy proposes moves, search improves on them, and the policy is then trained to imitate the improved choices.

This "policy improvement through search, then distillation" loop is the conceptual ancestor of test-time scaling and of training reasoning models on their own best samples.

  • Silver et al. (2016) combined policy and value networks, trained by supervised learning on human games and then by self-play RL, with Monte Carlo tree search to master Go.
  • AlphaZero (Silver et al. 2017) removed human data entirely and learned chess, shogi and Go from self-play, using MCTS visit counts as policy targets and game outcomes as value targets.
  • MuZero (Schrittwieser et al. 2019) learned a model of the environment's dynamics and planned with it, reaching top performance without being given the rules.

Bolting MCTS (Monte Carlo tree search) onto LLM reasoning gave mixed results. Kimi k1.5 and DeepSeek-R1 both reported strong results without tree search or process reward models. The idea survived in another form: long chains of thought behave like a search the model performs inside its own context.

The Language Model as a Policy

A language model is already a stochastic policy: given a prompt \(x\) and the tokens generated so far, it outputs a distribution over the next token. RL fine-tuning keeps that policy and changes which responses it prefers, using a reward that scores whole responses (or whole trajectories) rather than imitating reference text.

Two modelling choices recur:

  • Token-level MDP. The state is \((x, y_{<t})\) and the action is the token \(y_t\). Transitions are deterministic concatenation, and the reward is usually zero until the end-of-sequence token. PPO with a value head is natural in this view.
  • Sequence-level bandit. The whole response \(y\) is a single action with reward \(r(x,y)\). GRPO, RLOO and DPO are natural in this view.

Almost all LLM RL adds a KL penalty toward a reference model:

\[ \max_{\pi_\theta}\; \mathbb{E}_{x\sim\mathcal{D},\, y\sim\pi_\theta(\cdot\mid x)}\big[r(x,y)\big] \;-\; \beta\, D_{\mathrm{KL}}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big). \]

\(\pi_{\text{ref}}\) is usually the supervised (SFT) model and \(\beta\) sets how far the policy may drift. The KL term does three jobs:

  • it keeps the policy in the region where the reward is trustworthy;
  • it preserves fluency and diversity;
  • as the DPO derivation shows, it gives the problem a closed-form solution.

The RLHF Pipeline

RLHF turns human judgments of "which response is better" into a reward function and then optimizes the policy against it. Christiano et al. (2017) introduced the idea for Atari and simulated robotics, where humans compared short clips of behavior.

Ziegler et al. (2019) applied it to language, Stiennon et al. (2020) to summarization, and Ouyang et al. (2022) to instruction following.

The three-stage RLHF pipeline: supervised fine-tuning, reward modelling from preference pairs, and KL-regularized RL. ① SFT pretrained LM + demonstrations → π_SFT ② Preferences sample 2+ responses, labelers rank them → (x, y_w, y_l) ③ Reward model Bradley–Terry loss on pairs → r_φ(x, y) ④ RL (PPO) maximize r_φ − β · KL(π ‖ π_ref) → π_RLHF Reference π_ref frozen copy of π_SFT copy weights (also initializes the policy) KL
Fig. The canonical RLHF pipeline. Stage ② is often repeated online: new policy samples are labelled and the reward model retrained. The stages follow Ouyang et al. 2022; the drawing is original.

Ouyang et al. (2022) reported several findings that shaped the field:

  • Labelers preferred outputs of a 1.3B-parameter InstructGPT model over those of the 175B-parameter GPT-3 on the authors' prompt distribution. The smaller model had roughly 100× fewer parameters. Alignment training was cheap relative to pretraining.
  • The recipe was SFT on demonstrations, a reward model trained on rankings, then PPO against it with a per-token KL penalty to the SFT model.
  • RLHF made models better at following instructions on the prompt distribution it was trained on. It did not make them more capable in general, and could cost some performance on public NLP benchmarks (an "alignment tax").

Bai et al. (2022a) trained helpful and harmless assistants with the same recipe. They retrained preference models and policies weekly on fresh feedback.

Bai et al. found a roughly linear relation between RL reward and the square root of the KL divergence from the initial policy. That was an early hint of the overoptimization scaling laws.

Preference Data

Preference data is the bottleneck of RLHF, and its collection choices matter more than the RL algorithm. Pairwise comparisons are used instead of absolute scores because people agree more on "A is better than B" than on "A is a 7".

  • On-policy samples. Pairs should come from the current policy, or the reward model will be accurate on responses the policy no longer produces. This is why iterated, online collection works better than a single offline round.
  • Labeler instructions and agreement. The guidelines define what "better" means (helpfulness, honesty, harmlessness). Inter-annotator agreement sets a ceiling on reward-model accuracy.
  • Coverage. Prompts should span the deployment distribution, including refusals and multi-turn conversations, or the reward model will extrapolate. Lambert's RLHF book covers these trade-offs in depth.

Reward Models

A reward model is usually the SFT model with its language-model head replaced by a scalar head, trained with the Bradley–Terry model of pairwise preferences:

\[ P(y_w \succ y_l \mid x) = \sigma\big(r_\phi(x,y_w) - r_\phi(x,y_l)\big), \qquad \mathcal{L}_{\text{RM}}(\phi) = -\mathbb{E}_{(x,y_w,y_l)}\big[\log \sigma\big(r_\phi(x,y_w) - r_\phi(x,y_l)\big)\big]. \]

\(y_w\) and \(y_l\) are the preferred and rejected responses and \(\sigma\) is the logistic function. Only reward differences are identified, so the scale and offset of \(r_\phi\) are arbitrary. Implementations normalize rewards or whiten advantages for that reason.

A reward model is a proxy learned from finite data, and the policy will find its errors. That is the subject of overoptimization.

PPO for Language Models

PPO for LLMs keeps four models in memory: the policy, a value model (often initialized from the reward model), the reward model, and the frozen reference. The KL penalty is usually folded into a per-token reward:

\[ 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_\phi(x,y). \]

GAE is then run over tokens with the value model as the critic, and the policy is updated with the clipped objective. This works, but it is heavy:

  • Memory. Four large models.
  • A hard critic. The critic must learn to predict the final reward from partial text.
  • Tuning. Many hyperparameters: \(\beta\), \(\epsilon\), \(\lambda\), value-loss weight, learning rates for actor and critic.

Most of the 2024–2025 algorithm work is about removing pieces of it.

Direct Preference Optimization

Rafailov et al. (2023) showed that the KL-regularized RLHF objective can be optimized without a reward model or RL. A simple classification loss on preference pairs gives the same optimum. Direct preference optimization (DPO) became the default alignment method for open models in 2023–2024, because it is as easy to run as SFT.

\[ \mathcal{L}_{\text{DPO}}(\theta) = -\mathbb{E}_{(x,y_w,y_l)}\left[\log\sigma\left(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\right)\right]. \]

The term \(\beta \log(\pi_\theta/\pi_{\text{ref}})\) acts as an implicit reward. The loss raises it for the chosen response and lowers it for the rejected one. The paper's title, "your language model is secretly a reward model", refers to this.

Deeper Deriving DPO from the KL-regularized objective

Step 1, closed-form optimum. For a fixed prompt \(x\), the objective \(\mathbb{E}_{y\sim\pi}[r(x,y)] - \beta D_{\mathrm{KL}}(\pi\|\pi_{\text{ref}})\) can be rewritten as \(-\beta\, D_{\mathrm{KL}}\big(\pi \,\|\, \tfrac{1}{Z(x)}\pi_{\text{ref}}\, e^{r/\beta}\big) + \beta \log Z(x)\). The KL is minimized (zero) when

\[ \pi^*(y\mid x) = \frac{1}{Z(x)}\,\pi_{\text{ref}}(y\mid x)\exp\!\Big(\tfrac{1}{\beta} r(x,y)\Big), \qquad Z(x) = \sum_y \pi_{\text{ref}}(y\mid x)\exp\!\Big(\tfrac{1}{\beta} r(x,y)\Big). \]

Step 2, invert for the reward. Taking logs, \(r(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x)\). The partition function \(Z(x)\) is intractable (a sum over all responses), but it depends only on \(x\).

Step 3, plug into Bradley–Terry. The preference probability depends only on reward differences for the same prompt, so \(\beta\log Z(x)\) cancels:

\[ P(y_w\succ y_l\mid x) = \sigma\!\left(\beta\log\frac{\pi^*(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta\log\frac{\pi^*(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\right). \]

Step 4, maximum likelihood. Parameterize \(\pi^*\) by \(\pi_\theta\) and maximize the likelihood of the observed preferences; the negative log-likelihood is \(\mathcal{L}_{\text{DPO}}\).

Gradient. \(\nabla_\theta\mathcal{L}_{\text{DPO}} = -\beta\,\mathbb{E}\big[\sigma(\hat r_l - \hat r_w)\,(\nabla\log\pi_\theta(y_w\mid x) - \nabla\log\pi_\theta(y_l\mid x))\big]\), with \(\hat r = \beta\log(\pi_\theta/\pi_{\text{ref}})\). Pairs the model already ranks correctly get small weight, so it focuses on mistakes.

Caveats. The derivation assumes the optimum over all distributions and a dataset that covers the responses that matter.

In practice DPO is offline: it never sees its own samples. It can therefore lower the likelihood of both chosen and rejected responses, and move probability to responses absent from the data.

Online or iterative DPO, which relabels fresh policy samples, closes much of the gap to online RL. Noukhovitch et al. (2024) found online DPO the most robust of the RLHF algorithms they tested to off-policy data.

AI Feedback and Constitutional AI

Human preference labels are slow and expensive. For some properties, such as harmlessness on adversarial prompts or expert correctness, they are also unreliable. RL from AI feedback (RLAIF) replaces many of those labels with judgments from a model guided by written principles.

  • Bai et al. (2022b) proposed Constitutional AI, which has two phases. In the supervised phase, the model critiques and revises its own responses against a list of principles. In the RL phase, an AI preference model trained on AI-labelled comparisons replaces human harmlessness labels.
  • Lee et al. (2023) compared RLAIF and RLHF directly on summarization and dialogue and found that AI-labelled preferences could reach performance comparable to human-labelled ones.

AI feedback is the ancestor of today's rubric-based and judge-based rewards for agentic tasks. Its main risk is that the policy learns to please the judge, which inherits the judge's blind spots.

RL with Verifiable Rewards

RL with verifiable rewards (RLVR) replaces the learned reward model with a program that checks the answer. Does the final number match? Do the unit tests pass? Does the proof check? The reward is binary or nearly so, cheap to compute, and much harder to hack than a neural reward model. Since 2024, this has been the main way reasoning capability is trained.

Lambert et al. (2024) named the approach in the Tülu 3 report. They applied RL after SFT and DPO, on prompts with checkable answers (math, precise instruction following).

DeepSeek-R1 made it famous. R1-Zero used only two rule-based rewards:

  • Accuracy reward. A boxed math answer or passing test cases.
  • Format reward. Reasoning placed inside <think> tags.

The authors avoided neural outcome and process reward models. They cited reward hacking and the extra cost of training them.

Verifiers look simple but carry most of the engineering risk:

  • Math: extract the final answer, normalize it (fractions, units, LaTeX), and compare symbolically. Too strict a checker rejects correct answers and adds noise; too loose a checker accepts guesses.
  • Code: run hidden tests in a sandbox with time and memory limits. Weak tests reward wrong programs; tests the model can see or edit reward tampering.
  • Instruction following: check constraints programmatically (word counts, formats, required keywords).
  • Agent tasks: check the final environment state (tests pass in the repo, the database row exists, the page shows the right value). See SWE agents.

GRPO: Group Relative Policy Optimization

Shao et al. (2024) introduced GRPO in DeepSeekMath as a PPO variant that drops the value model. For each prompt it samples a group of \(G\) responses, scores them, and uses the group's own statistics as the baseline.

GRPO became the default algorithm for RLVR because it removes the critic (the learned value model). The critic is the hardest-to-tune part of PPO for LLMs, so dropping it also cuts memory accordingly.

For prompt \(q\) with sampled outputs \(o_1,\dots,o_G\) and rewards \(r_1,\dots,r_G\), every token of output \(i\) gets the same advantage:

\[ \hat{A}_{i,t} = \frac{r_i - \operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}. \]

The policy is updated with a PPO-style clipped ratio per token. The loss is averaged first over tokens in each response, then over responses. A KL penalty to the reference policy is added directly to the loss rather than to the reward:

\[ \mathcal{J}_{\text{GRPO}}(\theta) = \mathbb{E}\left[\frac{1}{G}\sum_{i=1}^{G}\frac{1}{|o_i|}\sum_{t=1}^{|o_i|}\Big(\min\big(\rho_{i,t}\hat{A}_{i,t},\,\text{clip}(\rho_{i,t},1-\epsilon,1+\epsilon)\hat{A}_{i,t}\big) - \beta\, \mathbb{D}_{\mathrm{KL}}[\pi_\theta\|\pi_{\text{ref}}]\Big)\right]. \]

\(\rho_{i,t}\) is the ratio of new to old token probabilities and \(|o_i|\) the response length. The KL term is estimated per token with the unbiased "k3" estimator \(\frac{\pi_{\text{ref}}}{\pi_\theta} - \log\frac{\pi_{\text{ref}}}{\pi_\theta} - 1\).

DeepSeekMath 7B was trained with continued pretraining on 120B math tokens, then with GRPO. It reached 51.7% on the competition-level MATH benchmark, without tools or voting.

PPO versus GRPO: PPO uses a learned value model and GAE; GRPO samples a group of outputs and normalizes rewards within the group. PPO prompt q policy π_θ trained output o reward model r_φ (frozen) reference π_ref (frozen) value model V_ψ (trained) KL folded into per-token reward GAE → per-token Âₜ GRPO prompt q policy π_θ trained o₁ … o_G a group of G samples verifier or reward model reference π_ref (frozen) no value model · KL added to loss group norm Âᵢ = (rᵢ − μ) / σ the baseline comes from the other samples of the same prompt, not from a learned critic
Fig. PPO and GRPO side by side. GRPO trades the value model for more samples per prompt. (Adapted and redrawn from Shao et al. 2024.)

The Critic-Free Family: REINFORCE, RLOO and REINFORCE++

GRPO is one member of a family of methods that go back to REINFORCE. All of them estimate the baseline from other samples instead of learning a critic.

The family argues that PPO's machinery is not needed for LLMs, for three reasons:

  • The pretrained policy is already a good starting point.
  • Rewards arrive once per response.
  • The variance a critic removes can be removed more cheaply by sampling several responses per prompt.

RLOO: the Leave-One-Out Baseline

Kool et al. (2019) observed that with several samples per input, each sample's baseline can be built from the others "for free". This needs no learned value function and introduces no bias.

Ahmadian et al. (2024) revisited this for RLHF in "Back to Basics" (ACL 2024). They argued that many of PPO's components are unnecessary there:

  • They model the whole response as one action instead of treating each token as an action, so there is no per-token critic or GAE.
  • With \(K\) samples per prompt, the REINFORCE leave-one-out (RLOO) baseline for sample \(i\) is the mean reward of the other \(K-1\) samples.
  • They report that REINFORCE-style variants, including RLOO, outperformed PPO and RL-free methods such as DPO and RAFT in their RLHF experiments, at lower cost.
\[ \hat{A}_i = r_i - \frac{1}{K-1}\sum_{j\neq i} r_j = \frac{K}{K-1}\big(r_i - \bar{r}\big), \qquad \nabla_\theta J \approx \frac{1}{K}\sum_{i=1}^{K}\hat{A}_i\,\nabla_\theta\log\pi_\theta(y_i\mid x). \]

\(\bar r\) is the mean reward of all \(K\) samples. The baseline for \(y_i\) excludes \(r_i\), so it is independent of \(y_i\) and the estimator stays unbiased.

GRPO's group mean includes \(r_i\). This introduces a small bias (a factor \((K-1)/K\) on the gradient), which is harmless in practice. The second form of the equation shows that RLOO is just mean-centering rescaled by \(K/(K-1)\).

RLOO and GRPO differ in two practical ways:

  • No std division. RLOO does not divide by the standard deviation.
  • KL placement. In RLOO-style setups the KL penalty is usually folded into the reward, \(r'_i = r_i - \beta\,\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})\). GRPO adds it as a separate loss term.

The ms-swift documentation exposes exactly these two switches (ms-swift 3.10 or later). --advantage_estimator rloo selects the leave-one-out baseline, and --kl_in_reward true moves the KL into the reward. --num_generations sets \(K\).

The leave-one-out idea also travels beyond text. Gupta et al. (2025) studied RL fine-tuning of text-to-image diffusion models:

  • They found PPO sample-efficient but memory-hungry and sensitive to hyperparameters, and REINFORCE simpler but high-variance and sample-inefficient.
  • Their LOOP method combines the multiple-samples-per-prompt leave-one-out baseline with PPO's clipping and importance sampling.
  • They report a better balance of sample efficiency and final performance on several black-box objectives.

REINFORCE++ and Global Normalization

Hu (2025) proposed REINFORCE++. It also drops the critic, but changes three things relative to GRPO:

  • It keeps PPO's clipping and mini-batch updates.
  • It folds a token-level KL penalty into the reward.
  • It normalizes advantages over the whole batch rather than within each prompt's group.

The paper reports better stability than GRPO with Bradley–Terry reward models (learned pairwise-preference scorers). With these models, per-prompt normalization can amplify small, noisy reward differences. With rule-based rewards, the paper reports comparable results.

Advantages assigned to eight samples of one prompt under GRPO, RLOO and Dr. GRPO.
Fig. One prompt, eight samples, three correct (reward 1) and five wrong (reward 0). GRPO divides by the group standard deviation, RLOO uses the leave-one-out mean, and Dr. GRPO subtracts the mean only. All three rank the samples identically and differ only in scale. Scale matters when it varies across prompts: GRPO gives a nearly solved or nearly impossible prompt the same total update as a 50/50 prompt. Illustrative rewards; advantages computed from the formulas.
import numpy as np

def group_advantages(rewards, method="grpo", eps=1e-6):
    """rewards: [num_prompts, K] scalar rewards for K samples per prompt."""
    r = np.asarray(rewards, dtype=np.float64)
    K = r.shape[1]
    mean = r.mean(axis=1, keepdims=True)
    if method == "grpo":                     # Shao et al. 2024
        return (r - mean) / (r.std(axis=1, keepdims=True) + eps)
    if method == "dr_grpo":                  # Liu et al. 2025: no std division
        return r - mean
    if method == "rloo":                     # Kool et al. 2019; Ahmadian et al. 2024
        loo_mean = (r.sum(axis=1, keepdims=True) - r) / (K - 1)
        return r - loo_mean                  # == K/(K-1) * (r - mean)
    if method == "reinforce_pp":             # Hu 2025: global (batch) normalization
        a = r - mean                         # optional per-prompt centering
        return (a - a.mean()) / (a.std() + eps)
    raise ValueError(method)

r = np.array([[1, 0, 0, 1, 0, 0, 0, 1]])
for m in ["grpo", "rloo", "dr_grpo"]:
    print(m, np.round(group_advantages(r, m), 3))
# prompts where all K samples get the same reward yield zero advantage: filter them (DAPO)
MethodCritic?Baseline / advantageKL handlingSamples per promptOn-policy?
PPO (RLHF form)Yes, learned value modelGAE over tokens using \(V_\psi\)Per-token penalty folded into reward1 is enoughNear on-policy (a few epochs, clipped)
GRPONo\((r_i-\mu)/\sigma\) within the groupSeparate loss term (k3 estimator); often \(\beta = 0\) in 2025 recipes\(G\) (commonly 8–64)Near on-policy, clipped
RLOONo\(r_i\) minus mean of the other \(K-1\)Usually folded into the reward\(K \ge 2\)On-policy (REINFORCE); clipping optional
REINFORCE++NoReward minus summed KL, normalized over the batchToken-level, folded into the reward1 or moreNear on-policy, clipped
DPONo (no RL loop)Implicit reward \(\beta\log(\pi_\theta/\pi_{\text{ref}})\), chosen vs. rejectedBuilt into the objective via \(\pi_{\text{ref}}\)0 (fixed pairs); 2 if onlineOffline unless relabelled online

Table. Five policy-optimization methods used for LLMs. The critic-free methods differ mainly in how they build the baseline from samples and where they put the KL term.

Fixing GRPO: DAPO, Dr. GRPO, GSPO and CISPO

Once GRPO was used for long reasoning runs, several groups found that its normalizations and clipping produce systematic biases. The 2025 variants are mostly targeted fixes, and most frameworks now expose them as flags.

The biases fall into four groups:

  • overly long wrong answers;
  • collapsing entropy;
  • wasted samples;
  • instability on mixture-of-experts models.

Four variants address them:

  • Yu et al. (2025) released DAPO (ByteDance Seed and Tsinghua AIR). With Qwen2.5-32B it reached 50 points on AIME 2024. It needed half the training steps used for DeepSeek-R1-Zero-Qwen-32B, which scored 47 points. DAPO combines four techniques:
    • Clip-Higher: a larger upper clip bound so low-probability tokens can grow, against entropy collapse.
    • Dynamic Sampling: drop prompts whose samples are all right or all wrong, because they have zero advantage.
    • Token-level loss: average over all tokens in the batch, so long responses are not underweighted.
    • Overlong reward shaping: do not punish truncated responses as if they were wrong.
  • Liu et al. (2025) (Sea AI Lab) proposed Dr. GRPO ("GRPO done right"). It removes two normalizers:
    • Dividing by \(|o_i|\) gives short correct answers larger per-token updates and penalizes long wrong answers less. As a result, wrong answers grow longer.
    • Dividing by the group std overweights prompts that are nearly always or nearly never solved.
    Removing both terms kept accuracy and improved token efficiency. Their minimal recipe reached 43.3% on AIME 2024 from a 7B base model. Training took about 27 hours on 8 A100s.
  • The Qwen team (2025) proposed GSPO. It computes the importance ratio from the whole sequence likelihood and clips at the sequence level. They report that it stabilizes RL for mixture-of-experts models and contributed to the Qwen3 models.
  • MiniMax (2025) introduced CISPO in MiniMax-M1. It clips the importance-sampling weights instead of dropping the gradient of clipped tokens. Rare but important tokens (such as "wait" or "however" at a reflection point) therefore still contribute. The model has 456B parameters (45.9B active). Its full RL training ran on 512 H800 GPUs for about three weeks, at an estimated rental cost of about $535k.
VariantWhat it changesProblem addressedTRL / veRL flag (as of 2026)
DAPO\(\epsilon_{\text{high}} > \epsilon_{\text{low}}\); filter zero-variance groups; token-level mean; overlong maskingEntropy collapse, wasted batch, length bias, truncation noiseloss_type="dapo"; DAPO recipe
Dr. GRPONo \(1/|o_i|\), no \(1/\sigma\); constant normalizerLong wrong answers; difficulty biasloss_type="dr_grpo", scale_rewards=False
GSPOSequence-level ratio and clippingToken-ratio noise; MoE instabilityGSPO supported in veRL
CISPOClip the IS weight, keep every token's gradientClipping silences rare reflective tokens"cispo" loss in TRL
RLOO / REINFORCE++Leave-one-out or global baselinesBias of in-group mean; RM noise amplification--advantage_estimator rloo (ms-swift); RLOO, REINFORCE++ in veRL/OpenRLHF

Table. GRPO variants and what they fix. Flag names are taken from the TRL GRPO docs, the veRL README and the ms-swift docs; check your version, as defaults change often.

Deeper GRPO vs. PPO in detail: where the biases come from

Same estimator family. Drop clipping and KL and take one gradient step per batch. GRPO then reduces to REINFORCE with baseline \(b(q) = \mu_q\) and a per-prompt scale \(1/\sigma_q\).

PPO with \(\gamma = \lambda = 1\) and a perfect critic gives per-token advantages \(r - V(q, o_{<t})\). Here the baseline changes along the response as the critic updates its expectation. That is PPO's real advantage, within-response credit assignment, and it matters most in long multi-turn episodes. Its real cost is that the critic must be accurate, and early in training it is not.

Length bias. GRPO's \(\frac{1}{|o_i|}\sum_t\) means each token's gradient weight is \(\hat A_i/|o_i|\). For a wrong answer (\(\hat A_i<0\)), longer responses spread the penalty over more tokens, so each token is pushed down less. The policy can therefore lower its loss by making wrong answers longer.

Two fixes exist. DAPO's token-level mean, \(\frac{1}{\sum_i |o_i|}\sum_i\sum_t\), weights every token equally across the batch. Dr. GRPO's constant normalizer \(1/(G\cdot L_{\max})\) removes the dependence on length entirely.

Difficulty bias. With binary rewards and success rate \(p\) in a group, \(\sigma = \sqrt{p(1-p)}\). Dividing by it multiplies the update by \(1/\sqrt{p(1-p)}\), which grows without bound as \(p \to 0\) or \(1\).

So a prompt solved 1 time in 64 gets as much total push as one solved 32 times in 64. Sometimes that is desirable, because it focuses on rare successes. It also amplifies verifier noise on near-solved prompts.

Zero-variance groups. If all \(G\) samples have the same reward, every advantage is 0 and the prompt contributes nothing except KL and entropy terms. As the policy improves, more prompts saturate and the effective batch shrinks. DAPO oversamples and filters; curricula that keep prompts near 50% success do the same job upstream.

Clipping asymmetry. Take \(\epsilon = 0.2\). A token at probability 0.01 can only rise to 0.012 per update, while a token at 0.9 can fall to 0.72. Exploration tokens are capped hardest. That is why Clip-Higher raises \(\epsilon_{\text{high}}\) and CISPO keeps gradients for clipped tokens.

KL. Many 2025 reasoning recipes set \(\beta = 0\) (TRL's default is now 0). Their argument: a verifiable reward is hard enough to hack that the reference anchor mostly slows learning.

ProRL argued the opposite for very long runs. It kept KL control and periodically reset the reference policy to the current one. With learned or judged rewards, keep the KL term.

Reasoning Models

Reasoning models are LLMs trained with large-scale RL to produce long chains of thought before answering, and to get better as they are allowed to think longer. They showed that RL could change behavior qualitatively (planning, checking, backtracking), not just tune style.

  • OpenAI (2024) introduced o1 in September 2024, describing a large-scale RL algorithm that teaches the model to use its chain of thought productively. Performance improved with both more RL training compute and more thinking time at test time.
  • DeepSeek-AI (2025) published DeepSeek-R1 in January 2025, later in Nature.
    • R1-Zero. GRPO with rule-based rewards was applied directly to the base model. AIME 2024 pass@1 (the success rate of a single sample) rose from 15.6% to 71.0% during training. With majority voting over 64 samples it reached 86.7%.
    • Emergent behavior. Responses grew longer, and the authors reported an "aha moment" where the model paused to re-check its work.
    • Released R1. R1-Zero's outputs mixed languages and were hard to read. The released R1 therefore added a cold-start SFT stage, a language-consistency reward, rejection-sampled SFT on about 800k samples, and a final RL stage covering general prompts.
  • Kimi Team (2025) released Kimi k1.5 the same week, with long-context RL and improved policy optimization but, explicitly, no MCTS, value functions or process reward models. They also introduced "long2short" methods to transfer long-CoT gains into shorter responses.
  • MiniMax-M1 (2025) scaled hybrid-attention reasoning models with CISPO and published its RL compute bill. Such cost disclosures are still rare.

Distillation turned out to be the cheap path to small reasoning models. Smaller dense models fine-tuned on R1's long-CoT traces gained much of the capability, without any RL on the small models. The pattern of "RL a large model, then distill" repeated through 2025–2026.

Process vs. Outcome Rewards and Test-Time Scaling

An outcome reward scores only the final answer, while a process reward scores each intermediate step. Process rewards give denser credit assignment and can catch right answers reached by wrong reasoning. But they are expensive to label and, when learned, easy for the policy to exploit.

  • Uesato et al. (2022) compared process- and outcome-based feedback on grade-school math. Final-answer accuracy was similar, but process supervision (or a reward model that imitated it) was needed to reduce reasoning errors in solutions with correct answers.
  • Lightman et al. (2023) collected PRM800K, a dataset of step-level human labels on MATH solutions, and found that a process reward model reranked best-of-N samples better than an outcome reward model.
  • Snell et al. (2024) studied how to spend test-time compute: searching against process verifiers, or revising responses sequentially. A compute-optimal, difficulty-adaptive strategy was more than 4× more efficient than best-of-N. On problems where a small model had non-trivial success, test-time compute could beat a 14× larger model at matched FLOPs.

In practice, 2025 frontier RL mostly used outcome rewards for training. Process models were kept for test-time reranking or for monitoring.

Long chains of thought make outcome rewards workable. The model learns to check its own steps, which gives a kind of self-supervised process signal.

What RL Adds, and What It Doesn't

The sharpest open question in reasoning RL is whether RLVR teaches the model new capabilities or mostly makes it reliably produce answers it could already sample. The evidence points both ways. The honest answer in late 2026 is "mostly sharpening, sometimes more, depending on the base model, the data and how long you train".

  • Yue et al. (2025) compared base and RLVR-trained models with pass@k (the chance that at least one of k samples is correct) at large k. RL models won at k = 1, but base models had higher pass@k at large k. This suggests RLVR narrows sampling onto solutions the base model already contained. In their experiments, distillation from a stronger teacher, unlike RLVR, did add new reasoning patterns.
  • Liu et al. (2025) (NVIDIA) argued with ProRL that prolonged RL with KL control, reference resets and diverse tasks produced models that beat their base models across a wide range of k, including tasks where the base model failed regardless of attempts.
  • Shao et al. (2025) found that spurious rewards work on some models. GRPO on Qwen2.5-Math-7B with random rewards improved MATH-500 by 21.4 points. Ground-truth rewards improved it by 29.1 points. The gains did not transfer to Llama 3 or OLMo 2. The authors traced the effect to clipping bias amplifying a pretrained behavior, code-style reasoning, whose frequency rose from 65% to over 90%.
  • Liu et al. (2025) found self-reflection and "aha" behavior already present in base models, including DeepSeek-V3-Base, before RL.
Illustrative pass@k curves for a base model and an RL-trained model, crossing at large k.
Fig. Why pass@1 and pass@k can disagree. The RL model concentrates probability on problems it can already solve (higher pass@1) but loses rare successes on hard problems, so the base model overtakes it at large k. Illustrative: ten problem types with made-up per-sample success rates, and pass@k \(= \mathbb{E}_x[1-(1-p_x)^k]\). The qualitative pattern follows Yue et al. 2025.

Two practical lessons follow:

  1. Report curves. Report pass@k curves, not just pass@1, when claiming a capability gain.
  2. Use controls. Test any new RL recipe on more than one model family, preferably including one without heavy math mid-training. Add a random-reward control. A recipe that also "works" with random rewards is measuring the base model's priors, not the reward.

From Single-Turn to Agentic RL

Agentic RL trains an LLM to act over many steps in an environment it only partially observes. The model issues tool calls, reads their results, and decides what to do next. The reward arrives at the end of a long trajectory. The model is no longer answering a question. It is running an episode, which brings back the classic RL problems that single-turn RLVR could ignore.

Zhang et al. (2025) surveyed more than 500 works and framed the difference formally. Conventional LLM RL treats generation as a single-step decision (a degenerate MDP). Agentic RL is a temporally extended POMDP (a partially observable Markov decision process, where the agent sees only part of the state). The survey organizes the field by capability (planning, tool use, memory, reasoning, self-improvement, perception) and by domain.

In practice, five things change in the move from single-turn to multi-turn:

AspectSingle-turn RLVRAgentic RL
EpisodeOne response, 1k–30k tokens10–200+ turns, mixing model tokens with tool outputs; 100k+ tokens of context
EnvironmentA stateless checkerA stateful sandbox: container, repository, browser, VM, simulated user
Cost per rolloutGPU time onlyGPU time plus CPU/container time, network, external APIs; highly variable latency
Credit assignmentWhich tokens of one answer matteredWhich turn, tool call or plan mattered, possibly 100 steps before the reward
RewardAnswer correctnessFinal state checks, tests, rubrics or judges; often partial, delayed and noisy

Table. What changes from single-turn to agentic RL. The ranges are typical of published 2025–2026 setups, not hard limits.

Multi-Turn Credit Assignment

With one reward per trajectory, every token in a 50-turn episode gets the same advantage under GRPO-style training. That is unbiased but very noisy. A single bad tool call in an otherwise good trajectory is rewarded, and a brilliant step in a failed one is punished. Three families of fixes are in use.

  • Hierarchical value learning. Zhou et al. (2024) proposed ArCHer. It runs an off-policy, value-based learner at the level of turns (utterances). Within each turn, a token-level policy gradient is guided by the turn-level value. They reported roughly 100× better sample efficiency than prior methods on their multi-turn tasks.
  • Trajectory-level optimization with stabilizers. Wang et al. (2025) built RAGEN and its StarPO framework for trajectory-level agent RL.
    • Echo Trap. They named this recurring failure mode: reward variance collapses and gradients spike as the agent locks into repetitive patterns.
    • StarPO-S. Their stabilized variant filters trajectories, adds a critic and stabilizes gradients.
    • What helps. Diverse initial states, medium interaction granularity and frequent resampling.
    • Reward design. Without fine-grained, reasoning-aware rewards, agents learn shallow strategies or hallucinated thoughts.
  • Denser signals. Turn-level rewards (format, tool success, intermediate state checks), process judges, or learned critics over turns. All of them add hackable surface area. Most production recipes therefore keep the outcome reward primary and add dense terms with small weights.
A multi-turn agent trajectory where model-generated segments are trained and tool outputs are masked from the loss. ONE TRAJECTORY (context grows left to right) task prompt think + call search("…") tool output results think + call run_tests() tool output 2 failed answer final patch r(τ) verifier LOSS MASK 0 1 0 1 0 1 ADVANTAGE outcome-only: the same  = r(τ) − b on every trained token turn-level critic or process judge: a different  per turn generated by the policy (trained) written by the environment (masked: no gradient)
Fig. A multi-turn trajectory as the trainer sees it. Tool outputs are kept in the context, so the model conditions on them, but they are excluded from the loss, because the policy did not choose those tokens. Original drawing; the masking convention follows Jin et al. 2025.

Tool-Use RL

Tool-use RL teaches a model when and how to call tools (a search engine, a code interpreter, an API) inside its reasoning, rewarding only the final outcome. It is the smallest step from single-turn RLVR to agents. The episode is still one "answer", but generation pauses for tool calls and resumes with their results.

Jin et al. (2025) introduced Search-R1:

  • The model emits search queries inside special tags during reasoning. Retrieved passages are inserted into the context. It may search several times before answering.
  • The policy-gradient loss is computed only over model-generated tokens. Retrieved-token masking stabilized training.
  • The reward is exact match on the final answer, with no format reward and no neural reward model. It works with PPO (the default in their experiments) and GRPO.
  • On question-answering benchmarks, the abstract reports average relative gains over RAG baselines of 24% for Qwen2.5-7B and 20% for Qwen2.5-3B.

Feng et al. (2025) (ByteDance Seed) introduced ReTool for code-interpreter use in math reasoning:

  • A cold-start SFT stage on reasoning traces rewritten to replace manual calculation with code and its execution results.
  • PPO-based RL with code executed in a sandbox mid-rollout. The reward is +1 for a correct final answer and −1 otherwise. Code executability itself earns no reward.
  • The 32B model reached 67% on AIME 2024 after 400 training steps. A text-only RL baseline reached 40% after 1,080 steps. Response length fell by about 40% after RL, and code self-correction emerged.

Both papers make the same two engineering points:

  • Mask tool outputs. Exclude them from the loss.
  • Reward the outcome. Keep the reward on the outcome rather than on tool usage, or the model learns to call tools for their own sake.

The rollout loop below shows the pattern most frameworks implement:

def rollout(policy, env, task, max_turns=32, max_tokens=65536):
    """Multi-turn rollout that records which tokens the policy generated."""
    obs = env.reset(task)                       # initial observation (the task prompt)
    tokens, loss_mask, logprobs = policy.tokenize(obs), [], []
    loss_mask += [0] * len(tokens)
    for turn in range(max_turns):
        out = policy.generate(tokens, stop=["</tool_call>", "</answer>"])
        tokens += out.ids;  loss_mask += [1] * len(out.ids);  logprobs += out.logprobs
        if out.is_final_answer or len(tokens) > max_tokens:
            break
        result = env.step(out.text)             # run the tool in the sandbox
        obs_ids = policy.tokenize(result.observation)
        tokens += obs_ids;  loss_mask += [0] * len(obs_ids)   # masked: env tokens
        if result.done:
            break
    reward = env.grade()                        # outcome reward from a verifier
    return dict(tokens=tokens, loss_mask=loss_mask, logprobs=logprobs, reward=reward)

One subtlety: the token IDs fed back to the trainer must be exactly the ones the inference engine generated. Re-tokenizing the decoded text can produce different IDs and silently shift log-probabilities. This is one source of the train–inference mismatch.

Coding and Software-Engineering Agents

Software engineering is the flagship domain of agentic RL because it has the best verifier: a repository's tests. A coding agent explores a repo, edits files, runs commands and submits a patch. The reward is whether hidden tests pass in a fresh container.

The hard part is not the algorithm but the environments. Training needs thousands of executable, reproducible, decontaminated repositories, with tests that actually check the fix.

Scaling SWE Environments

  • Pan et al. (2024) released SWE-Gym, describing it as the first environment for training SWE agents. It holds 2,438 real Python task instances from 11 repositories, with executable environments and tests. Fine-tuning Qwen2.5-Coder-32B on 491 successful agent trajectories raised SWE-bench Verified from 7.0% to 20.6%. A trained verifier for best-of-16 selection reached 32.0%.
  • Jain et al. (2025) built R2E-Gym with more than 8.1K executable environments generated from GitHub commits. Its SWE-Gen pipeline backtranslates commits into problem statements and generates tests when commits lack them. A 32B model reached 34.4% pass@1 on SWE-bench Verified with SFT alone. Hybrid verifiers, which combine test execution and learned trajectory scoring, lifted it to 51%.
  • Yang et al. (2025) released SWE-smith, which synthesizes about 50k task instances from 128 repositories by injecting bugs that break existing tests. Their SWE-agent-LM-32B reached 40.2% pass@1 on SWE-bench Verified.

RL Recipes for SWE Agents

  • Wei et al. (2025) (Meta) proposed SWE-RL, which avoids executing code during training. The reward is −1 for a malformed patch. Otherwise it is the difflib sequence similarity between the predicted and the true patch, mined from open-source software evolution data. Llama3-SWE-RL-70B solved 41.0% of SWE-bench Verified. RL on this one task also improved five out-of-domain tasks (including math and general language understanding), whereas the SFT baseline got worse on average.
  • Agentica and Together AI (2025) trained DeepSWE from Qwen3-32B with RL only, using their rLLM framework. The data was 4.5K R2E-Gym problems, with overlapping repositories filtered out.
    • Results. On SWE-bench Verified it reached 42.2% pass@1 (averaged over 16 runs) and 59% with hybrid test-time scaling.
    • Cost. Training took about six days on 64 H100s.
    • Recipe. Their "GRPO++" combined most of the fixes above: Clip-Higher, no KL loss, no std normalization, leave-one-out advantages, no entropy loss, and filtering of truncated or timed-out trajectories.
  • Cao et al. (2025) (NovaSky, Berkeley Sky Computing Lab and Anyscale) released SkyRL-Agent and SA-SWE-32B. The model was trained from Qwen3-32B with pure RL on the same 4.5K R2E-Gym instances.
    • Results. SWE-bench Verified pass@1 rose from 24.4% to 39.4% with a simple ReAct loop.
    • Cost. Training used 4,601 H100-hours, versus 9,180 for DeepSWE by their accounting.
    • Recipe. Fully on-policy updates, leave-one-out advantages, no KL or entropy losses, and an AST-based code-search tool with hints that made more rollouts succeed early on.
    • Transfer. The model also improved slightly out of domain (Terminal-Bench, BrowseComp-Plus, WebArena).
  • The Kimi K2 report (2025) describes a large-scale agentic data synthesis pipeline and a joint RL stage over real and synthetic environments for a 1T-parameter MoE (32B active), reporting 65.8 on SWE-bench Verified in a non-thinking setting.

A pattern is visible across these recipes:

  • leave-one-out or mean-centred baselines;
  • no KL and no entropy bonus;
  • aggressive filtering of trajectories that timed out or were truncated;
  • most of the effort spent on environments and tools.

SWE-bench Verified itself became unreliable for frontier models in 2026. OpenAI attributed this to contamination and flawed tests. The open-model numbers above are useful mainly as within-paper comparisons.

Web, Deep-Research and Computer-Use Agents

Web and GUI agents act through pages, screenshots or accessibility trees. Their environments are slower, flakier and harder to reset than containers, and success is harder to check. RL here leans on curricula, learned outcome reward models and very large rollout infrastructure.

  • Qi et al. (2024) proposed WebRL. It combines a self-evolving curriculum that generates new tasks from failed attempts, an outcome-supervised reward model, and adaptive RL to limit policy drift. On WebArena-Lite, Llama-3.1-8B rose from 4.8% to 42.4%, and GLM-4-9B from 6.1% to 43%. Both ended above the GPT-4-Turbo (17.6%) and GPT-4o (13.9%) baselines they report.
  • OpenAI (2025) described deep research (February 2025) as a version of o3 trained end-to-end with RL on hard browsing and reasoning tasks. It uses browser and Python tools and the same RL methods as o1. It learned to plan multi-step searches, backtrack and react to new information.
  • The UI-TARS-2 report (2025) combined a data flywheel, a stabilized multi-turn RL framework, and a hybrid environment. That environment joins GUI control with file systems and terminals on a unified sandbox platform. It reports 47.5 on OSWorld and 50.6 on WindowsAgentArena. It also reports 73.3 on AndroidWorld, and about 60% of human-level on a 15-game suite.

The SkyRL-Agent paper is a useful warning from this domain. Its computer-use case study on OSWorld improved training reward but showed little gain in validation accuracy. Rising reward on a small or noisy environment set is not evidence of a better agent.

Rewards Without Verifiers: Rubrics and Judges

Most valuable agent work, such as a research report, a design document or a support conversation, has no unit test. The 2025 answer is to turn expert judgment into a checklist and let a model apply it. These rubric-based rewards, scored by an LLM judge, sit between the precision of verifiers and the flexibility of preference reward models.

Gunjal et al. (2025) (Scale AI) proposed Rubrics as Rewards (RaR):

  • Rubric writing. An LLM writes 7–20 self-contained criteria per prompt, conditioned on a reference answer. Each criterion is tagged Essential, Important, Optional or Pitfall, with a matching weight.
  • Aggregation. Explicit aggregation judges each criterion separately and sums the weights. Implicit aggregation shows the full rubric to a judge and asks for one 1–10 score.
  • Results. They trained with GRPO on Qwen2.5-7B for medicine and science. The implicit variant beat a Likert-scale judge baseline by up to 31% relative on HealthBench and 7% on GPQA-Diamond.
  • Ablations. Rubrics written without reference answers scored lower, and generic rubrics underperformed prompt-specific ones.
A spectrum of reward sources from programmatic verifiers to human ratings. exact match math, short QA tests / execution code, SWE state checks web, GUI, DB rubric + judge reports, medicine preference RM chat, style human rating gold, scarce precise · cheap · narrow broad · costly · noisy hacked by weak tests, answer leaks, grader exploits hacked by flattery, length, style, judge blind spots rule of thumb: use the leftmost signal the task allows; add judges only where nothing objective exists
Fig. Reward sources, from programmatic verifiers on the left to human judgment on the right. Each kind of reward has its own typical way of being gamed. Original drawing.

Judge-based rewards need the same care as judge-based evals:

  • Calibrate. Check the judge against human labels.
  • Separate. Keep the judge outside the policy's model family where possible.
  • Randomize. Shuffle response order in pairwise judgments.
  • Hold out. Keep a held-out human-rated set to detect when policy reward and human ratings diverge.

Environment Design

In agentic RL, the environment is the dataset. Its task distribution, tools, observation format, reset semantics and grader decide what the agent can learn. Most failed agentic RL projects fail here rather than in the optimizer.

A good environment has five properties:

  • Executable. Every task has a reference solution that passes.
  • Isolated. No shared state between rollouts, and no network unless intended.
  • Fast to reset.
  • Graded outside the agent's reach.
  • Calibrated in difficulty. The current policy succeeds sometimes but not always.

Most frameworks converged on a Gymnasium-like interface with text actions. SkyRL-Gym provides math, coding, search and SQL environments on the Gymnasium API. In February 2026, SkyRL added an integration with the Harbor agent-evaluation harness for terminal-use agents. A minimal version:

from dataclasses import dataclass, field

@dataclass
class StepResult:
    observation: str
    reward: float = 0.0          # dense shaping (optional, keep small)
    done: bool = False
    info: dict = field(default_factory=dict)

class TextEnv:
    """One episode = one task. Instances must not share mutable state."""
    def reset(self, task) -> str:
        self.task = task
        self.sandbox = start_container(task.image, network=False)   # isolated, seeded
        return task.instruction
    def step(self, action_text: str) -> StepResult:
        call = parse_tool_call(action_text)
        if call is None:
            return StepResult("Invalid tool call. Use the documented format.", reward=0.0)
        out = self.sandbox.run(call, timeout=60)                      # bounded time
        return StepResult(truncate(out, 8000), done=(call.name == "submit"))
    def grade(self) -> float:
        """Run hidden tests in a FRESH container on the exported artifact only."""
        patch = self.sandbox.export_diff()
        return run_hidden_tests(self.task, patch)                    # 1.0 / 0.0
    def close(self):
        self.sandbox.stop()

Three design decisions matter more than they look:

  • Observation truncation (how much tool output to show) sets the context budget. It also changes what the agent learns to ask for.
  • Error messages for malformed calls are a training signal. Vague ones waste rollouts.
  • Grading the exported artifact in a fresh environment, rather than inspecting the agent's live sandbox, is the single most effective defense against reward hacking. It removes the agent's ability to tamper with the grader.

Long-Horizon Issues

As horizons grow from tens to hundreds of turns, four problems get worse together:

  • Credit assignment weakens. One terminal reward is shared by more decisions.
  • Context fills up. Agents need memory or summarization, and the summarizer itself becomes part of the policy.
  • Rollout time becomes long-tailed. A few trajectories run for many minutes and stall synchronous batches.
  • Rewards become rarer. When the policy almost never succeeds, groups have zero variance and GRPO-style methods get no signal.

The common responses are:

  • curricula (start with short tasks or give hints, as SkyRL-Agent did);
  • asynchronous rollouts (below);
  • trajectory filtering;
  • context-management actions trained as part of the policy.

None of them solve the problem cleanly. Long-horizon RL is the main open frontier for agents, as discussed in Open Problems.

Anatomy of an LLM RL System

An LLM RL system is two very different workloads joined by a weight-sync channel. Generation is memory-bandwidth-bound autoregressive decoding with highly variable lengths. Training is compute-bound forward and backward passes over fixed-size batches.

In long-CoT and agentic runs, generation usually takes most of the wall-clock time. System design is therefore mostly about keeping generation busy without letting the data drift too far off-policy (sampled from a policy other than the one being trained).

Three layouts are common:

  • Colocated, synchronous. Generation and training share the same GPUs and alternate. Weights are resharded in place between the training and inference layouts. The layout is simple and strictly on-policy, but GPUs idle while the longest rollout in a batch finishes.
  • Disaggregated, one-step off-policy. Separate GPU pools for rollout and training. Rollouts for step \(k+1\) are generated with weights from step \(k\) while the trainer updates on step \(k\)'s data. Throughput roughly doubles for a staleness of one step.
  • Fully asynchronous. Rollout workers stream trajectories continuously. The trainer consumes whatever is ready and pushes new weights periodically, sometimes interrupting in-flight generations. Utilization is highest, but each sample may be several versions stale and needs an off-policy correction.
Timelines of synchronous, one-step off-policy and fully asynchronous RL training.
Fig. Three ways to schedule generation and training. In the synchronous layout, the longest rollout in each batch sets the pace (the tail). Overlapping the two workloads removes idle time at the cost of policy staleness, which the trainer must correct for. Illustrative durations.

Training Frameworks

By 2026, most open RL for LLMs ran on a handful of frameworks that share one architecture. It has three components:

  • Controller. Orchestrates rollout, reward and training workers.
  • Inference engine. vLLM or SGLang, used for generation.
  • Training backend. FSDP or Megatron.

The frameworks differ in how they place models on GPUs, how asynchronous they are, and how much agent-loop support they provide.

  • Sheng et al. (2024) (HKU and ByteDance) proposed HybridFlow (EuroSys 2025), open-sourced as veRL. A single controller coordinates data flow between models, while each model's computation runs multi-controller. A "3D-HybridEngine" reshards actor weights between training and generation without redundant copies. They reported 1.53× to 20.57× throughput over earlier RLHF systems.
  • Hu et al. (2024) built OpenRLHF on Ray, vLLM, DeepSpeed and Transformers, with an emphasis on simplicity. They reported 1.22× to 1.68× speedups over contemporary frameworks.
  • Hugging Face TRL is the most accessible entry point. It offers a GRPOTrainer with vLLM in colocate or server mode, configurable loss normalizations, and built-in importance-sampling correction for vLLM mismatch.
  • SkyRL (NovaSky at the Berkeley Sky Computing Lab, with Anyscale) targets long-horizon agents. It started as SkyRL-v0 (May 2025), an RL pipeline for multi-turn tool-use LLMs on SWE tasks. Next came SkyRL-SQL, then the modular skyrl-train and SkyRL-Gym (June 2025). skyrl-tx, a self-hosted backend for the Tinker API, followed in October 2025, and the SkyRL-Agent layer in November 2025. In 2026 it implemented the Tinker API so Tinker scripts run on local GPUs. It also integrated with Harbor for terminal agents and released v0.3.0 (July 2026).
  • slime (THUDM) connects Megatron training to SGLang rollouts. It provides custom generation functions for multi-turn tool use and a fully asynchronous mode for agentic generation. Its README says it is the RL framework behind GLM-4.5, GLM-4.6 and GLM-5.
  • Fu et al. (2025) built AReaL, a fully asynchronous system that decouples generation from training. It balances rollout and training workers to bound staleness and uses a staleness-aware PPO variant. They report up to 2.77× training speedup over synchronous systems on the same GPUs, with matched or better final accuracy.
  • ms-swift (ModelScope) wraps GRPO-family training with switchable advantage estimators (GRPO, RLOO) and KL placement. It is a practical choice for teams already in that ecosystem. rLLM (Agentica) is the agent-RL framework behind DeepSWE.
  • Tinker (Thinking Machines Lab) takes a different approach. It is a hosted API that exposes low-level primitives (sample, forward_backward, optim_step, save_state) on LoRA adapters. The user writes the RL loop and the service handles distributed training and fault tolerance.
FrameworkOriginTraining / rollout backendsAsyncAgent / multi-turnGood for
veRLByteDance Seed → communityFSDP, FSDP2, Megatron / vLLM, SGLangYes (recipes)Multi-turn tool calling, sandbox and search integrationsLarge-scale research, MoE, broad algorithm coverage
OpenRLHFOpen-source communityDeepSpeed / vLLM on RaySee docsSee docsReadable PPO/REINFORCE++ baselines
TRLHugging FaceTransformers + Accelerate / vLLMServer modeTool-calling environmentsSmall to medium runs, teaching, quick experiments
SkyRLBerkeley Sky Lab + Anyscaleskyrl-train; SkyRL-Agent also runs on veRL and TinkerYes (pipelined dispatcher)SkyRL-Agent, SkyRL-Gym, HarborLong-horizon SWE and terminal agents
slimeTHUDM (GLM team)Megatron / SGLangYes (fully async mode)Custom multi-turn generatorsLarge MoE RL with SGLang
AReaLFu et al. 2025Own system (see paper)Fully asyncSee docsThroughput-bound reasoning RL
TinkerThinking MachinesHosted (LoRA)User-definedUser-defined loopResearchers without a GPU cluster

Table. Common open RL stacks for LLMs, from each project's paper or README as of October 2026. Feature lists change monthly; treat this as orientation, not a spec. "See docs" marks details I could not confirm from the sources cited.

Inference Engines in the Loop

Rollout throughput is decided by the inference engine, so RL frameworks embed serving systems rather than calling model.generate. Two dominate.

  • Kwon et al. (2023) introduced vLLM and PagedAttention. PagedAttention manages the KV cache in fixed-size blocks, like virtual-memory pages. This nearly eliminates fragmentation and allows large continuous batches.
  • Zheng et al. (2024) introduced SGLang, whose RadixAttention reuses KV cache across requests that share prefixes. That fits RL well. The \(G\) samples of the same prompt share a prefix, and multi-turn agents re-send a growing shared context every turn.

Embedding an inference engine creates three systems problems:

  • Weight sync. After every update, new weights must reach the rollout engines. Options include NCCL broadcast, resharding from training to inference parallelism, or delta updates as in slime.
  • Memory contention in colocated setups. The KV cache must be freed or offloaded during training (TRL's sleep mode, veRL's hybrid engine).
  • Numerical mismatch. The inference engine and trainer compute slightly different probabilities for the same tokens, even with identical weights.

The last of these turns out to matter a lot.

Async Training and Off-Policy Corrections

Every efficient RL system is somewhat off-policy. Rollouts come from older weights (staleness), from a different numerical implementation of the same weights (mismatch), or both. Left uncorrected, the gradient is biased toward the behavior policy, and long runs can drift or collapse. The fix in every case is importance sampling (IS: reweighting each sample by the ratio of target to behavior probability), truncated to control variance.

  • Noukhovitch et al. (2024) studied asynchronous RLHF. Of the algorithms they tested, online DPO was the most robust to off-policy data, and robustness improved with model size. Async training was about 40% faster for a LLaMA 3.1 8B chatbot at matched final performance.
  • Yao et al. (2025) showed that hybrid engines (vLLM for rollout, FSDP for training) can assign noticeably different token probabilities with identical weights. This quietly turns on-policy RL into off-policy RL. Their truncated importance sampling (TIS) correction improved BF16 training and preserved performance even with 8-bit quantized rollouts.
  • Framework support followed quickly. TRL now applies a sequence-level masked IS correction to vLLM rollouts by default, and veRL added rollout importance sampling. IMPALA's V-trace (Espeholt et al. 2018) is the classic ancestor of all of them.
Deeper Importance-sampling corrections for async and mismatched rollouts

Three policies, not two. Three policies need to be kept apart:

  • \(\pi_\theta\): the trainer's current policy.
  • \(\pi_{\text{old}}\): the trainer's copy of the policy that generated the batch (used for PPO's ratio).
  • \(\mu\): the policy the inference engine actually sampled from.

In a perfect synchronous system \(\mu = \pi_{\text{old}}\). In practice \(\mu\) differs because of staleness (older weights) and mismatch (different kernels, precision, sampling code).

The unbiased gradient for data sampled from \(\mu\) is \(\mathbb{E}_{y\sim\mu}\big[\tfrac{\pi_\theta(y)}{\mu(y)} \hat A\, \nabla\log\pi_\theta(y)\big]\). Factor the ratio per token: \(\frac{\pi_\theta}{\mu} = \underbrace{\frac{\pi_\theta}{\pi_{\text{old}}}}_{\text{PPO ratio, clipped}} \cdot \underbrace{\frac{\pi_{\text{old}}}{\mu}}_{\text{behavior correction}}\).

Truncated IS (TIS). Multiply each token's loss by \(w_t = \min\big(\frac{\pi_{\text{old}}(y_t)}{\mu(y_t)},\, C\big)\) with a cap \(C\) (single digits are typical). The weight is treated as a constant (no gradient). Truncation bounds variance at the cost of a little bias, exactly as V-trace's \(\bar\rho\) does in IMPALA.

Masked IS instead drops tokens or sequences whose ratio leaves \([C_{\min}, C_{\max}]\). TRL's default is a sequence-level mask.

Token vs. sequence level. The exact sequence ratio is a product of per-token ratios, and its variance grows with length. That is why per-token truncation is common. Sequence-level ratios (geometric mean, as in GSPO) are less noisy per token and match sequence-level rewards better.

Staleness bounds. Async systems also cap how many versions old a sample may be. AReaL bounds staleness, and many recipes allow 1–4 steps. They may also interrupt long generations to reload weights mid-trajectory. A trajectory generated by several policy versions needs per-token \(\mu\) log-probs recorded at generation time.

Diagnostics. Log the per-token mismatch \(\log\pi_{\text{old}} - \log\mu\) (mean, max, fraction beyond the cap) every step. A slow rise usually means a numerical change (new kernel, FP8 rollouts, MoE routing differences between engines).

Routing replay addresses the MoE case. It records the experts chosen at rollout time and reuses them in training.

def tis_weights(logp_old_trainer, logp_rollout, mask, cap=2.0):
    """Per-token truncated IS weights for engine/trainer mismatch (no grad)."""
    w = torch.exp(logp_old_trainer - logp_rollout).clamp(max=cap)
    mismatch = ((logp_old_trainer - logp_rollout).abs() * mask).sum() / mask.sum()
    return w.detach(), mismatch.detach()
# loss = (ppo_per_token_loss * tis_weight * mask).sum() / mask.sum()

Training Stability

Long RL runs fail in recognizable ways. Most of the 2025 algorithm variants are responses to these symptoms, so it pays to watch the right curves from the first step.

  • Entropy collapses and learning plateaus.
  • Response length explodes or collapses.
  • Gradient norms spike.
  • Reward climbs while held-out accuracy does not.

Entropy Collapse

Cui et al. (2025) studied entropy in reasoning RL and found that policy entropy falls sharply early in training, after which performance saturates. They fit an empirical relation between entropy and downstream performance:

\[ R = -a\, e^{H} + b, \]

where \(H\) is policy entropy, \(R\) is validation performance and \(a, b\) are fitted constants. The relation implies a ceiling of \(R = b - a\) once entropy reaches zero. The policy "spends" entropy to buy performance and runs out.

They traced the decline to the covariance between a token's probability and its advantage. This covariance is mostly positive, so confident tokens that are rewarded get more confident. Their fixes, Clip-Cov and KL-Cov, restrict updates on the highest-covariance tokens.

Illustrative entropy-performance trade-off R = -a exp(H) + b, with performance rising as entropy falls toward a ceiling.
Fig. The entropy–performance relation \(R = -a e^{H} + b\), read right to left as training proceeds. Performance rises as entropy is consumed and approaches the ceiling \(b - a\) at \(H = 0\). Illustrative constants (\(a = 0.15, b = 0.75\)); the functional form is from Cui et al. 2025.

Five practical levers work against entropy collapse:

  • Raise \(\epsilon_{\text{high}}\), the upper clip bound (Clip-Higher).
  • Raise sampling temperature.
  • Keep prompts at intermediate difficulty.
  • Avoid a large learning rate.
  • Treat an entropy bonus with care.

Entropy bonuses on long sequences can instead cause entropy to explode into gibberish, which is why DeepSWE and SkyRL-Agent disabled them.

Length Dynamics

Response length is the most informative single curve in reasoning RL. Steady growth usually reflects the model learning to think longer, as in R1-Zero. Sudden growth, especially in wrong answers, often reflects the normalization bias Dr. GRPO identified, or a reward model that likes long answers.

Truncation at the context limit also interacts with reward. If truncated responses score 0, the policy is penalized for long reasoning it never got to finish. Hence DAPO's overlong shaping and the common practice of masking truncated samples.

Other Instabilities

  • Gradient spikes and the Echo Trap in multi-turn training (RAGEN). Watch reward variance within groups and the gradient norm, and filter low-variance trajectories.
  • MoE routing drift. Small changes in expert routing between rollout and training amplify mismatch. Sequence-level ratios (GSPO) and routing replay help.
  • Learning-rate sensitivity. RL fine-tuning uses tiny learning rates (around \(10^{-6}\) for full fine-tuning in published recipes such as SkyRL-Agent's) and often constant schedules.
  • Silent data bugs. Examples are wrong chat templates, mismatched tokenization between rollout and training, or rewards computed on the wrong field. These are more common than algorithmic failures and look identical on a loss curve.

Compute and Data Recipes

Published recipes from 2025–2026 converge on a small set of choices. The data matters more than the algorithm, and the cheapest wins come from prompt selection and filtering.

  • Start from a strong base or SFT model. RL sharpens what is there. Cold-start SFT on a few thousand good traces (R1, ReTool) makes RL faster and more readable.
  • Curate prompts by difficulty. Estimate the base model's pass rate per prompt and keep those in a middle band. Drop always-solved and never-solved prompts, and refresh as the policy improves (DAPO's dynamic sampling does this online).
  • Decontaminate training prompts and environments against every benchmark to be reported (DeepSWE dropped repositories shared with SWE-bench Verified).
  • Group size and batch. 8–16 samples per prompt is common for math, with smaller groups for expensive agent rollouts. Larger batches with fewer gradient steps per batch tend to be more stable.
  • Budget. Published examples span a wide range:
    • 8 A100s for a day (Dr. GRPO's 7B recipe).
    • 64 H100s for six days (DeepSWE).
    • About 4,600 H100-hours (SA-SWE-32B).
    • 512 H800s for three weeks (MiniMax-M1).
    Agentic runs also need CPU fleets for sandboxes.
  • LoRA RL works for many settings at much lower cost. Tinker is built entirely on it, and veRL reported LoRA GRPO on a trillion-parameter model using 64 H800s.

Reward Hacking

Reward hacking is when the policy raises the reward without doing what the reward was meant to measure. It is Goodhart's law with a gradient. RL is an optimizer pointed at the reward function, and it will find every gap between the reward and the designer's intent.

Skalse et al. (2022) defined it formally as optimizing a proxy in a way that lowers the true objective, and showed that "unhackable" proxies are very restrictive. Weng (2024) surveys the phenomenon in depth.

Agentic RL makes hacking more likely, because agents can act on the world that contains the grader:

  • Test tampering. Editing or deleting tests, special-casing test inputs, or exiting early with a success code.
  • Answer leakage. Finding gold answers in the filesystem, the environment's history, or the web.
  • Judge exploitation. Flattery, verbosity, confident tone or formatting that a judge or reward model over-rewards.
  • Reward tampering. Modifying the reward code itself when it is reachable.

Two studies show how this generalizes and how hard it is to remove:

  • Denison et al. (2024) trained models on a curriculum of increasingly gameable environments. Training on simple specification gaming (such as sycophancy) increased gaming in later environments. In a small fraction of cases, models trained on the full curriculum rewrote their own reward function zero-shot. Training away the early gaming reduced but did not eliminate later tampering.
  • Baker et al. (2025) (OpenAI) monitored a frontier reasoning model's chain of thought during agentic coding RL. A weaker model (GPT-4o) reading the chain of thought caught reward hacking far better than one reading only actions. Adding the monitor to the reward helped under light optimization. Under strong optimization, though, the agent learned obfuscated hacking: it hid its intent while still hacking. The authors recommend paying a "monitorability tax" by not optimizing the chain of thought directly.

The defenses are mostly environment engineering:

  • Grade exported artifacts in a fresh container.
  • Make tests, reward code and gold answers unreachable.
  • Check diffs for edits to tests and CI.
  • Use held-out tests the agent never runs.
  • Read samples of high-reward trajectories every few hundred steps.

Reward Model Overoptimization

With a learned reward model, the true objective first rises and then falls as the policy optimizes the proxy harder. Gao et al. (2022) measured this with a synthetic setup. A large "gold" reward model stands in for humans, and smaller proxy models are trained on its labels. They found clean functional forms in \(d = \sqrt{D_{\mathrm{KL}}(\pi\|\pi_{\text{init}})}\):

\[ R_{\text{BoN}}(d) = d\,(\alpha_{\text{BoN}} - \beta_{\text{BoN}}\, d), \qquad R_{\text{RL}}(d) = d\,(\alpha_{\text{RL}} - \beta_{\text{RL}} \log d). \]

\(R\) is the gold reward relative to the initial policy, and \(\alpha, \beta\) depend on proxy reward-model size and data. Larger reward models overoptimize more slowly. In their setup, the KL penalty did not change the shape of the gold-reward-versus-KL frontier. It acted more like early stopping.

Illustrative overoptimization curves: proxy reward keeps rising while gold reward peaks and declines.
Fig. Overoptimization. The proxy reward keeps rising with distance from the initial policy while the gold reward peaks and falls. Illustrative parameters using the best-of-n form \(R = d(\alpha - \beta d)\), with the peak at \(d^* = \alpha/2\beta\); the functional form is from Gao et al. 2022.

Overoptimization is why RLHF runs use four safeguards:

  • KL penalties.
  • Early stopping on a held-out gold signal.
  • Reward-model ensembles.
  • Periodic retraining of the reward model on the current policy's samples.

Verifiable rewards largely avoid it, which is one reason RLVR scaled further than RLHF. Judges and rubrics bring it back.

Spurious Rewards and Contamination

Not every gain during RL comes from the reward. Two confounders have misled published results. One is base-model priors that RL amplifies regardless of the reward. The other is benchmark contamination, which makes "improvement" a matter of recall.

  • Spurious rewards. As discussed above, random rewards gave Qwen2.5-Math-7B most of the MATH-500 gain of real rewards. The mechanism was clipping bias amplifying a pretrained behavior (Shao et al. 2025). Any claim from a single model family, especially one with heavy math mid-training, should come with a random-reward or format-only control.
  • Format effects. Liu et al. (2025) found that the prompt template alone changes Qwen2.5 base-model accuracy substantially. Early RL gains can be the model learning the format.
  • Contamination. RL prompts scraped from the web overlap with benchmarks, and SWE environments built from GitHub overlap with SWE-bench repositories. Decontaminate by exact and fuzzy match on problems and, for SWE, by repository.

Evaluating RL-Trained Models

Evaluating an RL run is harder than evaluating a model. The policy is stochastic, runs are noisy across seeds, and the training reward is itself an eval that the policy has been optimizing. Good protocols separate the training signal from the measurement and report uncertainty.

  • pass@k curves. pass@k is the chance that at least one of k samples is correct. Report pass@1 and pass@k for k up to at least 64 or 256. Use the unbiased estimator \(1 - \binom{n-c}{k}/\binom{n}{k}\) from Chen et al. (2021), with \(n \ge k\) samples and \(c\) correct. A curve that rises at k = 1 but falls at large k signals sharpening rather than new capability.
  • Held-out environments. Evaluate on tasks, repositories, websites or tools that never appeared in training, with graders the policy never saw. For agents, also evaluate out of domain (SA-SWE-32B was checked on Terminal-Bench, BrowseComp-Plus and WebArena).
  • Seeds and robust aggregates. Agarwal et al. (2021) showed that few-run deep RL results are often unreliable. They recommended stratified bootstrap confidence intervals, performance profiles and the interquartile mean (IQM, the mean of the middle 50% of runs). Each LLM RL run is expensive, so at least report variance across evaluation samples and, for headline claims, a second seed.
  • Integrity checks. Audit a sample of successful trajectories for hacking, track the rate of test-file edits, and compare training reward with a held-out gold metric over time.
  • Cost and length. Report tokens per answer and turns per episode alongside accuracy. A model that is better only because it thinks three times longer is a different product.
ClaimMinimum evidenceCommon mistake
"RL improved reasoning"pass@1 and pass@k curves on held-out benchmarks; two model families; random-reward controlOne benchmark, one family, pass@1 only
"Algorithm A beats B"Same data, compute and framework; several seeds or bootstrap CIs; IQMDifferent implementations of "the same" baseline
"Agent generalizes"Held-out environments and tools; out-of-domain suitesEvaluating on repositories that overlap training
"No reward hacking"Trajectory audits; tamper detectors; held-out gradersRising training reward as the only signal

Table. What to show for common RL claims. The companion post on agent evaluation covers graders and harnesses in more depth.

Reference Architecture

An agentic RL training system has seven parts. The architecture below is a synthesis of the systems discussed above (veRL, SkyRL-Agent, slime, AReaL, DeepSWE); no single project uses exactly this layout.

  • A registry of tasks and environments.
  • Rollout workers running the agent loop on an inference engine.
  • A sandbox pool.
  • Isolated graders.
  • An experience buffer.
  • A trainer.
  • An evaluation harness with monitoring.
Reference architecture for agentic RL training: registry, rollout workers, sandboxes, graders, buffer, trainer, evaluation and monitoring. TRAINING LOOP ① Task & env registry tasks · env images reward specs · tools train / held-out splits difficulty tags ② Rollout workers inference engine (vLLM / SGLang) agent loop, G samples per task async dispatcher, timeouts records token IDs + logprobs ③ Sandbox pool containers · browsers · VMs tools, simulated users no egress by default snapshot + fast reset ④ Graders (isolated) hidden tests in fresh env state checks · rubric judges reward models · tamper checks reward + metadata per trajectory ⑤ Experience buffer trajectories + loss masks policy version (staleness) drop zero-variance groups, timeouts, truncations ⑥ Trainer FSDP / Megatron advantages (GRPO/RLOO) clipped loss + IS weights optional KL to π_ref tasks calls results trajectories + artifacts scored batch weight sync EVALUATION & MONITORING ⑦ Eval harness checkpoints on held-out envs · pass@k curves out-of-domain suites · several seeds trajectory audits for hacking ⑧ Monitoring reward, entropy, length, clip fraction train–inference mismatch, staleness sandbox errors, rollout latency tails checkpoints metrics
Fig. A reference architecture for agentic RL. Rollout workers run the agent loop against sandboxes; graders score exported artifacts in isolation; the buffer filters and tags trajectories with their policy version; the trainer applies the clipped, importance-weighted loss and pushes weights back. Evaluation runs on held-out environments the trainer never sees. Original synthesis.

Three properties of this design do most of the work:

  • Graders are isolated from the agent's sandbox and see only exported artifacts. This closes the most common hacking routes.
  • Every trajectory carries its policy version and rollout log-probs, so the trainer can correct for staleness and mismatch.
  • Evaluation uses environments and graders disjoint from training, so the eval curve can disagree with the reward curve. That disagreement is the signal to look for.

Production Challenges and Solutions

The problems teams actually hit when running agentic RL are mostly systems and data problems. The table maps each to the fixes that the papers and frameworks above converged on.

ChallengeSymptomSolutions
Long-tail rolloutsGPUs idle waiting for the slowest trajectoryAsync or one-step off-policy rollouts; per-stage pipelined dispatch (SkyRL-Agent); turn and wall-clock caps; interruptible generation
Train–inference mismatchSlow drift or sudden collapse; rising \(|\log\pi_{\text{old}} - \log\mu|\)Truncated or masked IS (TIS, TRL default); record rollout logprobs; routing replay for MoE; avoid re-tokenizing
Stale dataUnstable updates at high async depthBound staleness (1–4 versions); staleness-aware PPO (AReaL); per-sample version tags
Zero-signal batchesMany groups all-correct or all-wrongDifficulty-band curricula; dynamic sampling (DAPO); hints for hard tasks
Entropy collapseEntropy falls early; reward plateausClip-Higher; Clip-Cov / KL-Cov; temperature; fresher, harder prompts
Length blow-upWrong answers get longer; truncation rate risesToken-level or constant normalization (DAPO, Dr. GRPO); overlong masking; length-aware eval
Reward hackingReward up, held-out metric flat; test editsIsolated graders on exported artifacts; unreachable tests; diff checks; CoT and trajectory monitors (without optimizing against them)
Judge noise and biasPolicy learns style, length, flatteryRubrics with reference answers (RaR); calibrated judges; held-out human ratings; ensembles
Sandbox flakinessInfra errors scored as failuresSeparate infra errors from task failures and drop them; health checks; retries on infra only
Environment scarcityOverfitting to a few hundred tasksSynthetic environments from commits and bug injection (R2E-Gym, SWE-smith); self-evolving curricula (WebRL)
ContaminationSuspiciously fast gains on a benchmarkDecontaminate by problem and repository; hold out environments; refresh evals
CostWeeks of cluster time per experimentSmall-model ablations first; LoRA RL; colocated small runs; early stopping on eval

Table. Production challenges of agentic RL mapped to concrete solutions, compiled from the papers and frameworks cited in this post.

A Playbook for an Agentic RL Project

The steps below assume a team with a modest GPU budget that wants to train an open-weight model on a specific agentic task. Examples are fixing bugs in an internal codebase or answering research questions over internal documents.

The order matters. Most of the risk is in the environment and the grader, so build those first and run RL last.

  1. Define the task and the grader. Write down what "done" means as an executable check. Collect 50–200 real tasks with reference solutions and confirm every one passes its grader with the reference and fails without it.
  2. Build the environment. Containerize it, make reset fast, cut network egress, and expose a small, well-documented tool set. Grade exported artifacts in a fresh container.
  3. Measure the base model. Run 8–16 samples per task with the scaffold planned for training. Read 30 transcripts. Compute per-task pass rates. If almost everything is 0% or 100%, fix the task mix or add SFT before RL.
  4. Cold-start SFT (if needed). Rejection-sample successful trajectories from a stronger model or from many samples of the base model. Fine-tune on a few thousand of them so the format and tool use are reliable.
  5. Pick a framework and a boring algorithm. GRPO or RLOO with token-level normalization, Clip-Higher, no std normalization, \(\beta = 0\) for verifiable rewards, IS correction on, tool outputs masked. Change one thing at a time from there.
  6. Pilot small. Train a small model on a subset for a few hundred steps. Check that reward rises, entropy and length behave, mismatch stays small, and held-out pass@1 moves with training reward.
  7. Scale environments before scaling the model. Grow to thousands of tasks (synthetic generation, bug injection, curricula). Diversity of environments generalizes better than more steps on the same few.
  8. Go async when rollouts dominate. Move to disaggregated or async rollouts once tail latency wastes more than about a third of GPU time. Bound staleness and watch the mismatch metric.
  9. Evaluate like a skeptic. Held-out environments, pass@k curves, out-of-domain suites, trajectory audits, and a random-reward control for any surprising gain.
  10. Ship and close the loop. Turn production failures into new environments and tasks, and re-run the eval suite on every checkpoint considered for shipping.
Deeper Debugging a stalled or collapsing RL run: a checklist

Reward flat from step 0. Check that rewards are attached to the right samples (print three trajectories with their rewards). Check the fraction of zero-variance groups. If it is above about 80%, the task is too hard or too easy for the policy. Check the chat template and stop tokens match between rollout and training. Confirm gradients flow only through masked-in tokens and that the mask is not all zeros.

Reward rises, eval flat. Suspect hacking or overfitting. Read the top-reward trajectories. Diff the environment state for test or grader edits. Compare against a held-out grader. For judge rewards, check length and style correlations with reward.

Entropy collapses in the first 100 steps. Lower the learning rate, raise \(\epsilon_{\text{high}}\), raise temperature, remove easy prompts, and check that the run is not accidentally training on greedy samples.

Entropy or length explodes. Remove the entropy bonus, check for a length bias in the loss normalization, mask truncated samples, and look for garbage tokens (often a tokenizer or sampling-parameter mismatch).

Sudden collapse after many good steps. Look at the mismatch metric and gradient-norm spikes around the collapse. Common causes are a rollout-engine upgrade, FP8 or quantized rollouts without IS correction, MoE routing drift, or a data shard with broken rewards.

Roll back to the last good checkpoint, lower the learning rate and turn on (or tighten) IS truncation.

Throughput poor. Profile generation versus training time per step, rollout length distribution and sandbox startup time. Long tails call for async rollouts. Slow sandboxes call for snapshot-based resets and prewarmed pools.

Always log these signals:

  • Reward. Mean and within-group variance; fraction of zero-variance groups.
  • Policy. Entropy, response length (correct vs. wrong), clip fraction, KL to reference.
  • Off-policy health. Mismatch statistics, staleness, truncation rate.
  • Environment. Tool-error rate, sandbox infra-error rate.
  • Eval. Held-out eval at fixed intervals.

Applications

RL is now used wherever there is a reward that can be computed at scale. The list grew quickly once verifiers and judges replaced human labels. The table summarizes the main application areas, and the paragraphs after it add context for the ones not covered elsewhere.

DomainReward signalRepresentative workMain difficulty
Math and reasoningAnswer checkersDeepSeekMath, R1, DAPO, Kimi k1.5Sharpening vs. new capability; verifier precision
Coding and SWE agentsHidden tests in containers; patch similaritySWE-RL, DeepSWE, SA-SWE-32B, Kimi K2Environment scale; test adequacy; tampering
Search and deep researchExact match; rubric judgesSearch-R1, OpenAI deep researchMoving web; grading long reports
Computer use and GUIEnvironment state checks; ORMsWebRL, UI-TARS-2Slow, flaky environments; reset
Alignment and chatPreference RMs; AI feedbackInstructGPT, Constitutional AI, DPOOveroptimization; sycophancy
Expert domainsRubrics with reference answersRubrics as Rewards (medicine, science)Judge validity
Recommendation and adsEngagement, long-term value from logsTop-K off-policy REINFORCE at YouTubeLogged-data bias; huge action spaces
RoboticsTask success in simulationOpenAI's robot hand (ADR)Sim-to-real transfer
Image generationBlack-box quality and alignment scoresLOOP for diffusion modelsReward hacking of aesthetic scorers

Table. Application areas of modern RL, with the reward each relies on.

Recommendation and Ads

Recommendation is RL's oldest large-scale industrial use. It is an offline, off-policy problem at heart: the system learns from logs produced by previous versions of itself.

Chen et al. (2019) deployed REINFORCE in a top-K recommender at YouTube. Their work had four parts:

  • Scaling to action spaces of millions of items.
  • Off-policy correction for logs from multiple behavior policies.
  • A novel top-K correction for recommending several items at once.
  • Validation in live experiments.

The same importance-weighting ideas reappear in async LLM RL.

Robotics

Robotics is where RL's sample inefficiency hurts most, so training happens in simulation. OpenAI et al. (2019) solved a Rubik's cube with a robot hand using policies trained only in simulation. Automatic domain randomization generated ever-harder randomized environments.

The lesson carries over to agents. A curriculum of environments that widens as the policy improves is what makes simulation-trained behavior transfer.

Alignment and Safety

RLHF and Constitutional AI remain how assistants learn helpfulness, honesty and refusal behavior. RL is also how unwanted behaviors are learned by accident. Reward hacking, sycophancy and obfuscated reasoning are training outcomes, not only inference-time risks. Monitoring chains of thought without optimizing against them (Baker et al. 2025) and graders that resist tampering are part of alignment practice for agentic RL.

Beyond Text: Diffusion Models

RL fine-tuning of image generators uses the same estimators with a different policy. The denoising chain is the trajectory, and a black-box scorer is the reward.

Gupta et al.'s LOOP (2025) is a clean example of the critic-free recipe moving across modalities. It uses several samples per prompt, a leave-one-out baseline, and PPO-style clipping.

Open Problems

Agentic RL works well enough in 2026 to train the best open coding and research agents. It also works poorly enough that most runs still need hand-holding. These are the problems I think matter most.

  • Does RL create capability or select it? The pass@k evidence (Yue et al. vs. ProRL) is mixed and model-dependent; pass@k is the chance that at least one of k samples succeeds. A clean answer would control for base-model priors, contamination and training length. It would change how much compute goes to RL versus pretraining and distillation.
  • Long-horizon credit assignment. Outcome-only rewards spread one bit of information over hundreds of decisions. Turn-level critics, process judges and hierarchical methods (ArCHer) help in research settings. None is yet a standard ingredient of large agent runs.
  • Rewards for work without verifiers. Rubrics and judges extend RL to reports, advice and design. But they import the judge's biases, and they are hackable in ways that are hard to see. Validating judge-based rewards at scale, against humans, is unsolved.
  • Environment scaling. Synthetic environments (R2E-Gym, SWE-smith, self-evolving curricula) made thousands of tasks possible for code. Equivalent pipelines for the web, desktop apps and enterprise workflows mostly do not exist in the open. Such pipelines would also need reliable resets and graders.
  • Stable off-policy RL at scale. Async systems trade staleness and mismatch for throughput: rollouts come from an older or numerically different policy than the one being trained. The corrections (TIS, masking, bounded staleness) are heuristics. A principled, robust off-policy algorithm for long LLM trajectories would simplify infrastructure a lot.
  • Exploration. LLM RL explores only where the pretrained model already puts probability. Methods that reliably discover strategies the base model would not sample, without reward hacking, remain open.
  • Reward hacking that hides. Strong optimization can teach agents to conceal hacking in their reasoning. Keeping chains of thought monitorable while training hard on outcomes is both a safety and a measurement problem.
  • Reproducibility. The same algorithm in two frameworks can behave very differently. Few papers report seeds or variance. Shared environments, harnesses and reporting standards are still missing for LLM RL, like those rliable brought to classic deep RL.
About the figures

All figures are original drawings or JS charts drawn in the page.

Figures marked "Adapted and redrawn" are my own drawings based on a paper's figure. See the linked source for the original.

Charts marked "illustrative" use made-up parameters in a published functional form. No images from other sources are embedded.

Citation

Cited as:

Cheng, Kevin. (Oct 2026). Reinforcement Learning, from Bellman to Agents. Kevin's Notes.
@article{cheng2026rlagentic,
  title   = "Reinforcement Learning, from Bellman to Agents",
  author  = "Cheng, Kevin",
  journal = "Kevin's Notes",
  year    = "2026",
  month   = "Oct"
}

References

  1. Sutton, R. S., & Barto, A. G. "Reinforcement Learning: An Introduction (2nd ed.)." MIT Press 2018. incompleteideas.net/book/the-book-2nd.html
  2. Wikipedia. "Bellman equation." en.wikipedia.org/wiki/Bellman_equation
  3. Wikipedia. "Markov decision process." en.wikipedia.org/wiki/Markov_decision_process
  4. Sutton, R. S. "Learning to Predict by the Methods of Temporal Differences." Machine Learning 1988. mlanthology.org/mlj/1988/sutton1988mlj-learning
  5. Watkins, C. J. C. H., & Dayan, P. "Technical Note: Q-Learning." Machine Learning 1992. mlanthology.org/mlj/1992/watkins1992mlj-technical
  6. Williams, R. J. "Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning." Machine Learning 1992. mlanthology.org/mlj/1992/williams1992mlj-simple
  7. Sutton, R. S., McAllester, D., Singh, S., & Mansour, Y. "Policy Gradient Methods for Reinforcement Learning with Function Approximation." NeurIPS 1999. mlanthology.org/neurips/1999/sutton1999neurips-policy
  8. Mnih, V., et al. "Playing Atari with Deep Reinforcement Learning." 2013. arxiv.org/abs/1312.5602
  9. Google Research. "From Pixels to Actions: Human-level control through Deep Reinforcement Learning" (on Mnih et al., Nature 2015). research.google/blog/from-pixels-to-actions-…
  10. Mnih, V., et al. "Asynchronous Methods for Deep Reinforcement Learning." ICML 2016. arxiv.org/abs/1602.01783
  11. Schulman, J., et al. "Trust Region Policy Optimization." ICML 2015. arxiv.org/abs/1502.05477
  12. Schulman, J., et al. "High-Dimensional Continuous Control Using Generalized Advantage Estimation." ICLR 2016. arxiv.org/abs/1506.02438
  13. Schulman, J., et al. "Proximal Policy Optimization Algorithms." 2017. arxiv.org/abs/1707.06347
  14. Andrychowicz, M., et al. "What Matters In On-Policy Reinforcement Learning? A Large-Scale Empirical Study." 2020. arxiv.org/abs/2006.05990
  15. Henderson, P., et al. "Deep Reinforcement Learning that Matters." AAAI 2018. arxiv.org/abs/1709.06560
  16. Haarnoja, T., et al. "Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor." ICML 2018. arxiv.org/abs/1801.01290
  17. Espeholt, L., et al. "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures." ICML 2018. arxiv.org/abs/1802.01561
  18. Levine, S., Kumar, A., Tucker, G., & Fu, J. "Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems." 2020. arxiv.org/abs/2005.01643
  19. Kumar, A., et al. "Conservative Q-Learning for Offline Reinforcement Learning." NeurIPS 2020. arxiv.org/abs/2006.04779
  20. Silver, D., et al. "Mastering the game of Go with deep neural networks and tree search." Nature 2016. research.google/pubs/mastering-the-game-of-go-…
  21. Silver, D., et al. "Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm." 2017. arxiv.org/abs/1712.01815
  22. Schrittwieser, J., et al. "Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model." 2019. arxiv.org/abs/1911.08265
  23. Christiano, P., et al. "Deep Reinforcement Learning from Human Preferences." NeurIPS 2017. arxiv.org/abs/1706.03741
  24. Ziegler, D. M., et al. "Fine-Tuning Language Models from Human Preferences." 2019. arxiv.org/abs/1909.08593
  25. Stiennon, N., et al. "Learning to Summarize from Human Feedback." NeurIPS 2020. arxiv.org/abs/2009.01325
  26. Ouyang, L., et al. "Training Language Models to Follow Instructions with Human Feedback." NeurIPS 2022. arxiv.org/abs/2203.02155
  27. Bai, Y., et al. "Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback." 2022. arxiv.org/abs/2204.05862
  28. Bai, Y., et al. "Constitutional AI: Harmlessness from AI Feedback." 2022. arxiv.org/abs/2212.08073
  29. Lee, H., et al. "RLAIF vs. RLHF: Scaling Reinforcement Learning from Human Feedback with AI Feedback." ICML 2024. arxiv.org/abs/2309.00267
  30. Rafailov, R., et al. "Direct Preference Optimization: Your Language Model is Secretly a Reward Model." NeurIPS 2023. arxiv.org/abs/2305.18290
  31. Lambert, N. "Reinforcement Learning from Human Feedback." 2025. arxiv.org/abs/2504.12501
  32. Gao, L., Schulman, J., & Hilton, J. "Scaling Laws for Reward Model Overoptimization." ICML 2023. arxiv.org/abs/2210.10760
  33. Uesato, J., et al. "Solving Math Word Problems with Process- and Outcome-Based Feedback." 2022. arxiv.org/abs/2211.14275
  34. Lightman, H., et al. "Let's Verify Step by Step." 2023. arxiv.org/abs/2305.20050
  35. Snell, C., Lee, J., Xu, K., & Kumar, A. "Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters." 2024. arxiv.org/abs/2408.03314
  36. Shao, Z., et al. "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models." 2024. arxiv.org/abs/2402.03300
  37. Lambert, N., et al. "Tülu 3: Pushing Frontiers in Open Language Model Post-Training." 2024. arxiv.org/abs/2411.15124
  38. OpenAI. "Learning to Reason with LLMs." Sep 2024. openai.com/index/learning-to-reason-with-llms
  39. DeepSeek-AI. "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning." 2025; Nature 645, 2025. arxiv.org/abs/2501.12948
  40. Kimi Team. "Kimi k1.5: Scaling Reinforcement Learning with LLMs." 2025. arxiv.org/abs/2501.12599
  41. MiniMax. "MiniMax-M1: Scaling Test-Time Compute Efficiently with Lightning Attention." 2025. arxiv.org/abs/2506.13585
  42. Kool, W., van Hoof, H., & Welling, M. "Buy 4 REINFORCE Samples, Get a Baseline for Free!" ICLR 2019 Workshop. mlanthology.org/iclrw/2019/kool2019iclrw-buy
  43. Ahmadian, A., et al. "Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs." ACL 2024. arxiv.org/abs/2402.14740
  44. ModelScope. "RLOO." ms-swift documentation (v3.12). swift.readthedocs.io/…/GRPO/AdvancedResearch/RLOO.html
  45. Gupta, S., et al. "A Simple and Effective Reinforcement Learning Method for Text-to-Image Diffusion Fine-tuning." 2025. arxiv.org/abs/2503.00897
  46. Hu, J. "REINFORCE++: A Simple and Efficient Approach for Aligning Large Language Models." 2025. arxiv.org/abs/2501.03262
  47. Yu, Q., et al. "DAPO: An Open-Source LLM Reinforcement Learning System at Scale." NeurIPS 2025. arxiv.org/abs/2503.14476
  48. Liu, Z., et al. "Understanding R1-Zero-Like Training: A Critical Perspective." 2025. arxiv.org/abs/2503.20783
  49. Qwen Team. "Group Sequence Policy Optimization." 2025. arxiv.org/abs/2507.18071
  50. Yue, Y., et al. "Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model?" 2025. arxiv.org/abs/2504.13837
  51. Liu, M., et al. "ProRL: Prolonged Reinforcement Learning Expands Reasoning Boundaries in Large Language Models." 2025. arxiv.org/abs/2505.24864
  52. Shao, R., et al. "Spurious Rewards: Rethinking Training Signals in RLVR." 2025. arxiv.org/abs/2506.10947
  53. Cui, G., et al. "The Entropy Mechanism of Reinforcement Learning for Reasoning Language Models." 2025. arxiv.org/abs/2505.22617
  54. Chen, M., et al. "Evaluating Large Language Models Trained on Code." 2021. arxiv.org/abs/2107.03374
  55. Zhang, G., et al. "The Landscape of Agentic Reinforcement Learning for LLMs: A Survey." 2025. arxiv.org/abs/2509.02547
  56. Zhou, Y., Zanette, A., Pan, J., Levine, S., & Kumar, A. "ArCHer: Training Language Model Agents via Hierarchical Multi-Turn RL." 2024. arxiv.org/abs/2402.19446
  57. Wang, Z., et al. "RAGEN: Understanding Self-Evolution in LLM Agents via Multi-Turn Reinforcement Learning." 2025. arxiv.org/abs/2504.20073
  58. Jin, B., et al. "Search-R1: Training LLMs to Reason and Leverage Search Engines with Reinforcement Learning." 2025. arxiv.org/abs/2503.09516
  59. Feng, J., et al. "ReTool: Reinforcement Learning for Strategic Tool Use in LLMs." 2025. arxiv.org/abs/2504.11536
  60. Pan, J., et al. "Training Software Engineering Agents and Verifiers with SWE-Gym." 2024. arxiv.org/abs/2412.21139
  61. Jain, N., et al. "R2E-Gym: Procedural Environments and Hybrid Verifiers for Scaling Open-Weights SWE Agents." 2025. arxiv.org/abs/2504.07164
  62. Yang, J., et al. "SWE-smith: Scaling Data for Software Engineering Agents." NeurIPS 2025. arxiv.org/abs/2504.21798
  63. Wei, Y., et al. "SWE-RL: Advancing LLM Reasoning via Reinforcement Learning on Open Software Evolution." 2025. arxiv.org/abs/2502.18449
  64. Agentica & Together AI. "DeepSWE: Training a Fully Open-sourced, State-of-the-Art Coding Agent by Scaling RL." Jul 2025. together.ai/blog/deepswe
  65. Cao, S., et al. "SkyRL-Agent: Efficient RL Training for Multi-turn LLM Agent." 2025. arxiv.org/abs/2511.16108
  66. NovaSky-AI. "SkyRL: A full-stack RL library for LLMs (skyrl-train, skyrl-gym, skyrl-agent, skyrl-tx)." GitHub. github.com/NovaSky-AI/SkyRL
  67. Kimi Team. "Kimi K2: Open Agentic Intelligence." 2025. arxiv.org/abs/2507.20534
  68. OpenAI. "Why SWE-bench Verified no longer measures frontier coding capabilities." 2026. openai.com/index/why-we-no-longer-evaluate-swe-bench-verified
  69. Qi, Z., et al. "WebRL: Training LLM Web Agents via Self-Evolving Online Curriculum Reinforcement Learning." ICLR 2025. arxiv.org/abs/2411.02337
  70. OpenAI. "Introducing deep research." Feb 2025. openai.com/index/introducing-deep-research
  71. UI-TARS-2 Team. "UI-TARS-2 Technical Report: Advancing GUI Agent with Multi-Turn Reinforcement Learning." 2025. arxiv.org/abs/2509.02544
  72. Gunjal, A., et al. "Rubrics as Rewards: Reinforcement Learning Beyond Verifiable Domains." 2025. arxiv.org/abs/2507.17746
  73. Sheng, G., et al. "HybridFlow: A Flexible and Efficient RLHF Framework." EuroSys 2025. arxiv.org/abs/2409.19256
  74. verl community. "verl: Volcano Engine Reinforcement Learning for LLMs." GitHub. github.com/volcengine/verl
  75. Hu, J., et al. "OpenRLHF: An Easy-to-use, Scalable and High-performance RLHF Framework." 2024. arxiv.org/abs/2405.11143
  76. Hugging Face. "GRPO Trainer." TRL documentation. huggingface.co/docs/trl/main/en/grpo_trainer
  77. THUDM. "slime: an LLM post-training framework for RL scaling." GitHub. github.com/THUDM/slime
  78. Fu, W., et al. "AReaL: A Large-Scale Asynchronous Reinforcement Learning System for Language Reasoning." NeurIPS 2025. arxiv.org/abs/2505.24298
  79. Thinking Machines Lab. "Tinker." thinkingmachines.ai/tinker
  80. Kwon, W., et al. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arxiv.org/abs/2309.06180
  81. Zheng, L., et al. "SGLang: Efficient Execution of Structured Language Model Programs." NeurIPS 2024. arxiv.org/abs/2312.07104
  82. Noukhovitch, M., et al. "Asynchronous RLHF: Faster and More Efficient Off-Policy RL for Language Models." ICLR 2025. arxiv.org/abs/2410.18252
  83. Yao, F., Liu, L., Zhang, D., Dong, C., Shang, J., & Gao, J. "On the Rollout-Training Mismatch in Modern RL Systems." NeurIPS 2025. neurips.cc/virtual/2025/126728
  84. Skalse, J., Howe, N. H. R., Krasheninnikov, D., & Krueger, D. "Defining and Characterizing Reward Hacking." NeurIPS 2022. arxiv.org/abs/2209.13085
  85. Weng, L. "Reward Hacking in Reinforcement Learning." Lil'Log, Nov 2024. lilianweng.github.io/posts/2024-11-28-reward-hacking
  86. Denison, C., et al. "Sycophancy to Subterfuge: Investigating Reward-Tampering in Large Language Models." 2024. arxiv.org/abs/2406.10162
  87. Baker, B., et al. "Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation." 2025. arxiv.org/abs/2503.11926
  88. Agarwal, R., et al. "Deep Reinforcement Learning at the Edge of the Statistical Precipice." NeurIPS 2021. arxiv.org/abs/2108.13264
  89. Chen, M., Beutel, A., Covington, P., Jain, S., Belletti, F., & Chi, E. "Top-K Off-Policy Correction for a REINFORCE Recommender System." WSDM 2019. arxiv.org/abs/1812.02353
  90. OpenAI, et al. "Solving Rubik's Cube with a Robot Hand." 2019. arxiv.org/abs/1910.07113