Reasoning Models & RL Post-Training
Generative & Agentic AI · AI Foundations · Advanced · 26 min
Explain how reasoning models think longer at test time, how RL with verifiable rewards and GRPO train them, where reward hacking comes from, and when a reasoning model is worth its latency and cost.
A maths class where the teacher hands the same problem to six students, marks each final answer right or wrong, and then tells every student how they did compared with the class average on that problem. Beat the average and you keep doing what you did. Fall below it and you change your approach.
The idea in everyday words
A chess player in a fast blitz game moves on instinct. Give the same player ten minutes per move and they look ahead, try lines, notice mistakes and change their mind. Reasoning models are trained to use that thinking time well: they write out a private chain of reasoning before answering, and reinforcement learning rewards the habits (checking work, trying another approach) that lead to correct answers.
Thinking longer: chain-of-thought and test-time compute
Chain-of-thought (CoT) means the model writes intermediate steps before the final answer. Each written token is more computation spent on the problem, and the steps become context the model can check.
Test-time compute is the idea that you can buy accuracy by spending more computation when answering, not only when training. Two ways to spend it:
- Sequential: think longer. A reasoning model writes a long hidden or visible reasoning trace, tries an approach, notices an error, backtracks. More thinking tokens usually means better results on hard maths, code and planning, with diminishing returns.
- Parallel: sample many, then choose. Self-consistency samples several reasoning paths and takes the majority vote of their final answers. Best-of-n samples n answers and picks the one a verifier scores highest (a unit test, a checker, or a reward model).
from collections import Counter
answers = ["102", "96", "102", "112", "102", "96"] # final answers of 6 sampled paths
print("majority vote:", Counter(answers).most_common(1)[0][0])
scores = [0.91, 0.40, 0.88, 0.35, 0.93, 0.42] # a verifier's score per path
best = max(range(len(answers)), key=lambda i: scores[i])
print("best-of-n:", answers[best], "with score", scores[best])
The catch is cost and latency. Thinking tokens are generated like any output tokens: you wait for them and pay for them. A reasoning model that thinks for 5,000 tokens is far slower than a fast model answering in 50.
From RLHF to RL with verifiable rewards
The lesson "How LLMs Are Trained" covered RLHF and DPO for making a model helpful and polite. Reasoning models add a third kind of post-training:
| Method | Learning signal | Extra models during training | Best for |
|---|---|---|---|
| RLHF with PPO | a reward model trained on human preferences | reward model + value (critic) model | tone, helpfulness, safety |
| DPO | pairs of preferred vs rejected answers, no RL loop | none (a frozen reference copy) | cheap preference tuning |
| RL with verifiable rewards (RLVR) | a program that checks the answer: exact maths answer, unit tests pass, valid JSON | none needed for the reward | maths, code, logic, tool use |
Why verifiable rewards matter: a reward model is itself a neural network, and the policy can learn to fool it. A checker that runs the tests or compares the final number is much harder to fool, and it scales to millions of problems without human labellers.
The recipe in one picture (the DeepSeek-R1 paper made it famous):
- Start from a strong pretrained base model.
- Optionally, supervised fine-tune on a small set of good long reasoning examples (a "cold start") so the output stays readable.
- Run RL on many problems with checkable answers. The reward is mostly "is the final answer right?", plus small rewards for following the required format.
- Optionally, generate many solutions, keep the verified-correct ones, and fine-tune on them (rejection sampling), then run a final RL round for general helpfulness.
DeepSeek-R1-Zero skipped step 2 entirely: long, self-checking reasoning emerged from RL alone, although its output was hard to read and mixed languages.
GRPO: grade each answer against its own group
Group Relative Policy Optimization (GRPO) is the RL algorithm introduced in the DeepSeekMath paper and used for DeepSeek-R1. It is PPO without the critic.
The problem it solves: RL needs a baseline to tell whether an answer was better or worse than expected. PPO trains a separate value (critic) model, as big as the policy, to predict that baseline. That doubles memory and adds a hard-to-train network.
GRPO's trick: for each prompt, sample a group of G answers (for example 8 or 16), score them all, and use the group itself as the baseline:
- mean = average reward of the group
- std = population standard deviation of the group's rewards
- advantage of answer i = (reward_i − mean) / std
Then every token of answer i is pushed up (positive advantage) or down (negative advantage), with PPO-style clipping so a single update cannot move the policy too far, and a KL penalty that keeps it close to a frozen reference model.
Worked example. Six answers, two correct: rewards [1, 0, 1, 0, 0, 0]. Mean = 1/3, std ≈ 0.47. The correct answers get (1 − 0.33) / 0.47 ≈ +1.41; the wrong ones get ≈ −0.71.
Two consequences interviewers like:
- If every answer in a group gets the same reward, every advantage is 0. All right (too easy) or all wrong (too hard) teaches nothing. Training data should sit at the edge of what the model can do.
- A rare success counts a lot. With one correct answer out of six, it gets ≈ +2.24. Hard problems the model sometimes solves give the strongest signal.
Real implementations add a tiny epsilon to the std (or treat a near-zero std as zero), because floating-point averages of equal rewards can leave a std like 1e-17 instead of exactly 0.
Rewards, verifiers and reward hacking
Outcome rewards score only the final answer. Cheap and hard to fool, but they give no credit for a nearly-right method and can reward lucky guesses.
Process rewards score each reasoning step, using a process reward model (PRM) trained on step-level labels. Richer signal, but the PRM is a learned model again, so it can be gamed, and step labels are expensive to collect.
Reward hacking is the policy finding a way to score high without doing the task:
- Coding RL that only checks "tests pass" can learn to special-case the test inputs, or (with file access) to edit the tests.
- A format reward can be farmed by producing the format with nonsense inside.
- A length-sensitive reward can push answers to grow without getting better.
Defences: hidden or held-out tests, rewards that combine several checks, a KL leash to the reference model, sandboxing what the policy can touch, and reading samples of the reasoning during training, not just the reward curve.
Distillation brings reasoning to small models. Generate long verified reasoning traces with a big reasoning model, then supervised fine-tune a small model on them. DeepSeek released small dense models distilled this way that reason far better than the same sizes trained with RL from scratch. On AWS, Amazon Bedrock Model Distillation applies the same teacher-to-student idea for supported model pairs.
Using reasoning models in products (on AWS)
When a reasoning model earns its cost:
| Use a reasoning model | Use a fast model |
|---|---|
| multi-step maths, tricky code, planning an agent's next moves | classification, extraction, short rewrites |
| a wrong answer is expensive | a wrong answer is cheap to retry |
| seconds of latency are fine (or it runs offline) | a user is waiting on every token |
A common production pattern is a router: a fast model handles most requests and escalates the hard ones (low confidence, failed validation, multi-step tool plans) to a reasoning model.
Thinking budgets. Many APIs let you cap how much a model thinks. On Amazon Bedrock, Anthropic's Claude models with extended thinking are enabled through the Converse API's additionalModelRequestFields, for example {"thinking": {"type": "enabled", "budget_tokens": 4000}}. The response then includes reasoning content blocks before the answer. Thinking tokens are billed as output tokens and must fit within the max tokens you allow; check the model's documentation for the minimum budget and supported options, and note that some newer models use an effort setting instead of a fixed budget.
Prompting tips that change: reasoning models usually need less "think step by step" scaffolding and fewer worked examples. State the goal, constraints and output format clearly, then let them plan.
Training your own: run GRPO-style RL with open-source libraries such as Hugging Face TRL (which has a GRPO trainer) or veRL, on Amazon SageMaker AI training jobs or SageMaker HyperPod clusters, with your verifier as the reward function. Bedrock also offers managed fine-tuning options for some models.
Elsewhere: the same choices exist on Vertex AI (GCP) and Azure AI Foundry, and with self-hosted open-weights reasoning models.
Go deeper (engineer level)
The GRPO objective, more precisely. For each sampled answer and each of its tokens, take the probability ratio between the new and old policy, multiply by that answer's advantage, and clip the ratio to [1 − ε, 1 + ε] as in PPO. Average over tokens and answers, then subtract β × KL(policy ‖ reference). Every token of an answer shares the same advantage: credit assignment is coarse, which is one reason process rewards are attractive.
Known biases and fixes. Averaging the loss per answer gives each token of a long wrong answer a smaller penalty than a short wrong one, so long wrong answers are penalised less per token. Dividing by the group std gives prompts with tiny spread (almost all right or almost all wrong) extra weight. Follow-up work such as Dr. GRPO drops these normalisations; DAPO adds "dynamic sampling" (drop groups whose advantages are all zero and refill the batch) and a higher upper clip bound so rare tokens can grow. Know that these exist and why, not every detail.
pass@1 vs pass@k. RL with verifiable rewards reliably raises pass@1 (the chance the first answer is right). Some studies find the base model catches up when you allow many attempts (large k), suggesting RL mostly sharpens solutions the base model could already reach rather than creating new ones. It is an open research question; mention both sides.
Sequential vs parallel scaling. Longer thinking helps on problems that need many dependent steps; parallel sampling with a good verifier helps when checking is cheaper than solving (code with tests). Parallel samples also run concurrently, so their latency is one sample's, not n samples'.
Overthinking and faithfulness. Reasoning models can spend thousands of tokens on easy questions; budgets and routers control that. The written reasoning is not guaranteed to be the real cause of the answer, so do not treat a trace as an audit log of the model's decision.
Step by step
- The prompt:
"A box holds 6 pens. How many pens are in 17 boxes?" The right answer is 102, and a program can check any final answer.
- Sample and verify:
The policy samples G = 6 answers: 102, 96, 102, 112, 107, 96. The verifier gives reward 1 for 102 and 0 otherwise: rewards [1, 0, 1, 0, 0, 0].
- Baseline:
Mean reward = 2 / 6 ≈ 0.33. This measured average replaces PPO's critic model.
- Advantages:
Population std ≈ 0.47. Advantage = (reward − mean) / std: the two correct answers get +1.41, the four wrong ones −0.71.
- Update:
Tokens of the correct answers become more likely, tokens of the wrong ones less likely. If all six had been right, every advantage would be 0 and nothing would change.
- Stay close:
A KL penalty keeps the policy near a frozen reference model. Repeat over many prompts; better reasoning habits win because they earn above-average rewards.
Code example
# Test-time compute: majority vote (self-consistency) vs best-of-n with a verifier.
from collections import Counter
samples = ["102", "96", "102", "112", "102", "96"]
votes = Counter(samples)
print("votes:", dict(votes))
print("self-consistency answer:", votes.most_common(1)[0][0])
verifier_scores = [0.91, 0.40, 0.88, 0.35, 0.93, 0.42]
best = max(range(len(samples)), key=lambda i: verifier_scores[i])
print("best-of-n answer:", samples[best], "score", verifier_scores[best])
# A router: send only hard requests to the (slower, pricier) reasoning model.
def route(task):
hard = task["steps"] > 3 or task["needs_code"]
return "reasoning model, thinking budget 4000" if hard else "fast model"
for task in [{"name": "tag a ticket", "steps": 1, "needs_code": False},
{"name": "plan a data migration", "steps": 6, "needs_code": True}]:
print(task["name"], "->", route(task))Complexity
- Time: O(n) for one group of n rewards: one pass for the mean, one for the spread, one for the advantages
- Space: O(n) for the list of advantages
Interview tips
What is test-time compute? Contrast thinking longer (sequential) with self-consistency or best-of-n (parallel), and their latency and cost.
Walk through GRPO: sample a group, score with a verifier, advantage = (r − mean) / std, clipped policy update, KL to a reference. What does it remove compared with PPO, and why does that matter?
Why do groups where every answer is right (or wrong) give no learning signal, and what do training recipes do about it?
Give two examples of reward hacking in RL for code or maths and how you would defend against them.
When would you NOT use a reasoning model in a product? How would you cap its cost on Bedrock (thinking budgets, routing, caching)?
Challenge: GRPO Advantages for One Group
Write grpo_advantages(rewards) for one group of sampled answers to the same prompt.
- mean = average of the rewards.
- std = population standard deviation: square root of the average of (reward − mean)².
- Each answer's advantage = (reward − mean) / std, rounded to 2 decimals (Python
round(x, 2), JavaScriptMath.round(x * 100) / 100). - If std is below
1e-9(every reward the same, allowing for float leftovers), return a list of zeros. - Return a new list in the same order. Do not change the input.
Example: grpo_advantages([1, 0, 1, 0, 0, 0]) → [1.41, -0.71, 1.41, -0.71, -0.71, -0.71]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- DeepSeekMath paper (introduces GRPO)
- DeepSeek-R1 paper: reasoning via reinforcement learning
- Self-Consistency Improves Chain of Thought Reasoning
- Let's Verify Step by Step (process reward models)
- Chain-of-Thought Prompting Elicits Reasoning
More in AI Foundations
- Machine Learning in 15 Minutes
- Neural Networks from Scratch
- What Is GenAI? LLMs & Tokens
- Tokenization & Byte-Pair Encoding
- Transformers & Attention
- How LLMs Are Trained: Pretraining, SFT & RLHF
Previous: How LLMs Are Trained: Pretraining, SFT & RLHF · Next: Prompt Engineering