Level 3 In-Depth AI · Transformers and Language Models
Reasoning Models and Test-Time Compute
Models such as OpenAI's o1 and DeepSeek-R1 are trained with reinforcement learning to think at length before answering. Spending more computation at answer time, not just at training time, became a new way to make models smarter.
- Level
- ●●●●● Advanced
- Reading
- 12 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 55 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 55 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Large Language Models, Explained Simply
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Prompt Engineering
- Supervised Learning
- Reinforcement Learning: The Basics
- Chain-of-Thought and Reasoning Prompts
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Markov Decision Processes
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Value Functions and Bellman Equations
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- Policy Gradients
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- Actor-Critic Methods
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Proximal Policy Optimization
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
- Instruction Tuning and Chat Models
- RLHF and Preference Optimization
- Reasoning Models and Test-Time Compute
Read them roughly in this order. See it on the concept map →
Why it matters
For years, the recipe for a smarter language model was simply: make it bigger and train it on more data (Scaling Laws). Every answer then cost about the same small amount of computation, a fixed number of operations per output token, whether the question was "What's the capital of France?" or a competition maths problem.
In September 2024 OpenAI released o1, the first widely used reasoning model: a model trained to produce a long internal chain of thought, often thousands of tokens, before giving its answer. Its accuracy on hard maths, science and coding problems jumped far above earlier models of similar size. OpenAI reported that performance improved smoothly both with more reinforcement-learning training and with more time spent thinking per question. In January 2025 the Chinese lab DeepSeek released DeepSeek-R1 with open weights and a detailed paper showing how to train such a model, and within months most major labs offered "thinking" models (in 2025: OpenAI's o-series, Google's Gemini "thinking" models, Anthropic's Claude with extended thinking, Alibaba's Qwen models, and many others).
This introduced a second axis for scaling: test-time compute, the computation a model spends while answering. A harder question can now get more thought. This chapter explains how these models are trained, what "thinking longer" buys, and where its limits lie.
The intuition
Ask a person "What's 17 × 24?" and they can't just blurt out the answer: they work through it — 17 × 20 = 340, 17 × 4 = 68, total 408. Chain-of-thought prompting showed in 2022 that language models do better when asked to write such intermediate steps. Each written token is extra computation the model can build on.
But prompting only asks for steps. A reasoning model is trained to produce useful ones. The trick is to grade only the final answer, which can be checked automatically, and let reinforcement learning discover what kind of thinking leads to correct answers. Nobody writes the reasoning. The model tries many attempts per problem; the attempts that end in a right answer are reinforced, the others discouraged. Over thousands of training steps, models trained like this learn to write longer, to check their work, to notice mistakes ("wait, that's not right…") and to try another approach.
It is like a student who is never shown worked solutions, only told "right" or "wrong" at the end of each attempt, and who gradually invents the habits of careful problem solving.
Key idea Reasoning models are trained with RL on problems whose answers can be checked automatically. They learn to spend many thinking tokens before answering, and accuracy keeps improving as they are allowed to think longer: test-time compute is a new lever alongside model size and data.
How it works
Verifiable rewards
In RLHF and Preference Optimization the reward comes from a learned reward model, which can be gamed. Reasoning models are trained mainly on tasks with a verifiable reward: an automatic check that cannot be flattered.
- Maths: does the final answer (say, in a
\boxed{}at the end) equal the known answer? - Code: does the program pass the unit tests?
- Logic puzzles, formal proofs, some science questions: an exact checker exists.
The reward is typically 1 for a correct final answer and 0 otherwise, often plus a small format reward for putting the reasoning and answer in the expected places (DeepSeek-R1 used <think> … </think> tags). This setup is sometimes called RLVR, reinforcement learning with verifiable rewards.
The RL algorithm: GRPO
Any policy-gradient method works in principle (Policy Gradients, Proximal Policy Optimization). DeepSeek used GRPO (Group Relative Policy Optimization), introduced in its DeepSeekMath paper (2024). For each prompt, sample a group of answers (say 8 or 16) and score each one. Each answer's advantage, how much better than expected it was, is its reward compared with the rest of its group:
Every token of answer is then pushed up (if ) or down (if ) using PPO's clipped update, usually with a KL penalty towards a reference model. Using the group average as the baseline removes PPO's separate value network, which saves a whole model's worth of memory.
Worked example. Eight attempts at one problem; three are right. Rewards: . The mean is and the standard deviation is . Each right answer gets ; each wrong one gets . If all eight were right, or all wrong, every advantage would be 0 and the problem would teach nothing. That's why training sets are filtered to problems the model sometimes, but not always, solves.
DeepSeek-R1, step by step
The DeepSeek-R1 paper (January 2025) is the clearest public account of training a reasoning model. Its base was DeepSeek-V3, a 671-billion-parameter Mixture of Experts model.
- R1-Zero: pure RL. Starting from the base model, with no supervised fine-tuning at all, they ran GRPO with only accuracy and format rewards on maths, code and logic problems. The model's responses grew steadily longer during training, and behaviours such as re-checking and trying alternative approaches emerged on their own, including a moment the authors highlighted where the model wrote that it had an "aha moment" and re-evaluated its approach. On the AIME 2024 maths competition its pass@1 accuracy rose from 15.6% to 71.0% over training. But its output was hard to read and sometimes mixed languages.
- Cold start. For R1 proper, they first fine-tuned the base model on a few thousand curated long chain-of-thought examples to make the reasoning readable.
- Reasoning RL. GRPO on verifiable tasks, as for R1-Zero, plus a reward for keeping the chain of thought in one language.
- Rejection sampling and SFT. They sampled many answers from that model, kept the correct and readable ones (about 600,000 reasoning samples), added about 200,000 non-reasoning samples (writing, factual questions), and fine-tuned again.
- RL for all scenarios. A final RL stage combining verifiable rewards for reasoning with reward models for helpfulness and harmlessness.
The result performed comparably to OpenAI's o1 on several maths and coding benchmarks in the paper's comparisons. The authors also distilled R1 by fine-tuning smaller open models (Qwen and Llama, from 1.5B to 70B parameters) on 800,000 of its samples; for a 32B model, distillation from R1 beat running large-scale RL on that model directly (Knowledge Distillation and Small Models).
OpenAI has not published o1's training details. Its announcement says o1 was trained with large-scale reinforcement learning to use a chain of thought, and that accuracy improved with both more RL training compute and more test-time thinking.
What "thinking longer" buys
There are two broad ways to spend more compute at answer time:
- Sequential: one long chain of thought. Reasoning models do this by default. APIs let you control it, either with a thinking budget (a maximum number of thinking tokens) or, in newer APIs, with an effort level that the model translates into how long it thinks. Thinking tokens are billed like output tokens, so a hard question can cost many times more than a simple one.
- Parallel: sample several independent answers and combine them. Self-consistency (Wang et al., 2022) takes a majority vote over the final answers. Best-of-N uses a verifier or reward model to pick one. If you have a perfect checker, success is measured by pass@k: the probability that at least one of attempts is correct, for independent attempts with success rate .
A process reward model scores each step of a solution rather than only the final answer, which can guide search over partial solutions (OpenAI's "Let's Verify Step by Step", 2023). Snell and colleagues (2024) found that for some problems, spending extra test-time compute well could beat a model many times larger, and that the best strategy depended on the problem's difficulty.
In code
This simulation shows why test-time compute works, and computes GRPO advantages. A toy "model" solves a problem with probability 0.4 per attempt, otherwise it lands on one of 20 wrong answers.
import numpy as np
rng = np.random.default_rng(0)
def attempt(n): # right answer is 42 with probability 0.4, else one of 20 wrong ones
right = rng.random(n) < 0.4
return np.where(right, 42, rng.integers(0, 20, n))
def majority_vote(k, trials=5000): # no checker: pick the most common answer
wins = 0
for _ in range(trials):
vals, counts = np.unique(attempt(k), return_counts=True)
wins += rng.choice(vals[counts == counts.max()]) == 42 # break ties at random
return wins / trials
def best_of_k_with_verifier(k, trials=5000): # a checker can recognise a right answer
return np.mean([(attempt(k) == 42).any() for _ in range(trials)])
print(" k majority vote verifier (pass@k)")
for k in [1, 4, 16, 64]:
print(f"{k:2d} {majority_vote(k):.2f} {best_of_k_with_verifier(k):.2f}")
# GRPO-style advantages: 8 sampled answers to one problem, reward 1 if correct
rewards = np.array([1, 0, 0, 1, 0, 0, 0, 1], dtype=float)
adv = (rewards - rewards.mean()) / rewards.std()
print("advantages:", np.round(adv, 2))
# k majority vote verifier (pass@k)
# 1 0.40 0.39
# 4 0.58 0.87
# 16 0.97 1.00
# 64 1.00 1.00
# advantages: [ 1.29 -0.77 -0.77 1.29 -0.77 -0.77 -0.77 1.29]
Majority voting works because wrong answers scatter while right answers agree. It would fail if the model's mistakes all agreed: a common misconception gives a confident, consistent wrong answer. With a checker, a 40% solver becomes near-perfect with 16 tries, which is exactly why verifiable rewards are so powerful in RL: the model can find correct solutions by sampling and then learn from them.
Calling a reasoning model through an API is like calling any model, with an extra setting for how hard to think. With Anthropic's Python SDK, as of late 2026 (needs an API key, not run here; parameter names change between model generations, so check the provider's current docs):
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"}, # model decides how long to think
output_config={"effort": "high"}, # low | medium | high | xhigh | max
messages=[{"role": "user", "content": "How many primes are there between 100 and 200?"}],
)
for block in response.content:
if block.type == "thinking":
print("THINKING (summary):", block.thinking)
elif block.type == "text":
print("ANSWER:", block.text)
The raw chain of thought is not returned by most commercial APIs; you get a summary, or nothing, while still paying for the thinking tokens.
Common pitfalls
- Overthinking easy questions. Reasoning models can spend thousands of tokens on trivial requests, adding cost and latency. Use a small budget, or a non-reasoning model, for simple tasks.
- Assuming the visible reasoning is the real reason. The chain of thought is generated text, and research has found cases where models' stated reasoning leaves out factors that influenced the answer. Treat it as helpful, not as a faithful trace (Interpretability and Explainability).
- Expecting gains everywhere. Improvements are largest in maths, code and science, where answers can be checked. Gains in open-ended writing are smaller.
- Prompting them like older models. Telling a reasoning model "think step by step" is usually redundant, and heavily prescriptive step-by-step instructions can hurt. Give the goal and the constraints clearly.
- Ignoring cost. Thinking tokens are billed. Monitor them.
Watch out RL with automated rewards can still be gamed. In coding tasks, models have been observed to make tests pass by special-casing them rather than solving the problem. If your reward is "the tests pass", make sure the tests can't be trivially satisfied, and review samples by hand.
Where it leads
- Agents. Long reasoning combined with tool calls (searching, running code) underlies 2025-era AI Agents and AI Coding Assistants and Agents.
- Distillation. Reasoning traces from big models train small ones cheaply: Knowledge Distillation and Small Models.
- Efficient thinking. Research continues on shorter chains of thought, adaptive budgets, and reasoning in hidden vectors instead of words.
- Evaluation. Hard benchmarks such as AIME, GPQA and SWE-bench became the measuring sticks for these models: Evaluating LLMs and Benchmarks.
- Serving. Long outputs stress the The KV Cache and Fast Inference and make Long Context and Efficient Attention inference matter even more.
A bit of history
The pieces came together over several years. Chain-of-thought prompting (Wei et al., January 2022) showed that writing steps helps. Self-consistency (Wang et al., 2022) added majority voting. STaR (Zelikman et al., 2022) had a model learn from its own rationales that led to correct answers, an early form of learning from verifiable outcomes. OpenAI's "Let's Verify Step by Step" (2023) studied rewarding each step.
o1-preview appeared on 12 September 2024, followed by the full o1 in December 2024 and o3 (announced in December 2024, released in April 2025). DeepSeek released R1 and its paper on 20 January 2025, under an MIT licence. Its openness, strong results and the reported low cost of the underlying model caused a stir, including a sharp one-day fall in some AI-related stock prices in late January 2025. Within weeks, reproductions appeared, including s1 (Muennighoff et al., 2025), which fine-tuned a 32B model on only 1,000 reasoning examples and controlled thinking length by appending "Wait" when the model tried to stop early. By mid-2025, "thinking" modes were a standard feature of frontier models.
Try it
- In the simulation, change the wrong answers to come from only 2 possibilities instead of 20 (
rng.integers(0, 2, n)). What happens to majority voting at k = 16? Why?- Compute pass@k by formula, , for k = 1, 4, 16 and compare with the simulated column.
- Compute the GRPO advantages for a group where 7 of 8 answers are right. Which answer gets the largest push, and in which direction?
Hint for 1: with only two wrong answers, each wrong answer gets about 30% of the votes, close to the right answer's 40%.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via RL
Open reasoning model trained largely with reinforcement learning on verifiable rewards.
Learning to Reason with LLMs
OpenAI's announcement of o1, with its plots of accuracy rising with both training-time RL compute and test-time thinking compute.
Reinforcement Learning from Human Feedback (the RLHF Book)
A free online book covering reward models, PPO, DPO and its relatives, Constitutional AI and reasoning-era RL, written by a practitioner.
Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters
Studies how to spend extra compute at inference time, with search against verifiers and with revisions, and when that beats a bigger model.
DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models
Introduced GRPO, a PPO variant without a value network that scores each answer against a group of sampled answers. Later used to train DeepSeek-R1.
Let's Verify Step by Step
Compares rewarding only final answers with rewarding each reasoning step (process supervision) on competition maths.
STaR: Bootstrapping Reasoning With Reasoning
A model writes rationales, keeps the ones that reach the correct answer, and fine-tunes on them, an early form of learning to reason from verifiable answers.
Deep Dive into LLMs like ChatGPT
A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/reasoning-models.md