Visual Learn RL for LLM agents

Reinforcement learning for language-model agents

How a language model is trained on scores for its own sampled answers, from one gradient step to a multi-turn coding agent

A pretrained language model predicts the next token of text written by someone else. Reinforcement learning changes the model using scores for text it generates itself: a checked answer, a passing test suite, or a learned judgment of quality. This page builds the mechanism from a single policy-gradient update to a tool-using agent, then collects what AI laboratories have published about their own training.

10 sections · about 30 minutes · every figure is computed in your browser, and the simulated ones say so

Where reinforcement learning sits in training

Language models are trained in phases, and each phase supplies a different target. Pretraining supplies the next token of existing text. Supervised fine-tuning supplies demonstrations. Preference training supplies comparisons. Reinforcement learning (RL) supplies a score for something the model produced.Published recipes often mix or repeat these phases. Reports from OpenAI, DeepSeek, Qwen and other teams describe larger RL runs for reasoning and tool use than earlier instruction-following systems used; recipes and compute allocations remain mostly undisclosed.

PhaseTraining signalWhat it changes
PretrainingThe next token in a large text and multimodal corpusBroad statistical structure: language, factual associations, and patterns that later skills build on. The resulting base model continues text but does not reliably follow instructions.
Supervised fine-tuningPrompt–response demonstrations written by people, or generated and filtered by modelsThe loss usually covers only the response tokens. DeepSeek-R1 used a small set of long reasoning examples as “cold-start” data before its main RL phase.
Preference trainingComparisons between two responsesInstruction following, style and safety behavior. Comparisons train a reward model for RLHF, or update the policy directly with an objective such as DPO.
Outcome-based RLScores for sampled answers or tool-use trajectories: answer checkers, tests, environment state, learned gradersReasoning and tool use. OpenAI, DeepSeek, Qwen and others report using it; their task mixtures and compute allocations are only partly public.

The loop, in a game and in a language model

RL describes an agent that receives an observation, takes an action, and receives a reward from an environment. The environment has a full state that the agent may see only in part. For a language-model agent, the observation is whatever sits in the context window; an action can be a single token, a message, or a tool call; and the environment can be a code sandbox, a browser, a grader, or a simulated user.

Classic RL · a board game

Language-model agent · fixing a bug

The same loop in two settings. Blue marks what the policy chose, orange what the environment returned, green the reward. The strip under each diagram is one episode, read left to right; in the language-model strip each thin blue cell is one generated token. In the language-model example, every token choice in the episode shares a single reward that arrives at the end.
TermClassic RLLanguage-model agent
ObservationVisible board position or sensor readingsThe prompt and interaction history in the context window
StateThe environment’s full condition, which may be hiddenMay include files or browser data outside the context
ActionA move or a button pressThe next token; at a coarser level, a message or a tool call
RewardA score at a step or at the endA verifier, tests, a judge model, or intermediate feedback
EpisodeA sequence of interactionsA single answer or a multi-turn agent session

The example uses one outcome reward at the end of the episode, so a long sequence of token choices shares a small amount of feedback. Other systems add intermediate or process rewards, which score steps along the way.

Policy gradients: make what scored well more likely

A policy πθ is a probability distribution over actions, set by the model’s weights θ. A policy-gradient method samples an action, scores it, and adjusts θ to change the log-probability of that action in proportion to its advantage: how much better its return was than expected. A return is the sum of rewards from that action onward, with optional discounting of later rewards. A positive advantage pushes up the sampled action’s log-probability; a negative one pushes it down. Shared model weights mean a batch update can also affect other actions and contexts.

∇J(θ) ≈ E[ Σt At · ∇θ log πθ(at | st) ]REINFORCE with a baseline

A baseline is a reference value subtracted from the sampled return, often an estimate of the expected return from that state. A well-chosen baseline reduces the variance of the gradient estimate without changing its expected value. In the one-action example below, return and reward are the same.The estimator comes from Williams’s REINFORCE (1992). The baseline may depend on the state but not on the action taken; that condition keeps the expected gradient unchanged.

advantage = reward − baseline = 1.0 − 0.00 = +1.00|updates 0

