Expert about 7 h
The picture
01
Prompt
with checkable answer
02
Sample a group
G completions
03
Reward
programmatic
04
Advantage
relative to group
05
Policy update
with KL
The idea
For some tasks you do not need a learned judge: you can check the answer by program. A maths answer matches or it does not; code passes tests or it does not; JSON validates or it does not. Reinforcement learning with verifiable rewards samples several attempts, rewards the ones that verify, and shifts the model towards the strategies that produced them. Long step-by-step reasoning tends to emerge because it raises the pass rate.
GRPO in one formula
Group Relative Policy Optimisation samples a group of completions for each prompt and uses the group itself as the baseline, so no separate value network is needed:
Completions better than their siblings get positive advantage and become more likely; worse ones less. A KL term to a reference model limits drift.
import torch
def group_advantages(rewards: torch.Tensor, eps: float = 1e-4) -> torch.Tensor:
"""rewards: (num_prompts, G)"""
mean, std = rewards.mean(1, keepdim=True), rewards.std(1, keepdim=True)
return (rewards - mean) / (std + eps)
print(group_advantages(torch.tensor([[1., 0., 0., 1.], [0., 0., 0., 0.]])))
# the second prompt: all rewards equal, so advantages are 0, there is no learning signal
Prompts that are always solved or never solved teach nothing, so choose problems of intermediate difficulty.
Rewards you can program
import re
def extract_boxed(text: str) -> str | None:
m = re.findall(r"\\boxed\{([^{}]*)\}", text)
return m[-1].strip() if m else None
def correctness_reward(completions, answer, **kwargs):
return [1.0 if extract_boxed(c) == str(a).strip() else 0.0 for c, a in zip(completions, answer)]
def format_reward(completions, **kwargs):
return [0.2 if re.search(r"<think>.+?</think>\s*\\boxed\{.+?\}", c, re.S) else 0.0 for c in completions]
With TRL
from datasets import load_dataset
from trl import GRPOTrainer, GRPOConfig
# rows: {"prompt": "... put the final answer in \\boxed{}", "answer": "42"}
ds = load_dataset("json", data_files="math_train.jsonl", split="train")
cfg = GRPOConfig(output_dir="out/grpo", num_generations=8, learning_rate=1e-6, beta=0.04,
per_device_train_batch_size=8, gradient_accumulation_steps=4, max_completion_length=512,
bf16=True, logging_steps=5)
trainer = GRPOTrainer(model="Qwen/Qwen2.5-0.5B-Instruct", reward_funcs=[correctness_reward, format_reward],
args=cfg, train_dataset=ds)
trainer.train()
Columns from your dataset (like answer) are passed to the reward functions as keyword arguments. Start with a small model and an easy problem set to see rewards climb before scaling up.
How R1-style recipes are put together
A common recipe starts with a small set of reasoning examples for a cold-start SFT so outputs are readable, then runs large-scale RL with verifiable rewards, then does rejection sampling (keep only correct, well-formatted samples) to build a new SFT set, and finishes with a round of preference tuning. Smaller models are then improved by distilling from the reasoning model's outputs, which has been reported to work better than running RL directly on the small model.
Outcome versus process rewards
Outcome rewards judge only the final answer: simple and hard to game on verifiable tasks, but sparse. Process rewards score each step: denser, but need a trained step verifier or human labels, and can be gamed.
What goes wrong
- Reward hacking: models learn to satisfy the checker, not the task (printing the expected answer from a leaked test, matching format without reasoning). Read samples, not just reward curves.
- Collapse of response length or runaway length growth. Monitor length.
- Weak verifiers: a lenient answer matcher rewards luck.
- Narrow gains: improvement on the training distribution that does not transfer. Evaluate on held-out problem types.
Common mistakes
- Using problems that are all trivial or all impossible.
- Checking the reward curve but never reading completions.
- Skipping the SFT warm-up on a model that cannot follow the format.
Exercises
- Train a 0.5B model on arithmetic word problems with a correctness reward, and plot reward and completion length.
- Add a loophole to the reward on purpose, observe the model exploit it, then fix the verifier.
You are done when you can…
- Write reward functions for answer correctness and output format
- Compute group-relative advantages and explain why no value model is needed
- Recognise reward hacking in training logs and samples