Skip to content
ImagineWorld

Reasoning with Reinforcement Learning

node_idnode-book_building-frontier-llm-from-scratch_chapter-25-reasoning-with-reinforcement-learning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num25
chapter_titleReasoning with Reinforcement Learning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 25 — Reasoning with Reinforcement Learning

Section titled “Chapter 25 — Reasoning with Reinforcement Learning”

For years, getting a model to reason meant prompting it to “think step by step” and hoping. DeepSeek-R1 changed that by showing reasoning can be trained directly with reinforcement learning — not against human preferences, but against automatically verifiable rewards, like whether a math answer is correct or a program passes its tests. The result was a model that learned, on its own, to deliberate: to pause, reconsider, and check its work. The algorithm behind it, GRPO, is elegant and efficient, and the recipe is reproducible. This chapter is one of the most important in the book: it builds GRPO, explains the R1-Zero and R1 pipelines, and shows how their reasoning was distilled into small models.

Reasoning problems have a property that ordinary chat does not: many of them can be checked. A math problem has a known answer; a coding problem has unit tests; a logic puzzle has a verifiable solution. This means we can score a model’s full chain of thought by a simple, honest, unhackable rule — did it get the right answer? — without any neural reward model to game.

Reinforcement learning is the natural fit: let the model generate long reasoning traces, reward the ones that reach correct answers, and the model learns to produce more of whatever thinking led there. Crucially, we do not tell it how to reason; we only reward reaching the right answer, and let the reasoning strategy emerge.

25.2 GRPO: Group Relative Policy Optimization

Section titled “25.2 GRPO: Group Relative Policy Optimization”

PPO (Chapter 23) needs a separate value model — as large as the policy — to estimate a baseline for the advantage. GRPO (Group Relative Policy Optimization), introduced in DeepSeek-Math, removes it with a simple idea: for each prompt, sample a group of responses, and use the group’s average reward as the baseline. A response is “good” if it beats the average of its siblings on the same prompt. This eliminates the value model entirely — halving the large models in memory — and provides a naturally normalized advantage. The core step:

def grpo_step(policy, ref, prompt, reward_fn, group=8, beta=0.04, eps=0.2):
responses = policy.sample(prompt, n=group) # a group of G outputs
rewards = torch.tensor([reward_fn(prompt, r) for r in responses])
# group-relative advantage: the group mean is the baseline (no value model)
adv = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
for resp, a in zip(responses, adv):
logp = policy.logprob(prompt, resp) # current policy
ratio = torch.exp(logp - logp.detach()) # vs behavior policy
clipped = torch.clamp(ratio, 1 - eps, 1 + eps) # PPO-style clip
pg_loss = -torch.min(ratio * a, clipped * a).mean()
kl = (logp - ref.logprob(prompt, resp)).mean() # stay near reference
(pg_loss + beta * kl).backward()

Python — grpo.py: the core GRPO update (simplified)

The structure echoes PPO — a clipped policy-gradient objective with a KL penalty toward a reference — but the advantage comes from the group, not a learned critic. Responses above the group mean get a positive advantage and are reinforced; those below are suppressed. Because the reward here is a verifiable rule rather than a neural model, the chronic reward-hacking of Chapter 23 largely disappears: there is no reward model to fool, only a correct answer to find. Table 25.1 contrasts the two algorithms.

AspectPPOGRPO
Baseline for advantagea learned value modelthe group’s mean reward
Extra large modelyes (value/critic)no
Rewardtypically a neural reward modelverifiable rule (accuracy, tests)
Reward hackinga constant concernlargely avoided

Table 25.1 — PPO versus GRPO

Figure 25.1. GRPO. For each prompt, a group of responses is sampled and scored by a verifiable reward; each response’s advantage is its reward minus the group mean. Above-average responses are reinforced, below-average ones suppressed — no separate value model required.

25.3 DeepSeek-R1-Zero: Reasoning from Pure RL

Section titled “25.3 DeepSeek-R1-Zero: Reasoning from Pure RL”

