ELLMEngineering Large
Language Models
Download PDF

Chapter 17

Reinforcement Learning for Reasoning and Tool Use

On this page

Reinforcement learning adjusts the probability of actions using outcomes from sampled trajectories. To understand current reasoning training, follow one trajectory from generation through reward, advantage, policy update, and a fresh held-out evaluation.

Tokens are actions; the conversation is state

For text generation, the state includes the prompt and previously generated tokens. An action is the next token. For a tool-using agent, external observations and environment state also influence future decisions. A trajectory ends at an answer, failure, timeout, or explicit task boundary. Rewards may arrive at intermediate steps or only at the end.

A policy-gradient update increases log probability for actions with positive advantage and decreases it for actions with negative advantage. Advantage means outcome relative to an appropriate baseline, not simply “the answer was correct.” Subtracting a baseline can reduce estimator variance, but the baseline and normalization determine how prompts are weighted.

Terminal reward offers weak credit assignment: every sampled action may inherit a signal from the final result, including unnecessary prose and accidental shortcuts. A process reward can give finer feedback but may itself be incorrect. Neither establishes that a visible chain of thought faithfully describes the computation that produced an answer.

PPO: distinguish the old policy from the reference

Rollouts carry sampled actions and their behavior-policy probabilities into the learner. Rewards and advantages provide the learning signal, while a separate reference policy can regularize the update. Newly published weights refresh the behavior policy.
Open full diagram ↗

Rollouts carry sampled actions and their behavior-policy probabilities into the learner. Rewards and advantages provide the learning signal, while a separate reference policy can regularize the update. Newly published weights refresh the behavior policy.

PPO uses a clipped surrogate to limit incentives for large policy changes on sampled actions. Let r_t be the new policy's probability of the sampled action divided by its probability under the behavior policy that collected the rollout. A simplified term to maximize is:

2026-10-12T12:02:55.384801 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Clipping limits the benefit of moving a sampled action too far in the advantageous direction.

For advantage +2, ratio 1.4, and epsilon 0.2, the clipped term is 2.4, not 2.8. For advantage -2 and ratio 0.6, it is -1.6, not -1.2. The minimum matters for both signs. This does not guarantee a hard bound on policy divergence; other actions and shared parameters also move.

The old/behavior policy supplies the sampling probabilities for the ratio. The reference policy supplies a regularization anchor, often an SFT checkpoint. A critic estimates future return or a value baseline. A reward model or verifier scores outcomes. These roles can share architectures but are not interchangeable. Classic actor-critic PPO usually trains a value estimator and may use generalized advantage estimation; omitting it changes how advantage is obtained.

GRPO: use a group of outcomes as the baseline

DeepSeekMath introduced Group Relative Policy Optimization. Sample several responses to the same prompt, evaluate their rewards, and obtain a relative advantage from the group's mean and, in the normalized form, standard deviation. This avoids a separate learned critic for that baseline, but still requires policy, rollout, and reward computation.

For rewards [1,1,0,0], the mean is 0.5 and population standard deviation is 0.5; standardized advantages are [1,1,-1,-1]. For [1,1,1,1], there is no within-group contrast. A safe implementation assigns zero contrast instead of dividing by zero. The group therefore needs useful diversity: all-correct and all-wrong groups carry little or no relative reward signal.

This creates an important data tradeoff. Easy prompts can become uninformative, while very hard prompts may never yield a successful trajectory. Increasing group size can expose contrast but consumes more rollout tokens and verifier calls. Filtering zero-variance groups changes the effective training distribution; record attempted prompts and discarded groups, not just the accepted training batch.

Reward normalization is a choice, not a harmless cosmetic step. Dividing by group standard deviation changes the scale across prompts; averaging each response's token loss can change length weighting. An implementation must specify reward normalization, token/sequence normalization, response masks, KL placement, and clipping. Two programs both called GRPO can optimize measurably different objectives.

What newer variants are trying to repair

Approach Mechanism-level change Decision to inspect
DAPO Decoupled clipping, dynamic sampling, token-level loss aggregation, and explicit treatment of overlong responses Are entropy collapse, uninformative groups, or truncation dominating?
GSPO A length-normalized sequence likelihood ratio and sequence-level clipping/optimization Is token-level importance weighting unstable for the model and rollout distribution?
Outcome/process reward mixtures Add signals at different parts of the trajectory Does finer credit improve held-out success, or only reward the checker's preferred style?
On-policy distillation Train on states visited by the student using teacher feedback Is teacher-forced training missing the student's actual error distribution?

The primary descriptions are DAPO and GSPO. These methods should be compared as concrete objectives and pipelines, not stacked as independent switches. A wider upper clipping range, for example, changes the incentive to increase low-probability successful actions; it is not a universal fix for poor exploration.

For GSPO's normalized sequence ratio, average token log-probability differences and exponentiate. If two token probability ratios are 2 and 0.5, their geometric mean is 1, while their arithmetic mean is 1.25. Using the latter implements the wrong quantity. Length normalization helps control scale but is not the full trajectory importance ratio, which would multiply all token ratios. The scalar reference checks this distinction.

For truncation, distinguish a genuinely wrong completed answer from a trajectory cut off by a budget or failed environment. Giving every timeout the same semantic reward as an invalid solution can teach the wrong lesson. Conversely, dropping all failures without reporting them hides the true cost and can bias training toward easy tasks. Define the censoring and reward policy before interpreting improvements.

Rich feedback and self-distillation: a 2026 direction

A scalar failure says little about which action to change. Self-Distillation Policy Optimization, a 2026 study, conditions a self-teacher on feedback and distills its feedback-informed predictions into the policy. The teaching idea is to turn information such as a compiler error into a richer learning signal rather than reducing every failed attempt to the same zero reward.