A policy over five possible answers to “What is 6 × 7?”, updated by hand with the exact softmax gradient and a learning rate of 1. The baseline is a moving average of past rewards that moves halfway to each new reward; real systems use a learned critic or group statistics (simplified). A thin tick marks each probability before the last update. Repeat the same reward and each update moves the policy less, because the baseline catches up and the advantage halves.

PPO’s clipped objective

Proximal Policy Optimization (PPO) reuses each batch of samples for several gradient steps. During those steps the policy drifts away from the one that generated the samples, πold. PPO measures the drift for each sampled action with the probability ratio r and clips the objective in the direction favored by the advantage: above 1 + ε for a positive advantage, below 1 − ε for a negative one.

LCLIP = E[ min( rt·At, clip(rt, 1−ε, 1+ε)·At ) ]
rt = πθ(at|st) / πold(at|st)

Positive advantage · A = +1

Negative advantage · A = −1

The clipped objective for one action with ε = 0.2. The shaded band is the clip range; the dashed line is the unclipped objective r·A. Once the ratio has moved ε in the direction the advantage favors, the objective goes flat and stops pushing. In the other direction it stays sloped.

Clipping discourages large updates, but it does not impose a hard bound on how far the policy can change.DAPO (2025) uses separate lower and upper clip values and gives the upper side more room, a change its authors call “clip-higher.” They report that it lets low-probability tokens increase during training. arXiv:2503.14476 The PPO formulation used in early RLHF systems also trains a value model, or critic, that predicts the expected reward from each state and supplies the baseline.

GRPO: a baseline from a group of samples

Group Relative Policy Optimization (GRPO), introduced with DeepSeekMath in 2024, removes the value model. It samples a group of G responses to the same prompt, scores each, and normalizes the rewards within the group. With a single outcome reward, every token of response i receives the same advantage Âi. Responses above the group mean are reinforced; those below it are suppressed.

Âi = ( ri − mean(r1..G) ) / std(r1..G)one advantage per response

mean –|std –|reward signal –

Six sampled answers to “What is 17 × 24? Put the final answer in \boxed{}.” A verifier gives 1 for 408 and 0 otherwise. Click a verdict to swap that response for a version with the other outcome. Std is the population standard deviation.

When every response scores the same, the standard deviation is zero and the written formula is undefined. Implementations use a small denominator offset or explicitly set these advantages to zero, as this figure does. The group then supplies no reward-based policy gradient. A separate KL penalty can still contribute a gradient.The original DeepSeekMath objective, equation 3, adds KL regularization separately from the normalized reward term. The next figure shows the reward advantages for every possible outcome of a six-response group.

GRPO advantages in a group of six with 0/1 rewards, by the number of correct responses. Green: each correct response; red: each wrong one. A mixed group provides a reward-based learning signal, and the rare outcome gets the large advantage. Uniform rewards provide no such signal.

GRPO’s main costs and fixes, as reported in the papers that introduced them:

Later methods each change one part of this recipe: the baseline, the clipping rule, the token weighting, the sampling policy, or the correction for stale samples. Similar names can hide materially different objectives.

Rewards learned from human preferences

Helpfulness has no answer key. RLHF, reinforcement learning from human feedback, trains a reward model rφ from comparisons: a person reads two responses to the same prompt and picks the better one. The Bradley–Terry model turns the two scalar scores into a probability that the first is preferred.

P(A ≻ B) = σ( rφ(A) − rφ(B) )σ is the logistic function

Training maximizes the log-probability of each choice people made. A comparison moves the chosen response’s score up and the other’s down in proportion to 1 − P(chosen), so comparisons the reward model already predicts well move it little.

0 comparisons
A reward model with one free score per response (simplified), trained by one gradient step on the Bradley–Terry loss per click, learning rate 1.2. Grey dots are earlier positions; the horizontal scale expands to keep every score difference visible. Each agreeing click moves the scores less than the one before, because the gradient is 1 − P.

Keeping the policy near a reference

The policy is then trained to score well under the learned reward, with a penalty for drifting from a reference policy πref, usually the supervised model it started from. The penalty is the KL divergence, a measure of how different two probability distributions are, scaled by a coefficient β.

maximize E[ rφ(y) ] − β · KL( πθ ‖ πref )