The most surprising result came first. DeepSeek-R1-Zero applied GRPO directly to a base model — no supervised fine-tuning at all — with a strikingly simple reward: an accuracy reward (is the final answer correct?) plus a format reward (did the model put its reasoning between tags?). Nothing taught it how to reason. Yet over training, the model spontaneously developed sophisticated reasoning behavior: it learned to allocate more thinking to harder problems, to backtrack when a line of reasoning failed, and — in a widely noted “aha moment” — to explicitly reconsider its own work mid-solution. Reasoning strategies emerged from nothing but the pressure to reach verifiable correct answers. R1-Zero’s main flaw was readability — its raw chains of thought mixed languages and were hard to follow — which the full R1 recipe set out to fix.

DeepSeek-R1 wraps the pure-RL core in a multi-stage pipeline that preserves the emergent reasoning while making the model readable and broadly capable. The stages, in order (Table 25.2): a small cold-start SFT on a few thousand high-quality long reasoning traces to establish a clean format; reasoning RL with GRPO on verifiable problems; rejection sampling to harvest the best generated solutions into a large new SFT set; another SFT combining that reasoning data with general instruction data; and a final RL stage covering all scenarios, including helpfulness and harmlessness. The result is a model with frontier reasoning that is also a usable general assistant.

StageStepPurpose
1Cold-start SFTa clean, readable reasoning format to start from
2Reasoning RL (GRPO)learn to reason via verifiable rewards
3Rejection samplingcollect the best generated solutions as new data
4SFT (reasoning + general)fold in broad capability and instruction-following
5Final RL (all scenarios)align helpfulness, harmlessness, and reasoning

Table 25.2 — The DeepSeek-R1 training pipeline

25.5 Distilling Reasoning into Small Models

Section titled “25.5 Distilling Reasoning into Small Models”

A final, practical discovery: the reasoning of a large R1 model can be distilled into much smaller dense models simply by fine-tuning them on R1’s generated reasoning traces. DeepSeek released such distilled models built on small Qwen and Llama bases, and they reason far better than models of their size trained any other way — strong evidence that, once a large model has discovered how to reason, that skill transfers cheaply. The next chapter takes up distillation and quantization in general, the two techniques that turn an expensive frontier model into something that runs on modest hardware.

Remarkably, running GRPO yourself is nearly as short as the loss. The distinctive part is that you supply the reward function — a plain Python function that scores a completion, here checking a math answer — and trl’s GRPOTrainer handles the group sampling, advantages, and updates of the algorithm above:

from trl import GRPOTrainer, GRPOConfig
def reward_correct(completions, answer, **kw):
# +1 if the model's final answer matches, else 0 (verifiable)
return [1.0 if extract(c) == a else 0.0
for c, a in zip(completions, answer)]
trainer = GRPOTrainer(
model=model,
reward_funcs=reward_correct, # the rule-based reward
args=GRPOConfig(num_generations=8, beta=0.04),
train_dataset=math_problems,
)
trainer.train()

Python — huggingface/trl: GRPO with a verifiable reward (reproduced, Apache 2.0)

The pieces line up with the algorithm exactly: num_generations is the group size g sampled per prompt; beta is the KL coefficient toward the reference; and reward_funcs is the verifiable reward at the heart of the method — note that it is ordinary code that checks correctness, not a trained neural network, which is precisely why reward hacking is so muted. This is the same machinery that produced DeepSeek-R1, available to anyone with a model, a set of checkable problems, and a GPU. The DeepSeek-R1 report details the reward design and the five-stage pipeline, and DeepSeekMath introduced GRPO; R1 remains among the most reproducible frontier results ever published, and these are the primary sources.

With reasoning trained in, the model is, at last, complete as an artifact: pretrained, aligned, and able to reason. Part VII turns to the practical reality of using it — serving it efficiently to many users, and evaluating it honestly — before the final part assembles everything into your own model.

GRPO’s defining move (Chapter 25) is to drop the value network: instead of estimating a baseline, it samples a whole group of answers to the same prompt, scores each, and normalizes within the group. The normalized reward IS the advantage:

rewards = torch.tensor([reward(prompt, a) for a in group]) # (G,)
# advantage = how much better than the group's own average
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
ratio = (logp_new - logp_old).exp() # importance ratio
loss = -torch.min(ratio * advantages,
ratio.clamp(0.8, 1.2) * advantages).mean()
loss = loss + beta * kl_to_reference # stay near the SFT model
# no critic, no value targets — just relative ranking within each group

