◆ AI All-in-One

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
↗ Plan a path here

Read first

RLHF and Preference OptimizationChain-of-Thought and Reasoning Prompts

This leads to

—
The full path from zero — 55 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Large Language Models, Explained Simply
  14. Gradient Descent
  15. Tensors and Shapes
  16. NumPy and Array Thinking
  17. Language Modeling and Next-Token Prediction
  18. Prompt Engineering
  19. Supervised Learning
  20. Reinforcement Learning: The Basics
  21. Chain-of-Thought and Reasoning Prompts
  22. Linear Regression
  23. Training, Validation and Test Sets
  24. The Perceptron
  25. Markov Decision Processes
  26. Logistic Regression
  27. Overfitting and the Bias–Variance Tradeoff
  28. Value Functions and Bellman Equations
  29. Regularization: L1 and L2
  30. Neural Networks
  31. Recurrent Neural Networks
  32. Backpropagation
  33. Activation Functions
  34. Dropout and Regularizing Neural Networks
  35. Policy Gradients
  36. PyTorch
  37. Vanishing and Exploding Gradients
  38. Normalization Layers: BatchNorm and LayerNorm
  39. Optimizers: SGD, Momentum and Adam
  40. Actor-Critic Methods
  41. LSTMs and GRUs
  42. Residual Connections
  43. Training Neural Networks in Practice
  44. Proximal Policy Optimization
  45. Sequence-to-Sequence Models
  46. Transfer Learning
  47. Attention
  48. Self-Attention and Multi-Head Attention
  49. Positional Encodings
  50. The Transformer
  51. GPT and Decoder-Only Models
  52. Pretraining Large Language Models
  53. Fine-Tuning
  54. Instruction Tuning and Chat Models
  55. RLHF and Preference Optimization
  56. 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.

maths problem known answer: 408 (17 × 24) policy samples G = 4 a group of complete attempts <think> 17×20=340, 17×4=68 … </think> 408 <think> 17×24 ≈ 17×25 = 425 … </think> 425 <think> 24×17: 240+168 … wait, check: 408 ✓ </think> 408 <think> 17×24 = 17×2×12 … </think> 398 checker 1010 A = +1 A = −1 A = +1 A = −1 GRPO update advantage A = (reward − group mean) / group std: make every token of the above-average attempts more likely and of the below-average ones less likely
Fig. 1 How reasoning models are trained with verifiable rewards. For each problem the model samples a group of complete attempts. A checker marks each final answer right or wrong. Attempts that beat the group average are reinforced, the rest discouraged (the GRPO update). No human writes or grades the reasoning itself.

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 GG 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:

Ai=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG)A_i = \frac{r_i - \operatorname{mean}(r_1, \dots, r_G)}{\operatorname{std}(r_1, \dots, r_G)}

Every token of answer ii is then pushed up (if Ai>0A_i > 0) or down (if Ai<0A_i < 0) 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: (1,0,0,1,0,0,0,1)(1,0,0,1,0,0,0,1). The mean is 3/8=0.3753/8 = 0.375 and the standard deviation is 0.4840.484. Each right answer gets A=(1−0.375)/0.484=+1.29A = (1 - 0.375)/0.484 = +1.29; each wrong one gets (0−0.375)/0.484=−0.77(0 - 0.375)/0.484 = -0.77. 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.

  1. 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.
  2. 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.
  3. Reasoning RL. GRPO on verifiable tasks, as for R1-Zero, plus a reward for keeping the chain of thought in one language.
  4. 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.
  5. 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 kk attempts is correct, 1−(1−p)k1 - (1-p)^k for independent attempts with success rate pp.
0% 20% 40% 60% 80% 100% 1 2 4 8 16 32 64 attempts sampled per question, k (log scale) accuracy with a perfect checker (pass@k) majority vote, no checker a single attempt: 40%
Fig. 2 Accuracy of a toy solver that is right 40% of the time per attempt, as more attempts are sampled. With a perfect checker (pass@k) accuracy rises fastest; majority voting rises more slowly but needs no checker. Computed from the simulation in this chapter.

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

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

  1. 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?
  2. Compute pass@k by formula, 1−0.6k1 - 0.6^k, for k = 1, 4, 16 and compare with the simulated column.
  3. 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%.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. How is a reasoning model like DeepSeek-R1 mainly taught to reason?

  2. In a GRPO group of 8 attempts, all 8 are correct. What does this problem teach the model?

  3. A model solves a problem 40% of the time per attempt. With a perfect checker, what is pass@4 for independent attempts?

  4. When would majority voting (self-consistency) fail to help?

  5. Your team routes simple FAQ lookups to a reasoning model at high effort. What is the likely problem?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Learning to Reason with LLMs

OpenAI · 2024 · Beginner · Free

OpenAI's announcement of o1, with its plots of accuracy rising with both training-time RL compute and test-time thinking compute.

Paper

Let's Verify Step by Step

Lightman et al. (OpenAI) · 2023 · Advanced · Free

Compares rewarding only final answers with rewarding each reasoning step (process supervision) on competition maths.

Paper

STaR: Bootstrapping Reasoning With Reasoning

Zelikman et al. (Stanford & Google) · 2022 · Advanced · Free

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.

Video

Deep Dive into LLMs like ChatGPT

Andrej Karpathy · 2025 · Beginner · Free

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