For an original toy task, suppose a model writes a function with the wrong argument order. A trusted error message identifies the mismatch. A feedback-conditioned teacher distribution may put more mass on the corrected call, while the student must learn to make that call without seeing the future error at deployment. The training pipeline must keep teacher-only feedback out of the student's evaluation input and detach the target distribution appropriately. Otherwise it measures access to an answer hint, not learning.

This is not a license to trust every self-generated correction. The July 2026 preprint Denser Is Not Better reports forgetting and drift in its continual post-training experiments. The September 2 preprint Learn from Whoever Is Right explores answer-verified multi-teacher distillation. These are emerging findings with different experimental settings, not a settled ranking of RL objectives.

When studying this family, track who supplies feedback, which tokens the teacher sees, which distribution supplies student trajectories, which parameters are updated, and whether old capabilities survive. An external teacher, a self-teacher with privileged context, and an outcome verifier supply different information even if all produce a training target.

Verifiable reward needs an independently protected verifier

RL with verifiable rewards is useful when outcomes can be checked: execution tests, formal proof checking, exact structured answers, or environment success conditions. DeepSeek-R1 is an important example of reasoning-oriented reinforcement learning, but its reported results do not imply that any base model becomes broadly capable from a sparse binary reward alone.

Consider a code task with visible examples and hidden tests. The model receives a sandbox with source files and a way to submit a patch. Hidden tests and the scoring program live outside its writable scope. The verifier distinguishes compilation failure, test failure, infrastructure failure, timeout, and valid success. Network, filesystem, subprocess, and resource permissions are enforced by the environment, not by an instruction asking the model to behave.

Protect the held-out task set from prompt generation, selection, reward tuning, and synthetic-data construction. Generate adversarial verifier tests: empty output, fake success logs, modified tests, hardcoded examples, and attempts to read the checker. A rising training reward accompanied by unchanged hidden-test success is a reward-model problem until shown otherwise.

From one batch to the next

Example status: Explanatory pseudocode.

publish immutable actor snapshot v
sample prompt groups from a versioned task mixture
generate trajectories with v; save behavior log probabilities
run protected verifiers; distinguish failures from missing labels
compute advantages under the declared normalization policy
recompute current-policy log probabilities on scored action tokens
apply clipped objective and any explicit reference regularizer
check finite gradients; update actor and optimizer consistently
evaluate on independent tasks at a fixed sampling/token budget
publish v+1 only after release checks; retain rollback snapshot

Tool-result tokens are observations, not actions sampled from the actor, and normally should not enter the actor's action log-probability objective. Store token/action masks explicitly. For multi-turn trajectories, preserve tool versions, environment seeds, reset state, and termination reasons; replaying only the visible final answer is insufficient.

Suppose 128 prompts receive eight rollouts each, averaging 1,024 generated tokens. That is 1,048,576 generated tokens before verification and training. At an illustrative aggregate rollout rate of 20,000 tokens per second, generation alone takes at least 52.4 seconds. If optimization takes 12 seconds, making the optimizer twice as fast saves only six seconds from a serial cycle dominated by generation. This calculation explains why inference kernels and rollout scheduling are part of training research.

HybridFlow addresses the interaction between model roles and distributed execution. The architectural lesson is to plan training and generation layouts together. Their best parallel groups and memory allocations can differ, and switching representations or moving weights has a cost. Part V follows the ownership and staleness consequences rather than treating the RL library as a black box.

Measure learning, not only pass at a larger budget

Report single-sample success under a fixed generation budget, success with multiple candidates, the selection rule, and total inference/verifier cost. The probability that at least one candidate is correct is not the same as the ability to choose that candidate without an oracle. Majority voting, a learned judge, and executable selection have different failure modes.

For n independent identically sampled candidates containing c correct ones and 1 <= k <= n, the pass-at-k estimator used in Evaluating Large Language Models Trained on Code is 1 - choose(n-c,k)/choose(n,k), with result one when fewer than k candidates are wrong. The reference pass_at_k(10,2,3) returns about 0.533. It estimates an at-least-one-success event under the sampling assumptions, not the quality of the model's first answer. Correlated task variants and repeated tuning on a benchmark require separate caution.

Track answer length, entropy, group reward variance, discarded prompts, clipping fraction, KL estimates, verifier error rates, and behavior-policy age. Separate gains from better reasoning, more sampling, different tools, and relaxed time budgets. A shorter iteration loop is valuable only if it produces valid evidence about learning.

Exercises and worked answers

  1. Why is a reference model not the PPO denominator? The denominator is the policy that sampled the action. The reference is a regularization choice and may remain fixed across many updates.
  2. What happens to an all-wrong binary-reward group? Its within-group contrast is zero. Resampling or changing task difficulty may help, but changes the compute cost and training distribution.
  3. Can average pass-at-8 rise while average pass-at-1 falls? Yes, across a task distribution. Suppose two equally weighted tasks have independent per-sample success probabilities [0.9,0.1], changing to [0.5,0.4]. Average pass-at-1 falls from 0.50 to 0.45, while average pass-at-8 rises from about 0.785 to 0.990. For a single fixed task with i.i.d. samples, however, pass-at-k is 1-(1-p)^k, which increases monotonically with per-sample success p. Do not confuse pass-at-1 with greedy-decoding accuracy.
  4. What is wrong with rewarding a process's printed PASS? The actor can print it. The trusted verifier must inspect independently protected execution results, not accept self-reported success.
  5. Which first optimization fits the numerical cycle above? Improve valid rollout throughput or overlap before assuming optimizer speed dominates; include verifier capacity and policy staleness in the measurement.

Part II closing principle

Part III takes the trained checkpoint, tokenizer, and generation settings into a serving system and calculates its latency and memory requirements.