The penalty discourages moving into regions where the reward model has little training evidence, but it does not guarantee reliable scores. With fixed rewards, a fixed reference and β > 0, optimization over all output distributions has an exact solution: the optimal policy is the reference reweighted by exp(r/β) and renormalized.π*(y) = πref(y) · exp(r(y)/β) / Z, where Z normalizes the distribution. This is equation 4 in the DPO paper (Rafailov et al., 2023), which builds its loss on it. The figure applies that formula to one next-token distribution.

expected reward –|KL –|objective –

The exact KL-regularized optimum for a ten-token vocabulary. Purple ticks: the reference distribution. Blue bars: the optimal policy. The reward is +1 for t7, +0.6 for t8, −0.5 for t0 and 0 elsewhere. The slider is on a log scale from 0.05 to 5. A small β lets the policy pile onto the top-rewarded token at a large KL cost; a large β keeps it near the reference.

Variants that change the source of the preference

Direct Preference Optimization (DPO, 2023) derives a policy loss directly from preference pairs and a reference model, using the solution above. It avoids fitting an explicit reward model and running on-policy sampling during the DPO update.

Constitutional AI (Anthropic, 2022) uses written principles to guide model critiques, revisions and AI-generated preference labels. Anthropic then trains a preference model on those labels and applies reinforcement learning from AI feedback (RLAIF).

Rubric-based rewards have a grader model score an open-ended response against explicit criteria. The reward is more structured than one overall preference, but its reliability still depends on the rubric, the grader and how both were validated.

Rewards a program can check

RL with verifiable rewards (RLVR) uses tasks whose outcomes a program can check: a final math answer compared with a known one, or code run against tests. OpenAI reports that o1 learned to use chain of thought productively through large-scale RL but has not published its reward design. DeepSeek documents a clearer example. DeepSeek-R1-Zero was trained with RL directly from the base model, with a rule-based accuracy reward and a format reward and no supervised reasoning traces.

During that run, R1-Zero’s pass@1 score on the AIME 2024 math competition rose from 15.6% to 71.0%.Pass@1 is the fraction of problems solved by a single sampled answer, averaged over samples. Figures from the DeepSeek-R1 paper (2025), section 2.2.4. Its average response length grew steadily over training, and the model began re-checking its work and changing strategy mid-answer. DeepSeek called one such shift, in an intermediate checkpoint, an “aha moment.” Length growth can be limited: Kimi k1.5 used a length penalty to train short chain-of-thought models, and token budgets and penalties for overlong responses serve the same purpose.

Verifiable rewards help in three ways. Exact answers and well-designed tests give a more reproducible signal than an overall preference score, though weak tests can be incomplete or exploitable. Once tasks and checkers exist, many sampled responses can be graded without a person labeling each one. And a final score rewards any reasoning path that reaches the correct result; it does not say which intermediate steps were valid.

The method has spread in three directions. DeepSeek fine-tuned smaller Qwen and Llama models on reasoning traces from R1 (distillation) and reported large benchmark gains over the corresponding base models. Products expose the length–accuracy trade-off to users: Claude’s extended thinking, Gemini’s thinking budget and OpenAI’s reasoning effort. And verifiers now cover formal proofs in Lean, tool-call schemas, structured extraction, chemistry and rubric-graded free text.

Train-time and test-time compute

Train-time compute updates the weights. Test-time compute gives a trained model more generation or search per query. OpenAI reports that o1’s performance improved with more of both. Its o3 announcement says the team added another order of magnitude in both and kept seeing gains. These are relative trends from one provider, with no absolute compute values or cost breakdown.

xAI separately states that Grok 4 used reinforcement-learning compute comparable to its pretraining compute. That claim concerns a different model and a different reporting basis, so it does not belong on the same scale as OpenAI’s relative result.

Reinforcement learning for tool-using agents

A tool-using episode interleaves model messages, tool calls, and observations returned by an environment. Training can score the whole trajectory with an outcome, such as hidden-test results, or add intermediate scores. OpenAI has described end-to-end RL for deep research and tool use, and Qwen has published an agentic RL setup for coding. Other providers disclose less, so the figure shows a representative training design, not one product’s recipe.

policy tokens trained –|environment tokens masked –|advantage –