Python — GRPO: group-relative advantage with a KL leash

The reason GRPO works so well on reasoning is not the optimizer alone — it is what the optimizer is pointed at. RLHF (Chapter 23) learns a reward model because “helpful” cannot be written as a function. But “correct” often can. For mathematics, does the final answer match the gold solution? For code, do the unit tests pass? For format, did the model wrap its reasoning in the required tags? These verifiable rewards are programmatic, exact, and immune to the kind of exploitation that plagues a learned reward model:

def reward(completion, task):
r = 0.0
if extract_answer(completion) == task.gold:
r += 1.0 # correctness dominates
if has_tags(completion, "<think>", "</think>"):
r += 0.1 # light shaping toward format
return r

Python — grp0/reward.py: a verifiable, programmatic reward

The failure mode shifts accordingly. A learned reward model invites reward hacking (Section 23.6); a verifiable reward invites sparsity. If not a single sample in a group solves the problem, every reward is zero, the advantages are all zero, and the update carries no signal. This is why reasoning RL leans on a curriculum that keeps problems near the edge of the model’s ability, and on group sizes large enough that some sample usually succeeds — the design problem is no longer trust, but ensuring a gradient exists at all.

25.8 Worked Example: A GRPO Update from One Group

Section titled “25.8 Worked Example: A GRPO Update from One Group”

Section 25.2 defined the group-relative advantage; here it is in arithmetic. For one prompt, sample a group of four completions and score each with the verifiable reward above. The advantage of each is its reward, centered on the group mean and scaled by the group’s standard deviation:

rewards = torch.tensor([1.0, 0.0, 1.0, 0.0]) # G=4 sampled answers
adv = (rewards - rewards.mean()) / (rewards.std() + 1e-6)
# adv approx [ +0.87, -0.87, +0.87, -0.87 ]
# -> raise the probability of the two correct traces, lower the two wrong

Python — grp0/advantage.py: the group is its own baseline

The decisive detail is what is absent. PPO (Chapter 23) needs a value network to estimate a baseline for each token; GRPO simply uses the group’s mean reward as that baseline. No critic, no value head, no GAE — the comparison among siblings supplies everything. That single substitution roughly halves the memory of the RL stage and removes an entire model from the training loop, which is why a method this simple could be scaled to produce DeepSeek-R1’s reasoning (Section 25.3).

The group replaces the critic PPO asks a learned value function “how good was this token, on average?” GRPO asks “how did this whole answer compare to its siblings from the same prompt?” The second question needs no extra network — the baseline falls out of sampling several answers and centering on their mean.

GRPO removes PPO’s critic (Section 25.8) but keeps two of its stabilizers: the clipped importance ratio that prevents any single update from moving the policy too far, and a KL penalty that holds the policy near its reference. Each token’s contribution combines the group-relative advantage with a clipped probability ratio:

ratio = (new_logp - old_logp).exp() # importance ratio
clipped = torch.clamp(ratio, 1 - eps, 1 + eps)
loss = -torch.min(ratio * adv, clipped * adv).mean()
loss = loss + beta * kl_to_reference # stay near the reference

Python — grp0/objective.py: clipped ratio plus KL (illustrative)

The clipping is what makes the update safe to apply over several gradient steps on the same batch of samples. Without it, a token whose probability ratio has drifted far from one could dominate the update and destabilize the policy; the min of the clipped and unclipped terms caps how much any token can push, exactly as in PPO. The KL term plays the role it did in Section 23.6, leashing the policy to its reference so that reasoning improvements do not come at the cost of fluency or safety. What GRPO discards is only the critic — the learned value baseline — not the broader machinery of safe policy updates, which is why it remains stable enough to train reasoning models at scale.

Lighter than PPO, not reckless GRPO drops the value network but keeps PPO’s clipped objective and KL leash. The group mean replaces the critic’s baseline; everything that keeps the update safe stays. Simplicity, not abandon, is the design.

25.10 R1-Zero versus R1: The Role of Cold-Start Data

Section titled “25.10 R1-Zero versus R1: The Role of Cold-Start Data”

