Skip to content
ImagineWorld

Build a Reasoning Model

node_idnode-book_build-a-reasoning-model
node_typenode-book
schema_profileworld.node_book.v1
statusactive
orthogonal_scopemanifold, entropy, authority, state
manifoldworld
entropymedium
authorityinforms
stateexternal
domainimagineworld.net
node_interiorrosetta_contract
unisonone evidence claim read five ways: seated in the llms field, the work builds a reasoning model — the training pipeline for models that think before they answer — its framework, regime, and stance agreeing on what it is
governed_byWORLD-MANIFOLD
constitutional_citationCONSTITUTION
evidence_bundleworld-bundle-publication
compared_byworld-comparison-pillar-f-compiler-trinity-and-training-infrastructure
pillar_membershipF — training_infrastructure
book_titleBuild a Reasoning Model
book_subtitleFrom Scratch
book_authorSebastian Raschka
book_publisherManning
total_chapters8
total_source_pages419
total_nodes16
source_pdfbuild-a-reasoning-model_author_sebastian-raschka.pdf
source_pdf_sha256f00e3a80e1c80e2e26429d8844951e0ebf2fdb371f91b6a523a6c37f6ba6ed5f
source_text_output_slugbuild-a-reasoning-model
ocr_sourceQwen3-VL-8B-Instruct via llama-server (scaffold-ocr-batch-v2; pdftoppm 150dpi grayscale)
ocr_quality_classcleaned
verification_statuspartially-verified
verification_progress{"all_nodes":"stitched from OCR output; frontier verification status per node"}
stitched_bykimi-k3-frontier-transposition-pass
generated_at2026-09-20
pillar_normalizedF-training_infrastructure
updated_at2026-10-14T05:45:16Z
verification_noteTargeted cleanup pass 2026-09-20, two phases. Structural: 8 degenerate OCR repetition loops collapsed (6 line-wise, 1 div staircase, 1 in-line run of 32,457 chars that had destroyed scan page 055 - restored from the scan); page map repaired to 419/419 referenced exactly once; 17 of 18 MISSING-SOURCE claims disproved; 20 mangled folios repaired; 333 running headers removed; 132 headings promoted; YAML frontmatter restored in all 22 nodes. Prose: 1,858 hard-wrapped lines reflowed into paragraphs; 85 special tokens escaped so they render; 100 duplicate figure captions removed. Figures: inventory CLOSED - 169 figures, 162 recreated as mermaid/ASCII/table/LaTeX, 6 crop-embedded, 1 confirmed absent, 0 unresolved. Code: every python listing parsed with ast; 121 of 348 were failing on intake, now 257 of 263 parse and the remaining 6 are appendix B solutions that the book itself prints elided, verified against page-337.png and marked in place with ELIDED-IN-PRINT. See CLEANUP_NOTES.md sections 9-12.
asset_count6
visual_conversion_pages1, 17, 19, 20, 23, 24, 27, 28, 30, 31, 32, 34, 37, 38, 39, 41, 45, 46, 47, 48, 52, 53, 62, 70, 71, 72, 76, 79, 96, 105, 106, 109, 113, 115, 119, 121, 122, 124, 131, 132, 136, 140, 141, 148, 150, 151, 154, 155, 157, 159, 161, 162, 165, 170, 171, 172, 175, 183, 189, 192, 193, 194, 196, 197, 199, 200, 203, 207, 208, 215, 226, 233, 238, 239, 241, 248, 250, 253, 254, 257, 260, 262, 263, 266, 268, 272, 274, 275, 276, 280, 281, 282, 283, 284, 289, 292, 297, 299, 300, 308, 313, 343, 344, 346, 349, 350, 352, 354, 360, 372, 378, 382, 383, 390, 395, 396, 397, 401, 410, 413, 417, 418
scan_gaps_verified{"absent_from_scan":"printed 400-401 (between scan 411 and 412)","raster_dead":"printed 408 (scan page-418.png; zero pixels below value 128)","unreadable":"s…
local graph

Build a Reasoning Model — Sebastian Raschka

Section titled “Build a Reasoning Model — Sebastian Raschka”

From Scratch — Manning.

The book is organized as 8 chapters followed by appendices A–G; there are no part dividers.

node-book_build-a-reasoning-model_chapter-01-understanding-reasoning-models — Chapter 1 — Understanding reasoning models

node-book_build-a-reasoning-model_chapter-02-generating-text-with-a-pretrained-llm — Chapter 2 — Generating text with a pretrained LLM

node-book_build-a-reasoning-model_chapter-03-evaluating-reasoning-models — Chapter 3 — Evaluating reasoning models

node-book_build-a-reasoning-model_chapter-04-improving-reasoning-with-inference-time-scaling — Chapter 4 — Improving reasoning with inference-time scaling

node-book_build-a-reasoning-model_chapter-05-inference-time-scaling-via-self-refinement — Chapter 5 — Inference-time scaling via self-refinement

node-book_build-a-reasoning-model_chapter-06-training-reasoning-models-with-reinforcement-learning — Chapter 6 — Training reasoning models with reinforcement learning

node-book_build-a-reasoning-model_chapter-07-improving-grpo-for-reinforcement-learning — Chapter 7 — Improving GRPO for reinforcement learning

node-book_build-a-reasoning-model_chapter-08-distilling-reasoning-models-for-efficient-reasoning — Chapter 8 — Distilling reasoning models for efficient reasoning

node-book_build-a-reasoning-model_appendix-a-references-and-further-reading — Appendix A: References and further reading

node-book_build-a-reasoning-model_appendix-b-exercise-solutions — Appendix B: Exercise solutions

node-book_build-a-reasoning-model_appendix-c-qwen3-llm-source-code — Appendix C: Qwen3 LLM source code

node-book_build-a-reasoning-model_appendix-d-using-larger-llms — Appendix D: Using larger LLMs

appendix-e-batching-and-throughput-oriented-execution

Section titled “appendix-e-batching-and-throughput-oriented-execution”

node-book_build-a-reasoning-model_appendix-e-batching-and-throughput-oriented-execution — Appendix E: Batching and throughput-oriented execution

appendix-f-common-approaches-to-model-evaluation

Section titled “appendix-f-common-approaches-to-model-evaluation”

node-book_build-a-reasoning-model_appendix-f-common-approaches-to-model-evaluation — Appendix F: Common approaches to model evaluation

node-book_build-a-reasoning-model_appendix-g-building-a-chat-interface — Appendix G: Building a chat interface

node-book_build-a-reasoning-model_back-index — Index (first page only)

bar-fig-cover-build-a-reasoning-model.png

Book cover — Build a Reasoning Model (From Scratch), Sebastian Raschka, Manning. (Crop from scan page-001.png. Embedded rather than recreated: the cover is a photographic/illustrated plate.)

BUILD A Reasoning Model

Sebastian Raschka

MANNING

#TitlePage
1Understanding reasoning models1
2Generating text with a pretrained LLM18
3Evaluating reasoning models57
4Improving reasoning with inference-time scaling94
5Inference-time scaling via self-refinement136
6Training reasoning models with reinforcement learning179
7Improving GRPO for reinforcement learning225
8Distilling reasoning models for efficient reasoning267
appendix AReferences and further reading305
appendix BExercise solutions314
appendix CQwen3 LLM source code336
appendix DUsing larger LLMs358
appendix EBatching and throughput-oriented execution365
appendix FCommon approaches to model evaluation377
appendix GBuilding a chat interface397

contents

preface xiv acknowledgments xvi about this book xviii about the author xxii about the cover illustration xxiii

1 Understanding reasoning models 1 1.1 Defining reasoning in the context of LLMs 2 1.2 Understanding the standard LLM training pipeline 5 1.3 Improving LLM reasoning with training and inference techniques 7 1.4 Pattern matching vs. logical reasoning 10 1.5 Simulating reasoning without explicit rules 11 1.6 Why build reasoning models from scratch? 13 1.7 A road map to building reasoning models from scratch 15

2 Generating text with a pretrained LLM 18 2.1 Introducing LLMs for text generation 19 2.2 Setting up the coding environment 20 2.3 Understanding hardware needs and recommendations 23

CONTENTS

2.4 Preparing input texts for LLMs 25 2.5 Loading pretrained models 29 2.6 Understanding the sequential LLM text generation process 34 2.7 Coding a minimal text generation function 40 2.8 Faster inference via KV caching 46 2.9 Faster inference via PyTorch model compilation 50

3 Evaluating reasoning models 57 3.1 Building a math verifier 58 3.2 Loading a pretrained model to generate text 61 3.3 Implementing a wrapper for easier text generation 65 3.4 Extracting the final answer box 66 3.5 Normalizing the extracted answer 71 3.6 Verifying mathematical equivalence 74 3.7 Grading answers 77 3.8 Loading the evaluation dataset 81 3.9 Evaluating the model 84

4 Improving reasoning with inference-time scaling 94 4.1 Introduction to inference-time scaling 95 4.2 Loading a pretrained model 98 4.3 Generating better responses with chain-of-thought prompting 100 4.4 Controlling output diversity with temperature scaling 103 Understanding the process of selecting the next token 104 Rescaling token scores (logits) via a temperature parameter 107 Sampling the next token from a probability distribution 110 Adding temperature scaling to the text generation function 116 4.5 Balancing diversity and coherence with top-p sampling 118 Selecting a subset of top-p tokens 119 • Adding a top-p filter to the text generation function 123 4.6 Improving response accuracy with self-consistency 127

CONTENTS

5 Inference-time scaling via self-refinement 136 5.1 Scoring and iteratively improving model responses 137 5.2 Loading a pretrained model 139 5.3 Scoring LLM responses with a rule-based score 142 5.4 Understanding token probability scores 146 5.5 From token probability scores to log probabilities 156 5.6 Scoring model confidence with log probabilities 162 5.7 Self-refinement through iterative feedback 167 5.8 Coding the self-refinement loop 170

6 Training reasoning models with reinforcement learning 179 6.1 Introduction to RL for LLMs 180 The original RL pipeline with human feedback (RLHF) 182 From human feedback to verifiable rewards 185 6.2 RLVR using GRPO 186 High-level GRPO intuition via a chef analogy 188 The high-level GRPO procedure 189 6.3 Loading a pretrained model 191 6.4 Loading a MATH training subset 193 6.5 Sampling rollouts 195 6.6 Calculating rewards 199 6.7 Preparing learning signals from rollouts via advantages 201 6.8 Scoring rollouts with sequence log probabilities 203 6.9 From advantages to policy updates via the GRPO loss 208 6.10 Putting everything together in a single GRPO function 211 6.11 Implementing the GRPO training loop 214 6.12 Loading and evaluating saved model checkpoints 220

7 Improving GRPO for reinforcement learning 225 7.1 Improving GRPO 226 7.2 Tracking GRPO performance metrics 226 Executing a GRPO training run 227 · Inspecting the GRPO training run 229

CONTENTS

7.3 Tracking more advanced GRPO performance metrics 233 Advantage tracking 234 · Entropy tracking 236 Plotting additional GRPO metrics 240

7.4 Stabilizing sequence-level GRPO using clipped policy ratios 242 Computing clipped policy ratios 243 · Training with clipped policy ratios 247

7.5 Controlling how much the model changes with a KL term 249 Implementing the KL loss term 250 · Training with a KL loss term 253

7.6 Adding an explicit format reward 256 Using <think> tokens 257 · Training a model to emit <think> tokens 261 · More GRPO modifications, tips, and tricks 264

8 Distilling reasoning models for efficient reasoning 267 8.1 Introducing model distillation for reasoning tasks 268 8.2 Generating a dataset for reasoning distillation 271 8.3 Loading the MATH training dataset for distillation 273 8.4 Building training examples 276 Loading and understanding the tokenizer 277 · Formatting and tokenizing the dataset 279 · Filtering and splitting the dataset 282

8.5 Loading a pretrained model 285 8.6 Computing the training and validation losses 286 8.7 Implementing the training loop for distillation 291 8.8 Evaluating the distilled model 296 8.9 Future directions for reasoning models 301 8.10 Conclusions 302 What’s next 302 · Staying up to date in a fast-moving field 302

appendix A References and further reading 305 appendix B Exercise solutions 314 appendix C Qwen3 LLM source code 336 appendix D Using larger LLMs 358

CONTENTS

appendix E Batching and throughput-oriented execution 365 appendix F Common approaches to model evaluation 377 appendix G Building a chat interface 397 index 409

More than a decade ago, my journey into AI began with statistical pattern classification, where I learned how far relatively simple models can go when they capture useful structure in data. Over time, that curiosity shifted from models that recognize patterns to models that can explain, plan, and solve multistep problems.

With the release of ChatGPT in 2022, large language models (LLMs) moved into the mainstream. A later shift, especially visible in late 2024 and throughout 2025, was the extension of LLMs to create so-called reasoning models, which can solve more complex problems, especially in technical domains such as math and code.

At the same time, reasoning models can feel opaque, and this book is my attempt to make reasoning models more approachable. Rather than training a giant model from scratch, we’ll begin with a small pretrained LLM and apply reasoning techniques step by step. Along the way, you will implement text generation, evaluation with verifiers, inference-time scaling methods, and training methods, such as reinforcement learning with verifiable rewards and distillation from scratch. By the end, you will understand how the main reasoning methods work in practice and how they fit into a modern LLM development workflow.

Like my earlier book, Build a Large Language Model (From Scratch), this one takes a code-first approach, but the focus here is different. Instead of explaining the Transformer architecture in depth or covering large-scale pretraining, here we’ll concentrate on the methods that turn a conventional LLM into a reasoning model. If you have read the earlier book, this one should feel like a natural next step. If you haven’t, you can still follow along here without needing all the underlying LLM details up front.

We’ll use math examples throughout the book because they are practical for reasoning research and easy to verify automatically. That makes them a useful test bed for PREFA CE

understanding whether a model is actually solving a problem correctly. More broadly, my goal is not to teach one narrow benchmark but to give you the tools and intuition needed to build, evaluate, and improve reasoning systems in your own work.

When I first started working on reasoning models, I had to piece together ideas from papers, repositories, and scattered implementation notes. I hope this book saves you that effort and gives you a clearer path from first principles to working code. I strongly believe that the best way to understand reasoning models is to build one yourself.

Happy reading and coding!