Understanding reasoning models
local graph
Chapter 1 — Understanding reasoning models
Section titled “Chapter 1 — Understanding reasoning models”This chapter covers
- What “reasoning” means for a large language model
- Reviewing the conventional pretraining and post-training stages of LLMs
- Introducing key approaches to improving reasoning abilities in LLMs
- How reasoning differs from pattern matching
- Why we should build reasoning models from scratch
Welcome to the next stage of large language models (LLMs): reasoning. LLMs have transformed how we process and generate text, but their success has been largely driven by statistical pattern recognition. New advances in reasoning methods now enable LLMs to tackle more complex tasks, such as solving logical puzzles and multistep math problems.
Moreover, reasoning is an essential technique for making AI agents practical, such as when an agent has to break a task into steps, use tools, and recover from mistakes. Reasoning LLMs are already used in agent applications such as OpenClaw.
In this book, you’ll learn the inner workings of LLM reasoning methods through a hands-on, code-first approach. We’ll start with a pretrained LLM and extend it step by step with reasoning capabilities. We’ll implement these reasoning components ourselves, from scratch, to see how these methods work in practice.
If you are curious about how LLMs themselves are built and trained, my earlier book, Build a Large Language Model (From Scratch), also published by Manning (http://mng.bz/orYv), covers these foundations in detail, but it’s not required to follow along here.
Even if you just have a cursory knowledge of how LLMs are built, by the end of this book, you will understand how reasoning models work and be equipped to design, prototype, and evaluate the main methods for improving reasoning in LLMs.
When working with reasoning models, it’s crucial to know how to automatically check whether answers are correct on tasks such as math and how to turn a general-purpose model into a smaller reasoning model. We will use math examples throughout the book because they are easy to check automatically, but you do not need advanced math knowledge to follow along. Understanding reasoning methods is the central focus of this book.
With its focus on practical applications and explanations, this book is intended for LLM engineers, machine learning researchers, applied scientists, and software developers. Understanding how reasoning models are set up will help us judge when a standard LLM is sufficient and when extra reasoning machinery is worth the added complexity, cost, and latency. It will also help us design better evaluations, debug failures on multistep tasks, and adapt reasoning techniques to real products and research workflows.
1.1 Defining reasoning in the context of LLMs
Section titled “1.1 Defining reasoning in the context of LLMs”In this book, I use the term reasoning in a practical engineering sense rather than a philosophical one. In the context of LLMs, reasoning refers to a model generating intermediate steps before producing its final answer.
These intermediate steps may appear as visible step-by-step explanations, or they may be enclosed in special tags such as <think>…</think> and be hidden from the user. In either case, the core idea remains the same. The model is encouraged or trained to use tokens for intermediate problem-solving steps rather than jumping directly to the conclusion.
Correspondingly, I use reasoning model to mean an LLM that has been improved, either through training or prompting techniques, to produce such intermediate steps, which often increases accuracy on complex tasks such as coding, logical puzzles, and math problems.
Before we get to the coding portions of this book, I will briefly discuss the main techniques that improve these reasoning behaviors and how they relate to pattern matching and logical reasoning. This will lay the groundwork for later discussions of how LLMs are currently built, how they handle reasoning tasks, and what they are and are not so good at.
Chain-of-thought (CoT)
This style of generating intermediate steps is often referred to as chain of thought (CoT). Researchers and engineers often say that the model “thinks” through the problem step by step, meaning that it makes its intermediate reasoning process explicit and easier to follow. In this book, I use the terms reasoning and thinking in that common engineering sense. This does not imply that LLMs actually reason or think in the same way humans do.
Figure 1.1 illustrates how a conventional LLM generates the answer to a user’s question. A conventional LLM might not show how it came up with its answer, and while the answer might be correct, it doesn’t help the user understand the process behind it.
graph LR
U["User"] -->|"Prompt: Alice has 3 apples and Bob has 5 apples.<br/>Alice gives 1 apple to Bob.<br/>How many apples do they have together?"| L["Conventional LLM"]
L -->|"Answer: 8 apples"| OUT["Output"]
[!visual-conversion] Figure 1.1 — A simplified illustration of how a conventional, nonreasoning LLM might respond to a question with a short answer (printed p. 3, scan page-015.png). The print shows a user icon at left with a speech bubble carrying the prompt, an LLM icon at right, and a single answer bubble. Callouts label the two bubbles: “The question or task provided by the user” and “The output that the LLM generates to answer the user’s question”.
Figure 1.2 illustrates a simple example of multistep (CoT) reasoning in an LLM. The LLM-produced intermediate reasoning steps look very much like a person articulating internal thoughts aloud. How closely these methods (and the resulting reasoning processes) mirror human reasoning remains an open research question, one this book does not attempt to answer.
While figure 1.2 is a typical example of chain-of-thought reasoning, it’s important to emphasize that LLM reasoning differs from traditional, deterministic reasoning. For instance, a symbolic logic engine or theorem prover follows strict, rule-based steps that guarantee consistency and correctness. It works like following a recipe in which every step is fixed and must produce the same result each time. If you follow the steps exactly, you will always end up with the same dish.
graph LR
U["User"] -->|"Prompt: Alice has 3 apples and Bob has 5 apples.<br/>Alice gives 1 apple to Bob.<br/>How many apples do they have together?"| L["Reasoning LLM"]
L --> S
subgraph S ["Intermediate reasoning steps (chain of thought)"]
direction TB
S1["Step 1: Identify initial counts<br/>(Alice = 3, Bob = 5)"] --> S2["Step 2: Update counts after transfer<br/>(Alice = 2, Bob = 6)"] --> S3["Step 3: Calculate total: 2 + 6 = 8"]
end
S --> A["Answer: 8 apples"]
[!visual-conversion] Figure 1.2 — A simplified illustration of how a reasoning LLM might tackle a multistep reasoning task using a chain of thought (printed p. 4, scan page-016.png). Rather than just recalling a fact, the model combines several intermediate reasoning steps to arrive at the correct conclusion. In print the three steps sit in a dashed box between the model and the answer; the intermediate steps may or may not be shown to the user, depending on the implementation.
In contrast to a symbolic logic engine, an LLM generates reasoning autoregressively, which means it predicts one token at a time based on statistical patterns in its training data. As a result, the LLM’s “reasoning steps” are not guaranteed to be logically sound, even if they look convincing.
This book focuses on explaining and implementing the fundamental techniques that improve LLM-based reasoning and make LLMs better at handling complex tasks. My hope is that by gaining hands-on experience with these methods, you will be better prepared to understand and improve the reasoning methods being developed and maybe even explore how they compare to human reasoning.
LLM vs. human reasoning
Reasoning processes in LLMs may superficially resemble human thought, particularly in how intermediate steps are articulated. But it is important to recognize a key difference: humans can engage in deterministic reasoning by deliberately applying rules of logic or by reasoning over an internal model of the world. Deterministic, here, means that if we start with the same facts and follow the same steps, we will always reach the same conclusion. In contrast, current LLM reasoning is probabilistic, meaning that it generates one token at a time based on statistical patterns in training data, without guarantees of logical consistency.
Humans often reason by consciously manipulating concepts, intuitively understanding abstract relationships, or generalizing from a few examples. LLMs, by contrast, work by picking up patterns from huge amounts of text rather than relying on built-in reasoning rules or any kind of conscious thought.
In short, although the outputs of reasoning-enhanced LLMs can appear human-like, the underlying mechanisms differ substantially and remain an active area of exploration.
1.2 Understanding the standard LLM training pipeline
Section titled “1.2 Understanding the standard LLM training pipeline”Let’s briefly look at how conventional (nonreasoning) LLMs are typically trained so that we can understand where their limitations lie. This background will also help frame our upcoming discussions on the differences between pattern matching and logical reasoning.
Before applying any specific reasoning methodology, conventional LLM training is usually structured into two stages: pretraining and post-training, which are illustrated in figure 1.3. Some recent papers also distinguish a mid-training stage between the other two, such as to continue training a model on code, math, or long-context data, but I’ll group that stage under pretraining to keep the terminology simple in this book.
graph LR
A["Initial LLM"] --> B["Pretraining"]
B --> C
subgraph C ["Post-training"]
direction TB
C1["Instruction tuning"] --> C2["Preference tuning"]
end
[!visual-conversion] Figure 1.3 — Overview of a typical LLM training pipeline (printed p. 5, scan page-017.png). Recreated as a Mermaid flow: three left-to-right stages, with post-training drawn in the original as an outer rounded box enclosing Instruction tuning above Preference tuning, joined by a short arrow. The print carries three callout annotations attached by curved arrows to the boxes above them:
- Initial LLM — the LLM is initialized with random weights that are updated in the pretraining and post-training stages.
- Pretraining — the LLM is trained on large amounts of text, with the objective of predicting the next token.
- Post-training — the pretrained LLM is “refined” or fine-tuned in the post-training stage to follow human instructions and adhere to human preferences.
In the pretraining stage of a typical LLM training pipeline, LLMs are trained on massive amounts of unlabeled text, often many terabytes of data or trillions of tokens, including books, websites, research articles, and many other sources. The pretraining objective for the LLM is to learn to predict the next word (that is, the next token) in these texts.
Words and tokens
A token is a small unit of text that a language model processes. A token can be a full word, part of a word, or even punctuation, depending on how the text is split by a tokenizer.
For example, the sentence “An LLM can be useful.” might be broken into tokens like “An”, “L”, “LM”, “can”, “be”, “useful”, and “.” by a common tokenizer. These tokens are then converted into numerical IDs that the model can ingest.
A tokenizer is not part of the LLM itself, but it is nonetheless a critical component of the LLM text-processing and generation pipeline. We will see how tokenization works in the next chapter.
LLMs become highly capable when they’re pretrained on massive datasets, which typically involve several terabytes of text (equivalent to trillions of tokens). This training requires thousands of GPUs running for many months and can cost millions of dollars. Here, “capable” means that LLMs begin to generate text that closely resembles human writing. To some extent, pretrained LLMs also begin to exhibit so-called emergent properties, which means they can perform tasks that they were not explicitly trained to do, including translation and code generation.
These pretrained models serve as base models for the post-training stage, which uses two key techniques: supervised fine-tuning (often abbreviated as SFT in the literature and also known as instruction tuning) and preference tuning to teach LLMs to respond to user queries.
As shown in figure 1.4, instruction tuning improves an LLM’s capabilities for personal-assistance tasks such as question answering, summarizing, translating text, and more. The preference-tuning stage then refines these capabilities. As the term implies, preference tuning helps tailor responses to user preferences. Some readers may be familiar with the term reinforcement learning with human feedback (RLHF), which is a specific technique for implementing preference tuning.
In short, we can think of pretraining as “raw language prediction” (via next-token prediction) that gives the LLM some basic properties and capabilities to produce coherent texts. The post-training stage then improves the task understanding of LLMs via instruction tuning and refines the LLM to create answers with preferred stylistic choices via preference tuning.
It is worth noting that even an instruction-tuned model is not yet a “chatbot.” A chat interface adds another layer that guides the model’s responses in an interactive, multi-turn setting. This typically involves a system prompt, conversation history management, and other orchestration (an example of this is implemented in appendix G).
| Training stage | Example response to “Summarize the relationship between sleep and health” | Character of the response |
|---|---|---|
| Pretrained LLM | “Sleep is an essential function that allows your body and mind to recharge, leaving you refreshed and alert when you wake up. Healthy sleep also helps the body remain healthy and stave off diseases. Without enough sleep, the brain cannot function properly, affecting concentration and memory.” | Factual and coherent, but not actually a summary. Feels like an excerpt from an article. |
| Instruction-trained LLM | “Sleep plays a critical role in maintaining physical and mental health. Poor sleep is linked to problems like weakened immunity, weight gain, and impaired function, while good sleep supports memory, mood, and overall well-being.” | Concise and relevant, and actually summarizes the relationship. |
| Preference-tuned LLM | “Sure! 😴 Getting enough good-quality sleep is super important for your health. It helps your brain stay sharp, keeps your mood balanced, and even supports your immune system. On the flip side, not sleeping well can lead to stress, low energy, and trouble focusing.” | Uses an engaging tone and helpful framing. |
[!visual-conversion] Figure 1.4 — Example responses from a language model at different training stages (printed p. 7, scan page-019.png). The prompt asks for a summary of the relationship between sleep and health. Drawn in print as a user prompt bubble feeding three stacked response boxes, each tagged with its training stage on the right and annotated on the left; rendered here as a table because the figure is a three-way comparison of responses.
NOTE These pretraining and post-training stages are covered in my book Build a Large Language Model (From Scratch), published by Manning (http://mng.bz/orYv). The book you are reading now does not require detailed knowledge of those stages. Here, we will load a model that has already undergone the expensive pretraining and post-training stages so that we can focus on the methodology specific to reasoning models.
1.3 Improving LLM reasoning with training and inference techniques
Reasoning, in the context of LLMs, entered the public eye with the announcement of OpenAI’s o1 in ChatGPT on September 12, 2024. In the announcement article, OpenAI stated, “We’ve developed a new series of AI models designed to spend more time thinking before they respond” (https://openai.com/index/introducing-openai-o1-preview/). Furthermore, OpenAI wrote, “These enhanced reasoning capabilities may be particularly useful if you’re tackling complex problems in science, coding, math, and similar fields.”
A few months later, in January 2025, DeepSeek released the DeepSeek-R1 model and technical report, which details training methods for developing reasoning models (https://arxiv.org/abs/2501.12948). This made big waves because the company not only made freely and openly available a model that competes with and exceeds the performance of the proprietary o1 model but they also shared a blueprint for training such a model. In this book, we’ll look at how the methodologies used to develop reasoning models work by implementing similar methods from scratch.
The different approaches to developing and improving an LLM’s reasoning capabilities can be grouped into three broad categories, as illustrated in figure 1.5. These methods are typically applied to LLMs that have undergone the conventional pretraining and post-training phases, including instruction and preference tuning.
graph LR
A["Initial LLM"] --> B["Pretraining"]
B --> C
subgraph C ["Post-training"]
direction TB
C1["Instruction tuning"] --> C2["Preference tuning"]
end
C --> M
subgraph M ["Three different methods for enhancing reasoning in LLMs"]
direction TB
M1["1 - Inference-compute scaling"]
M2["2 - Reinforcement learning"]
M3["3 - Distillation"]
end
[!visual-conversion] Figure 1.5 — Three approaches commonly used to improve reasoning capabilities in LLMs: inference-compute scaling, reinforcement learning, and distillation (printed p. 8, scan page-020.png). These methods are typically applied after the conventional training stages (initial model, pretraining, and post-training with instruction and preference tuning), but reasoning techniques can also be applied to the pretrained base model. The upper row is labelled in print as “The main stages in developing conventional LLMs”. scaling, reinforcement learning, and distillation. These methods are typically applied after the conventional training stages (initial model training, pretraining, and post-training with instruction and preference tuning), but reasoning techniques can also be applied to the pretrained base model.
We will examine these common approaches in more detail throughout the book:
- Inference-time compute scaling (also often called inference-compute scaling, test-time scaling, and other variations) includes methods that improve the model’s reasoning capabilities at inference time (when a user prompts the model) without
training or modifying the underlying model weights. The core idea is to trade increased computational resources for improved performance, making even fixed models more capable through techniques such as chain-of-thought reasoning and various sampling procedures. This will be the focus of chapters 4 and 5.
- Reinforcement learning (RL) refers to training methods that improve a model’s reasoning capabilities by encouraging it to take actions that lead to high-reward signals. These rewards can be broad, such as task success or heuristic scores, or they can be narrowly defined and verifiable, such as correct answers in math problems or coding tasks.
Unlike inference-time compute scaling, which can improve reasoning performance without modifying the model, RL updates the model’s weights during training. This enables the model to learn and refine reasoning strategies through trial and error based on the feedback it receives from the environment. We will explore RL in more detail in chapters 6 and 7.
- Distillation involves transferring complex reasoning patterns learned by larger, more capable models into smaller or more efficient models. In the context of LLMs, this typically means performing supervised fine-tuning (SFT) using high-quality labeled instruction datasets generated by a larger, more capable model. This technique is commonly referred to as knowledge distillation or simply distillation in LLM literature. It’s important to note that this differs slightly from traditional knowledge distillation in deep learning, where a smaller (“student”) model typically learns from both the outputs and the logits produced by a larger (“teacher”) model. This topic is discussed further in chapter 8.
Reinforcement learning for reasoning and preference tuning
In the context of developing reasoning models, it is important to distinguish the reinforcement learning (RL) approach from reinforcement learning with human feedback (RLHF), which is used during preference tuning when developing a conventional LLM. Both settings use the same underlying process (RL), but they differ primarily in how the reward is obtained and validated (human judgments for RLHF versus automated verifiers or environments for reasoning RL).
RLHF incorporates explicit human evaluations or the rankings of model outputs as reward signals, directly guiding the model toward human-preferred behaviors. In contrast, RL in the context of reasoning models typically relies on automated or environment-based reward signals, which can be more objective but less aligned with human preferences. For instance, RL in a reasoning-model development pipeline might train a model to excel at mathematical proofs by providing explicit rewards for correctness. By contrast, RLHF would involve human evaluators ranking various responses to encourage outputs that align closely with human standards and subjective preferences.
1.4 Pattern matching vs. logical reasoning
Section titled “1.4 Pattern matching vs. logical reasoning”During pretraining, LLMs are exposed to vast quantities of text and learn to predict the next token by identifying and reproducing statistical associations in that data. This process enables them to generate fluent and coherent text, but it is fundamentally based on learned statistical regularities rather than explicit rules or guaranteed logical inference.
LLMs respond to prompts by generating text continuations that are statistically consistent with the patterns seen during training. This includes many premise-to-conclusion patterns that can look like logical inference. The key difference is that the model does not explicitly represent premises and apply formal rules but instead predicts likely continuations from similar examples in its training data.
Consider the following example:
SR The capital of Germany is…
Berlin.
An LLM producing the answer “Berlin” is not logically deducing the answer. Instead, it is recalling a strong statistical association learned from training data. This behavior reflects what we refer to as pattern matching, which means that the model completes text based on learned correlations and not by applying structured reasoning steps.
But what about tasks that go beyond pattern recognition, tasks where a correct answer depends on drawing conclusions from given facts? This brings us to a different kind of capability: logical reasoning.
Logical reasoning involves systematically coming up with conclusions using rules. Unlike pattern matching, it depends on intermediate reasoning steps and the ability to recognize contradictions or draw implications based on formal relationships.
Consider the following prompt as an example:
SR All birds can fly. A penguin is a bird. Can a penguin fly?
There are two ways to evaluate this.
First, in a closed-world (prompt-only) setting, given the two premises (claims or assumptions) in the prompt, the valid answer is “Yes, a penguin can fly.”
Second, in an open-world (with background knowledge) setting, if we allow knowledge not included in the prompt (such as that penguins cannot fly), this external fact conflicts with the conclusion derived from the premises, as shown in figure 1.6. A reasoning system should notice the inconsistency and either ask for clarification or weaken the first statement (for example, “Most birds can fly, with exceptions such as penguins.”).
In contrast, a statistical (pattern-matching) LLM does not explicitly track contradictions but instead predicts based on learned text distributions. For instance, if information such as “All birds can fly” is strongly reinforced in the training data, the model may confidently answer, “Yes, penguins can fly.”
graph TD
P["Prompt: 'All birds can fly. A penguin is a bird. Can a penguin fly?'"]
P --> A["1 - Premise 1: All birds can fly"]
P --> B["2 - Premise 2: A penguin is a bird"]
A --> C["3 - Inference: A penguin can fly"]
B --> C
D["4 - Fact: A penguin cannot fly"] --> E["5 - Result: Contradiction"]
C --> E
[!visual-conversion] Figure 1.6 — Contradictory premises lead to a logical inconsistency (printed p. 11, scan page-023.png). From “All birds can fly” and “A penguin is a bird” we infer “A penguin can fly.” This conclusion conflicts with the established fact “A penguin cannot fly,” which results in a contradiction. Print annotations: node 4 is marked “This is an established fact outside the premises,” node 3 “A conclusion reached from the premises,” and node 5 “The known fact contradicts the conclusion inferred from the premises.”
In the next section, we’ll look at an example of how an LLM handles this “All birds can fly…” prompt.
Logical reasoning and rule-based systems Why are explicit rule-based systems not more popular? Rule-based systems were widely used in the ’80s and ’90s for medical diagnosis, legal decisions, and engineering. They are still used in critical domains (medicine, law, aerospace), which often require explicit inference and transparent decision processes. They are hard to implement because they largely rely on human-crafted heuristics. (Heuristics are simple decision rules that give a good-enough answer quickly without guaranteeing an optimal one.) In contrast, deep neural networks, including LLMs, do not implement hand-written rules; they learn decision patterns from data and can be highly flexible when trained at scale.
1.5 Simulating reasoning without explicit rules
We saw how contradictory premises can lead to logical inconsistencies. A conventional LLM does not explicitly track contradictions but generates responses based on learned text distributions.
Figure 1.7 shows how a non-reasoning-enhanced LLM like GPT-4o in OpenAI’s ChatGPT responds to the “All birds can fly…” prompt discussed in the previous section. As you can see, GPT-4o appears to answer correctly even though it is not considered a
reasoning model (unlike OpenAI’s other offerings, such as o1, o3, o4-mini, and the more recent GPT-5, which have been explicitly developed with reasoning methodology).
ChatGPT 4o [ Share ]--------------------------------------------------------------------- User: Consider that all birds fly. And a penguin is a bird. Can penguins fly?
If we assume the statement "all birds fly" to be absolutely true, then logically, since a penguin is a bird, it should be able to fly. However, in reality, penguins are a known exception - they are birds that cannot fly.
This highlights a flaw in the initial premise. The assumption that all birds fly is incorrect because exceptions exist. This is an example of a logical syllogism where a universal premise is actually false.
Would you like me to formalize this reasoning using symbolic logic?
[thumbs up] [thumbs down] [copy] [retry]--------------------------------------------------------------------- Is this conversation helpful so far? [x][!visual-conversion] Figure 1.7 — An illustrative example of how a language model (GPT-4o in ChatGPT) appears to “reason” about a contradictory premise (printed p. 12, scan page-024.png). The print is a screenshot of a ChatGPT conversation; the exchange is fully legible in the scan and is transcribed above rather than embedded as a raster. The placeholder for this figure did not survive OCR and has been restored here at its print location.
So how did the 4o model generate its answer? Does this mean GPT-4o explicitly reasons logically? No, not necessarily. At a minimum, GPT-4o is highly effective at simulating logical reasoning in familiar contexts.
GPT-4o does not implement explicit contradiction checking; it instead generates answers based on probability-weighted patterns. This approach works well enough if the training data includes many instances that correct the contradiction (for example, text like “penguins cannot fly”) so that the model learns a statistical association between “penguins” and “not flying.” In other words, the model recognizes the contradiction implicitly because it has frequently encountered this exact reasoning scenario during training. This effect relies heavily on statistical associations built from extensive exposure to reasoning-like patterns in training data. So, even when a conventional LLM seems to perform logical deduction, as shown in figure 1.7, it’s not executing explicit, rule-based logic but instead leveraging patterns from its vast training data.
Still, GPT-4o’s success here is a good illustration of how powerful implicit pattern matching can become when trained at a massive scale. These pattern-based reasoning models usually struggle in a couple of scenarios:
Why build reasoning models from scratch?
- When the logical scenario is novel (not previously encountered in training data)
- When reasoning complexity is high, involving intricate, multistep logical relationships
Logical reasoning vs. reasoning models currently available today
Although GPT-4o is not officially labeled as a reasoning model, OpenAI offers several dedicated reasoning models, including o1, o3, o4-mini, and GPT-5. Moreover, other companies have been developing LLMs with explicit reasoning capabilities. As of this writing, popular examples include Anthropic’s Claude 4, xAI’s Grok 4, Google’s Gemini 2.5, DeepSeek, Alibaba’s Qwen3, and many more. The techniques employed by these models are the focus of this book. As we’ll see, this happens without implementing a rule-based reasoning pipeline. Instead, the LLM will learn or improve its reasoning capabilities through modified inference and training methodologies.
We might say that LLMs simulate logical reasoning through learned patterns. We can improve this further with specific reasoning methods, including inference-compute scaling and post-training strategies such as reinforcement learning, but the LLMs are not explicitly executing any rule-based logic internally.
Moreover, LLMs exist on a spectrum. Even before the advent of dedicated reasoning models such as OpenAI’s o1 and DeepSeek-R1, LLMs were capable of simulating reasoning behavior. These models exhibited behaviors aligning with the chapter’s earlier definition of reasoning in section 1.1, namely, generating intermediate steps before producing a final answer. What we now explicitly label a “reasoning model” is essentially a more refined version of this capability. These improved reasoning capabilities are achieved by using specific inference-compute scaling techniques (discussed in chapters 4 and 5) and targeted post-training methods, such as reinforcement learning (chapters 6 and 7), designed to improve and reinforce reasoning-like behavior.
1.6 Why build reasoning models from scratch?
Following the release of DeepSeek-R1 in January 2025, improving the reasoning abilities of LLMs has become one of the hottest topics in AI, and for good reason. Stronger reasoning skills allow LLMs to tackle more complex problems, making them more capable across various tasks that users care about.
This shift is also reflected in a February 12, 2025, statement from OpenAI’s CEO:
We will next ship GPT-4.5, the model we called Orion internally, as our last non-chain-of-thought model. After that, a top goal for us is to unify o-series models and GPT-series models by creating systems that can use all our tools, know when to think for a long time or not, and generally be useful for a very wide range of tasks.
The preceding quote underlines the major shift among leading LLM providers toward reasoning models. Here, “chain-of-thought” refers to a prompting technique that guides language models to reason step by step to improve their reasoning capabilities; we’ll cover it in more detail in chapters 4 and 5.
Also noteworthy is the mention of knowing “when to think for a long time or not.” This hints at an important design consideration: reasoning is not always necessary or desirable. For instance, reasoning models are designed for complex tasks such as solving puzzles, advanced math problems, and challenging coding tasks. They are also often useful in agent systems, especially for task decomposition, planning, and choosing which tools to use. They are not necessary for simpler tasks like summarization, translation, or knowledge-based question answering. In fact, using reasoning models for everything can be inefficient and expensive. For instance, they are typically more expensive to use, more verbose, and sometimes more prone to errors due to “overthinking.” Here, the simple rule applies: use the right tool (or type of LLM) for the task.
Reasoning models are often more expensive than non-reasoning models for two reasons. First, they tend to produce longer outputs because they include intermediate steps that explain how an answer is derived. As figure 1.8 illustrates, LLMs generate text one token at a time, and each token requires a full forward pass. If a reasoning model’s answer is twice as long, generation involves roughly twice as many forward passes, which increases compute costs.
graph LR
I1["Input to LLM:<br/>'The capital of Germany'"] --> L1["LLM"]
L1 --> O1["Output from LLM:<br/>'The capital of Germany is'"]
O1 --> L2["LLM"]
L2 --> O2["Output from LLM:<br/>'The capital of Germany is Berlin'"]
O2 --> L3["LLM"]
L3 --> O3["Output from LLM:<br/>'The capital of Germany is Berlin.'"]
[!visual-conversion] Figure 1.8 — Token-by-token generation in an LLM (printed p. 14, scan page-026.png). At each step, the LLM takes the full sequence generated so far and predicts the next token, which may represent a word, subword, or punctuation mark, depending on the tokenizer. The newly generated token is appended to the sequence and used as input for the next step. This iterative decoding process is used in both standard language models and reasoning-focused models. The print labels the first box “The input prompt provided to the LLM”, the top row “LLMs generate one token at a time; here the added token is ‘is’”, and the transition “The generated output is then passed to the LLM as input to generate the next token.”
Second, many reasoning workflows require running the model several times for a single task, such as to sample multiple candidate solutions, call tools, or run a verifier. These additional calls multiply the total number of tokens processed and further increase cost beyond the single-call behavior shown in figure 1.8.
That’s exactly why it helps to implement these models and methods from scratch. It’s one of the best ways to understand how they work. And if we understand how LLMs and reasoning models work, we can better understand these tradeoffs.
1.7 A road map to building reasoning models from scratch
Section titled “1.7 A road map to building reasoning models from scratch”Now that we’ve discussed reasoning in LLMs from a bird’s-eye view, the subsequent chapters will guide you through coding and applying reasoning methods from scratch. At a high level, the road map is simple. We’ll start with a conventional LLM, learn how to evaluate its reasoning behavior, and then explore two broad ways to improve it: inference techniques and training techniques. Figure 1.9 illustrates the main steps.
graph LR
S1["1 - Conventional LLM"] --> S2["2 - Evaluation"]
S2 --> S3["3 - Inference techniques"]
S3 --> S4["4 - Training techniques"]
S3 --> R["LLM with better reasoning abilities"]
S4 --> RM["Reasoning model"]
S3 -.->|"apply evaluation methods<br/>in later stages as well"| S2
S4 -.-> S2
[!visual-conversion] Figure 1.9 — A high-level road map of what we’ll build in this book (printed p. 15, scan page-027.png). We’ll start with a conventional LLM, add evaluation methods so we can measure its progress, and then explore two broad families of reasoning improvements: inference techniques and training techniques. Print stage captions:
- Stage 1: Load a pretrained LLM as a base model.
- Stage 2: Implement techniques to evaluate the performance of the LLMs with and without reasoning techniques.
- Stage 3: Implement reasoning-enhancing techniques that do not require training the LLM.
- Stage 4: Implement techniques that improve reasoning via training.
Dashed arrows in the print run back from stages 3 and 4 to stage 2, annotated “Apply evaluation methods to LLMs in later stages as well.”
Stage 1 is an explicit step in figure 1.9 because, in practice, reasoning methods are usually applied to an existing base LLM rather than one trained from scratch. We’ll begin with a conventional LLM that has already been pretrained, and we’ll treat it as the baseline we want to improve.
Stage 2 implements the evaluation tools needed to tell whether a method actually helps. That’s why stages 3 and 4 loop back to evaluation: after improving reasoning behavior through inference-time methods or additional training, we return to stage 2 to measure whether the change helped.
Stage 3 improves reasoning behavior at inference time without changing the model weights, while stage 4 improves the model itself through additional training, turning the pretrained LLM into a dedicated reasoning model.
Figure 1.10 provides more detail and summarizes the different substeps covered in each chapter.
graph LR
subgraph G1 ["1 - Conventional LLM"]
direction TB
A1["Loading pretrained weights"]
A2["Text generation"]
end
subgraph G2 ["2 - Evaluation"]
direction TB
B1["Benchmark-based evaluation"]
B2["Judgment-based evaluation"]
end
subgraph G3 ["3 - Inference techniques"]
direction TB
C1["Advanced text generation and voting"]
C2["Self-refinement"]
end
subgraph G4 ["4 - Training techniques"]
direction TB
D1["Reinforcement learning"]
D2["Distillation"]
end
G1 --> G2 --> G3 --> G4
[!visual-conversion] Figure 1.10 — A detailed road map of the chapter-level substeps (printed p. 16, scan page-028.png). After loading the base model, we’ll cover benchmark-based and judgment-based evaluation, then inference-time methods such as advanced text generation, voting, and self-refinement, and finally training-time methods based on reinforcement learning and distillation. Print stage captions:
- Stage 1: We load the pretrained LLM and implement the text generation functions (chapter 2).
- Stage 2: We implement evaluation methods that we will use for evaluating the models throughout this book (chapter 3).
- Stage 3: We implement and apply reasoning-enhancing techniques that do not require training the LLM (chapters 4 and 5).
- Stage 4: We cover two main categories of training techniques to improve the reasoning capabilities of LLMs (chapters 6 to 8).
I’m looking forward to the journey ahead and hope you are as well.
Summary
- Conventional LLM training occurs in several stages:
- Pretraining, in which the model learns language patterns from vast amounts of text
- Instruction fine-tuning, which improves the model’s responses to user prompts
- Preference tuning, which aligns model outputs with human preferences
- Reasoning methods are applied on top of a conventional LLM.
- Reasoning in LLMs refers to improving a model so that it explicitly generates intermediate steps (chain of thought) before producing a final answer, which often increases accuracy on multistep tasks.
Summary
- Reasoning in LLMs is different from rule-based reasoning, and it likely also works differently from human reasoning. Currently, the consensus is that reasoning in LLMs relies on statistical pattern matching.
- Pattern matching in LLMs relies purely on statistical associations learned from data, enabling fluent text generation but lacking explicit logical inference.
- Improving reasoning in LLMs can be achieved in a few ways:
- Inference-time compute scaling improves reasoning without retraining (e.g., chain-of-thought prompting). - Reinforcement learning involves training models explicitly with reward signals. - Supervised fine-tuning and distillation, using examples from stronger reasoning models.
- Building reasoning models from scratch provides practical insights into LLM capabilities, limitations, and computational tradeoffs.