Reinforcement learning for LLMs (RLHF, GRPO, RLVR)
Reinforcement learning is how the reasoning models of the last two years got good at maths, code and multi-step tool use. Unlike SFT, where you show the model the answer, RL lets the model try, scores the attempt, and reinforces whatever led to a higher score. The big practical shift is that you no longer need a learned reward model for many tasks: if you can check an answer with code, you can train on it.
Why it matters
RLHF (reinforcement learning from human feedback) was the original recipe: train a reward model on human preference comparisons, then optimise the policy against it with PPO. It works, but reward models are expensive to build and easy to exploit.
Two developments made RL accessible. GRPO (Group Relative Policy Optimization), introduced in the DeepSeekMath paper, removes PPO's separate value network by sampling a group of responses per prompt and using each response's reward relative to the group as its advantage. That cuts memory substantially. RLVR (reinforcement learning with verifiable rewards), named in the Tulu 3 report, replaces the reward model with a deterministic check: is the final number right, do the unit tests pass, does the output satisfy the constraint.
These ideas are now productised. Amazon Bedrock's reinforcement fine-tuning uses GRPO with Lambda-based or model-as-judge reward functions, Fireworks offers RFT driven by an evaluator function you write, and TRL ships a GRPOTrainer used in countless open replications.
How it works
For each prompt, the policy samples a group of completions. A reward function scores each one. GRPO normalises rewards within the group, so completions better than their siblings get a positive advantage and worse ones get a negative advantage, then applies a clipped policy-gradient update, optionally with a KL penalty to a reference model.
Rendering diagram…
Follow-up work refined the recipe. DAPO (ByteDance Seed) added decoupled clipping and dynamic sampling to stabilise long-chain reasoning training. Dr. GRPO ("Understanding R1-Zero-Like Training") identified a bias in GRPO's normalisation that inflates response length, especially for wrong answers, and removed the length and standard-deviation terms. TRL exposes several of these as loss_type options on the same trainer: in TRL v1.16 the default is "dapo" (token-level normalisation), with "dr_grpo" and others available, and the KL coefficient beta defaults to 0.0, so there is no reference-model penalty unless you turn it on. Defaults move between releases, so check the docs for your installed version.
Reward design is the actual work. Good rewards are:
- Verifiable: exact-match answers, unit tests, schema validation, a SQL query that returns the expected rows.
- Hard to game: a reward for "contains the word answer" will be found and exploited within a few hundred steps.
- Dense enough: if almost every sample scores zero, the group advantage is zero and nothing learns. Pick prompts the model solves sometimes, not never.
Reference architecture
At scale, generation dominates the cost, so production RL setups separate fast inference workers (usually vLLM) from the trainer and sync weights periodically.
Rendering diagram…
For agentic tasks, the environment is a sandbox where the model calls tools over several turns, and the reward is computed at the end (did the ticket get resolved, did the tests pass). Sandboxing matters: a model being trained to maximise "tests pass" will happily delete the tests if it can.
Code
GRPO with TRL using two reward functions: one checks the answer against a ground_truth column, one checks the output format. TRL passes extra dataset columns to reward functions as keyword arguments, and each function returns one float per completion.
import re
from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer
ds = load_dataset("json", data_files="sql_tasks.jsonl", split="train")
# rows: {"prompt": [{"role": "user", "content": ...}], "ground_truth": "42"}
def correctness(completions, ground_truth, **kwargs):
scores = []
for comp, gt in zip(completions, ground_truth):
text = comp[0]["content"]
m = re.search(r"<answer>(.*?)</answer>", text, re.S)
scores.append(1.0 if m and m.group(1).strip() == gt.strip() else 0.0)
return scores
def format_ok(completions, **kwargs):
return [0.2 if "<answer>" in c[0]["content"] else 0.0 for c in completions]
args = GRPOConfig(
output_dir="qwen3-sql-grpo",
num_generations=8, # group size G
max_completion_length=1024,
learning_rate=1e-6,
per_device_train_batch_size=8,
use_vllm=True,
)
trainer = GRPOTrainer(
model="Qwen/Qwen3-1.7B",
reward_funcs=[correctness, format_ok],
args=args,
train_dataset=ds,
)
trainer.train()
Keep the format reward small relative to correctness, or the model will learn to emit perfectly formatted wrong answers.
Trade-offs and pitfalls
- Reward hacking is the default outcome. Read samples every few hundred steps. If reward rises but held-out accuracy does not, the model found a loophole.
- Prompts that are too hard or too easy waste compute. Filter the dataset to prompts with a middling pass rate under the starting model.
- Length growth. Reasoning RL tends to make responses longer. Some of that is useful; some is the normalisation bias Dr. GRPO describes. Track length alongside accuracy.
- RL amplifies what SFT seeded. A short SFT warm-up on good formats usually makes RL far more stable.
- Generation is the bottleneck. Without vLLM-backed rollouts, RL on anything beyond small models is painfully slow.
- Learned reward models drift. If you must use one (for subjective tasks), refresh it and keep a human-labelled check set.
Checklist
- Prefer verifiable rewards; write unit tests for your reward functions.
- Filter prompts to those the model solves some of the time.
- Start from an SFT checkpoint that already produces the right format.
- Log sample completions and reward components, not just mean reward.
- Run held-out evals and a manual reward-hacking audit at each checkpoint.
- Sandbox any environment where the model executes code or tools.
Further reading
- DeepSeekMath, which introduced GRPO (arXiv 2402.03300)
- Tulu 3, which introduced RLVR (arXiv 2411.15124)
- DAPO: An Open-Source LLM Reinforcement Learning System at Scale (arXiv 2503.14476)
- Understanding R1-Zero-Like Training: A Critical Perspective, Dr. GRPO (arXiv 2503.20783)
- TRL GRPO Trainer documentation
- AWS: Reinforcement fine-tuning on Amazon Bedrock, a technical walkthrough