One simplified coding-agent episode; token counts are approximate. Each model turn gets its return-to-go minus a fixed baseline of 0.45. With no discounting, return-to-go includes the final outcome and all tool-call rewards at or after that turn. Tool outputs stay in the context but have no direct policy-loss term. A later reward trains earlier decisions too. A reward already received does not enter the return of a later action.

The tool-call option pays +0.10 after each of the four search, test or edit calls, with no bonus for submission. On a failed attempt, the first turn therefore gets 0 + 4 × 0.10 − 0.45 = −0.05; the final submission gets 0 − 0.45 = −0.45. This is a return-to-go estimate with a fixed illustrative baseline, not a learned critic.See Spinning Up’s derivation of reward-to-go. Keeping the baseline fixed makes the arithmetic visible; a trained critic would estimate the return under the selected reward scheme. Paying for tool calls can reward unnecessary calls, so denser feedback also changes what the agent is encouraged to do.

Four difficulties dominate:

Where agent rewards come from

Agent training needs tasks, environments and graders that expose the behavior being trained. The common sources, with no claim about how often each is used:

SourceWhat it checks
Unit or hidden testsSWE-style tasks run repository tests after the agent submits
Answer checkersMath, science and structured-output tasks compare with a known answer
LLM judge with a rubricA grader model scores the result against explicit criteria
Simulated usersA model plays a user with a hidden goal, as in τ-bench-style evaluations
Human preferencePeople compare sampled trajectories or final responses
Format and policy checksDeterministic checks on schemas, tool constraints or forbidden actions

Reward hacking

A policy is optimized against the reward the training system computes, not against the designer’s intent. If that reward omits part of the intended behavior, the policy can raise its score without improving the real outcome: by modifying tests, exploiting a grader’s preferences, or reading information the task meant to hide.

Gao, Schulman and Hilton measured this with a stand-in for people: a large “gold” reward model labeled the data, a smaller proxy reward model learned from those labels, and a policy was trained against the proxy.Scaling Laws for Reward Model Overoptimization (2022). They define d = √KL(π ‖ πinit) and fit the gold score for RL as R(d) = d(α − β ln d). With α held fixed, β varied smoothly with proxy reward-model size, and larger proxies reached higher gold scores. As training moved the policy further from its starting point, the proxy score kept rising while the gold score rose, peaked and fell.

Weak grader · β = 0.70

Better grader · β = 0.45

Strong grader · β = 0.33

Simulated with the functional form from Gao et al. (2022): true reward R(d) = d(1 − β ln d), measured (proxy) reward with β = 0.08, and d = √KL from the initial policy on the horizontal axis. The coefficients are chosen for illustration. The red band is the gap between what the grader measures and what was intended. A better grader moves the peak later and higher; it does not remove it.

Examples from published reports

Countermeasures

What laboratories have published

The table summarizes system cards, papers and official posts published through mid-2026, grouped by organization and ordered by date. Each row links its source. It lists what was disclosed; complete training recipes and compute allocations are not public for any of these systems.