The DeepSeek-R1 work (Section 25.3) ran a revealing two-part experiment that sharpens what reinforcement learning can and cannot do alone. R1-Zero applied GRPO directly to a base model with no supervised fine-tuning whatsoever — pure RL against verifiable rewards. Remarkably, sophisticated reasoning emerged: the model learned to produce long chains of thought, to check its work, even to exhibit what looked like reconsideration. RL alone was enough to elicit the capability.

But R1-Zero’s outputs had problems that made them hard to use — mixed languages, poor readability, a tendency to ramble — because nothing in a purely outcome-based reward rewards legibility. The full R1 recipe fixed this by prepending a small amount of curated “cold-start” supervised data: a modest set of clean, well-formatted reasoning traces used to fine-tune the base model before the RL stage. This cold start gave the model a readable starting style, which the subsequent GRPO then improved upon without the legibility collapsing. The lesson is a general one for the reasoning frontier (Chapter 38): pure RL can discover capability that no one demonstrated, but a little supervised data is what makes that capability usable — the two are complementary, not competing, and the cheapest path to a strong reasoning model uses both.

RL discovers, SFT civilizes R1-Zero showed reasoning can emerge from pure RL; R1 showed a little cold-start SFT is what makes it readable. Capability and usability come from different stages — elicit with RL, polish with a touch of supervision.

‘GRPO with verifiable rewards (Section 25.7) is only as good as the ‘reward it optimizes, and designing that reward is often the hard ‘part of reasoning RL — harder than the training itself. A good verifiable reward has three properties, and failures of reasoning-RL projects can usually be traced to violating one of them.

It must be unambiguous: there is a clear, checkable notion of correct, so the reward is a fact rather than a judgment. Mathematics (does the final answer match?) and code (do the tests pass?) are ideal precisely because correctness is mechanical. It must be hard to game: the model should not be able to earn the reward without actually doing the task. A reward that can be satisfied superficially invites the model to find the shortcut instead of learning the skill — the same reward-hacking hazard as Section 23.6, now in the verifiable setting, where a poorly specified checker becomes the thing the model learns to fool. And it must be reachable: the model must succeed at least occasionally, because reinforcement learning can only reinforce behavior it sometimes produces — a reward so sparse that the model never stumbles onto success provides no gradient to climb. The art is in the balance: a reward strict enough to be meaningful, robust enough to resist gaming, and attainable enough to be learnable. When all three hold, the verifiable-reward recipe (Section 25.3) is remarkably powerful; when one fails, no amount of GRPO tuning will rescue the run, because the problem is the target, not the optimizer.

The reward is the hard part A verifiable reward must be unambiguous, hard to game, and reachable. Math and code qualify naturally; a sloppy checker gets fooled, and a too-sparse reward never starts. Reasoning RL succeeds or fails on the reward’s design, not the optimizer’s.

A defining property of GRPO, and of PPO before it, is that they are on-policy: they learn from samples generated by the current policy, and as the policy updates, fresh samples must be generated to match. This is why every iteration of these methods includes a generation step — the model samples responses to prompts, those responses are scored, and the policy is updated on them (Section 25.6). It is also why they are expensive: generation is costly, and it must be repeated as the policy moves.

The contrast with DPO (Chapter 24) is instructive. DPO is off-policy in the relevant sense — it trains on a fixed, pre-collected dataset of preference pairs, generated once, with no sampling loop during training. That makes DPO far cheaper, but it forgoes something on-policy methods have: the ability to explore. Because GRPO samples from the current policy, it discovers the policy’s own current mistakes and successes and learns from exactly the distribution of behavior the model actually produces — which is what lets it push into new reasoning strategies (Section 25.3) rather than only sorting a static set of options. The trade is fundamental to reinforcement learning: on-policy methods are costly because they must keep generating, but that same generation is what lets them improve a policy beyond the behaviors present in any fixed dataset. The choice between an on-policy method like GRPO and an off-policy one like DPO is therefore partly a choice between exploration and economy — and it explains why the most capable reasoning models, which need to discover strategies no dataset demonstrated, are trained with the expensive on-policy approach.

Generate to explore, or reuse to economize On-policy methods like GRPO sample from the current policy each step — costly, but able to explore beyond any fixed dataset. Off-policy DPO trains on pre-collected pairs — cheap, but bounded by what was collected. Exploration versus economy.