DateRelease or paperWhat was disclosed
OpenAI
Sep 2024o1“Large-scale RL” that teaches the model to use chain of thought productively. Performance improved with more RL training compute and with more test-time compute.
Feb 2025Deep ResearchBrowsing and reasoning behavior trained end-to-end with RL on difficult research tasks.
Mar 2025Chain-of-thought monitoringPenalizing “bad thoughts” directly made the model hide its intent; OpenAI warns against optimizing the chain of thought directly.
Apr 2025o3 and o4-miniRL over tool use: the model learns when to search, run code or look at images mid-reasoning. About an order of magnitude more RL training compute than o1.
May 2025CodexRL on real software-engineering tasks in sandboxed repositories, aimed at passing tests and PR-quality output; later continued in GPT-5-Codex.
May 2025HealthBenchA rubric-graded evaluation of open-ended health conversations, an example of rubric grading for domains without a single correct answer.
Aug 2025GPT-5A unified system with a router; reasoning effort exposed to developers; followed by GPT-5.x releases.
—Reinforcement fine-tuning APICustomers bring graders; OpenAI runs the RL.
Anthropic
Dec 2022Constitutional AIRLAIF: model-generated critiques, revisions and preference labels guided by written principles.
Feb 2025Claude 3.7 SonnetExtended thinking with a user-set budget; first release of Claude Code, an agentic terminal coding tool.
May 2025Claude 4, later Claude Sonnet 4.5Release materials emphasize coding, tool use and longer tasks; interleaved thinking between tool calls. The Claude 4 system card reports measured rates of test special-casing. Anthropic publishes separate research on the faithfulness and monitorability of reasoning traces.
2025Reward hacking and misalignmentLearning to hack rewards generalized to broader misalignment; “inoculation prompting” introduced as a training-time mitigation.
Google DeepMind
2024AlphaProofRL in Lean, where the proof assistant verifies generated proofs. Training also generates and proves or disproves large numbers of formal problems.
Mar 2025Gemini 2.5Presented as “thinking models.” A developer-set thinking budget arrived with Gemini 2.5 Flash in April 2025.
May 2025AlphaEvolveGemini-driven evolutionary search with automated evaluators; found new algorithms and datacenter optimizations.
Jul 2025Deep Think at IMOParallel, multi-hypothesis reasoning trained with “novel RL techniques”; gold-medal level at IMO 2025 in natural language.
—Gemini 3Later Gemini releases extend reasoning across multimodal inputs.
—Jules, Gemini CLI, Project MarinerAgent products. That they are RL-trained on coding and browsing environments is inferred from the model posts, not separately documented.
DeepSeek
Feb 2024DeepSeekMathIntroduced GRPO: group-normalized advantages without a learned value model.
Jan 2025DeepSeek-R1; R1 in NatureR1-Zero: RL directly on the base model with rule-based accuracy and format rewards, no SFT. R1: cold-start SFT, reasoning RL, rejection sampling, and a final RL stage for helpfulness and harmlessness. Reasoning traces distilled into smaller Qwen and Llama models.
Alibaba Qwen
Apr 2025Qwen3Unified thinking and non-thinking modes; four-stage post-training: long chain-of-thought cold start, reasoning RL, mode fusion, general RL.
Jul 2025Qwen3-Coder“Agentic RL” on real software tasks, with 20,000 independent environments running in parallel on Alibaba Cloud.
Jul 2025GSPOSequence-level importance ratios and clipping; reported necessary for stable RL on large mixture-of-experts models.
Moonshot AI (Kimi)
Jan 2025Kimi k1.5RL with long-context scaling and a length penalty for short chain-of-thought models; online policy mirror descent instead of PPO.
Jul 2025Kimi K2A 1-trillion-parameter mixture-of-experts model. Large-scale synthetic agentic tool-use data, then a joint RL stage mixing verifiable rewards with a self-critique rubric reward for tasks without a checker.
xAI
Feb 2025Grok 3Reasoning mode.
Jul 2025Grok 4Stated to use as much compute on RL as on pretraining, with native tool use trained in; Grok 4 Heavy runs multiple agents in parallel at test time. Few algorithmic details.
Meta
2024Llama 3 paperIterative rounds of rejection sampling, SFT and DPO, deliberately avoiding PPO for stability and scale.
Apr 2025Llama 4“Continuous online RL” with a curriculum that filters to medium and hard prompts, alternating training and prompt filtering.
Mistral, ByteDance and others
Mar 2025DAPO; verlByteDance Seed’s RL system paper (clip-higher, dynamic sampling, token-level loss) and its open-source training framework.
2025AReaLAsynchronous RL that decouples generation from training. Other open infrastructure: OpenRLHF, TRL, PRIME-RL and Prime Intellect’s Environments Hub, slime, SkyRL, and a market of “RL environment” vendors.
Jun 2025MagistralMistral’s reasoning models trained with “pure RL” from Mistral Medium, using a modified GRPO: no KL term, clip-higher, minibatch normalization.
Jun 2025MiniMax-M1CISPO, which clips importance weights instead of token updates; diagnosis of numerical mismatch between the training and inference systems.

The algorithms, in order

YearMethodWhat it changed
1992REINFORCEWilliams’s likelihood-ratio policy-gradient estimator, which underlies most later policy-gradient methods.
2015TRPOTrust-region policy optimization: bound the policy change per step.
2017PPOA clipped surrogate objective that permits several minibatch updates on the same sampled data.
2017RL from human preferencesChristiano et al. learned a reward model from human comparisons of trajectories.
2019Preferences for GPT-2Ziegler et al. applied RL from human preferences to a language model.
2022InstructGPTOpenAI documented a pipeline of supervised fine-tuning, reward modeling and PPO.
2023DPOPreference optimization without a separate reward model or on-policy sampling.
2024GRPOGroup-normalized advantages, no critic.
2025DAPO, Dr. GRPOClip-higher, dynamic sampling, token-level loss, length-bias fixes.
2025GSPO, CISPOSequence-level ratios; importance-weight clipping; off-policy corrections.

Public releases through mid-2026 point in one general direction: longer coding and research trajectories, more parallel environments, and more asynchronous training infrastructure.

Open problems

Long-horizon credit assignment
A trajectory-level reward does not show which earlier decisions caused the outcome. Process rewards, turn-level judges and hierarchical policies give denser signals, but each can introduce new grader errors.
Environment construction
Useful agent training needs realistic tasks with a reproducible starting state and reliable grading. Teams build and synthesize such tasks, then filter or validate them with tests and verifiers.
Reward hacking at scale
A fixed grader can contain exploitable gaps. Held-out checks and chain-of-thought monitoring reveal some failures, while optimizing directly against a monitor can teach a model to hide the behavior being monitored.
Exploration and entropy collapse
Some RL runs concentrate on a small set of responses, and output diversity drops. Asymmetric clipping, entropy bonuses and prompt curricula are among the methods used to preserve useful exploration.
Capability elicitation
Researchers disagree about how much RL creates new strategies and how much it shifts probability toward behaviors the base model could already produce. Results depend on the task, training horizon and metric.
Generalization from narrow rewards
Gains on math or code do not guarantee better instruction following, calibration or performance in other domains. Mixed training objectives try to preserve several behaviors at once.
Infrastructure
Large runs coordinate generation, sandboxed environments, training and evaluation. Asynchronous rollouts improve hardware use but make policy staleness and importance weighting harder to control.
Self-play and self-verification
Formal systems can verify generated proofs and support self-play. Open-ended domains lack an equally reliable verifier, which makes self-generated tasks and rewards harder to validate.
Evaluation
Static benchmarks saturate or leak into training data. Held-out tasks, live evaluations and carefully isolated agent environments reduce these problems without eliminating them.

Glossary

Policy (π)
The model being trained, viewed as a probability distribution over actions given its observation or context.
Rollout, trajectory
One sampled episode: a sequence of observations, model actions and rewards.
Reward
A scalar signal from the environment, a verifier or a reward model. It can arrive during a trajectory or at the end.
Return-to-go
The sum of rewards from the current action onward, optionally discounting later rewards. Subtracting a baseline gives a sampled advantage estimate.
Advantage
How much better an action or episode was than expected; the quantity that scales each gradient step.
Baseline, critic, value model
A baseline estimates the expected return for the advantage calculation. PPO is commonly used with a learned value function; GRPO uses group reward statistics.
On-policy, off-policy
Whether the samples used for an update came from the current policy. Stale samples need importance-weight corrections.
KL penalty
A regularization term that penalizes divergence from a reference policy.
RLHF
RL from human feedback: a reward model trained on preference comparisons, then policy optimization against it.
RLAIF
RL from AI feedback: model-generated evaluations supply some or all of the reward signal.
RLVR
RL with verifiable rewards: the reward is a program, such as an answer checker, unit tests, a compiler or a proof assistant.
PPO
Proximal Policy Optimization: a policy-gradient method with a clipped surrogate objective, commonly paired with a learned value function.
GRPO
Group Relative Policy Optimization: a PPO variant that normalizes rewards across responses to the same prompt and has no learned value model.
DPO
Direct Preference Optimization: an objective that updates a policy directly from preference pairs and a reference policy, without fitting an explicit reward model.
Process reward model (PRM)
A grader that scores intermediate steps as well as the final result.
Loss masking
Excluding environment-produced tokens, such as tool outputs, from the training loss in multi-turn episodes.
Reward hacking, specification gaming
Achieving high measured reward through behavior that violates the task designer’s intent.
Entropy collapse
A large drop in output diversity during training, leaving fewer behaviors available for exploration.
Test-time compute
Spending more inference tokens, through longer reasoning or more samples, to improve accuracy on a single query.