Build a GPT from Scratch

Build a small GPT in PyTorch, one step at a time, from transformer math to training and text generation
0 min total read time
0 of 63 chapters published
Build a GPT from Scratch Cover

Read Build a GPT from Scratch free online

Build a GPT from Scratch takes one small language model from text input to generated output. We work through each tensor operation, connect it to the underlying math, and implement the model in readable PyTorch.

The book is inspired by Andrej Karpathy's educational work, especially nanoGPT and microGPT. The aim is not to copy those projects line by line. The aim is to explain the tensor shapes and mathematical decisions underneath them so that the implementation becomes readable.

Author and edition details

About the author and this edition

Michael Brenndoerfer, author of Build a GPT from Scratch

Michael Brenndoerfer

Michael has spent more than a decade working across software engineering, data, AI, and business. He writes to understand difficult ideas more deeply and to share what he learns in a clear, practical way.

Edition
First edition
Published
Last reviewed

Key Topics

GPTTransformersSelf-AttentionBackpropagationOptimizationPyTorchLanguage ModelsDeep Learning

Track Your Progress

Sign in to mark chapters as complete, track quiz scores, and see your reading journey

Sign in →

Table of Contents

Part I: Understanding the System

4 chapters
1

What Is a Language Model?

Soon

Start with a small next-token probability table. A rule-based generator exposes every choice and makes the difference between training and inference concrete.

2

The Complete LLM Pipeline

Soon

Follow one sentence through tokenization, batching, model output, sampling, and decoding. Each stage gets an interface that later chapters will replace with working code.

3

Setting Up the Project

Soon

Set up the Python environment, tests, configuration, run directories, and random seeds. The same project works on CPU and moves to a GPU when one is available.

4

Capstone: Trace One Sentence Through an LLM

Soon

Assemble the mock pipeline and account for every value and shape. Save the trace so later implementations can be checked against it.

Part II: Math and Learning Foundations

9 chapters
5

Scalars, Functions, and Computation

Soon

Attach mathematical notation to executable scalar functions. Work through a small neuron and inspect the floating-point behavior of each operation.

6

Vectors, Dot Products, and Representations

Soon

Calculate vector operations by hand, then reproduce them in Python. Dot products, norms, and projections lead directly to token representations and attention scores.

7

Matrices, Tensor Shapes, and Broadcasting

Soon

Work from row-by-column multiplication to batched tensors. Track the shapes used by GPT and learn where reshaping or broadcasting can silently change their meaning.

8

Probability for Language Modeling

Soon

Build conditional probabilities from a tiny corpus and calculate the probability of a complete sentence. Sampling experiments connect the equations to generated text.

9

Softmax, Cross-Entropy, and Perplexity

Soon

Turn a short vector of logits into probabilities and a loss. The NumPy implementation is checked against hand calculations and PyTorch.

10

Derivatives, Gradients, and the Chain Rule

Soon

Trace a loss backward through a small computation graph. Manual derivatives, finite differences, and autograd must agree before gradient descent begins.

11

Automatic Differentiation from Scratch

Soon

Write a scalar reverse-mode autodiff engine. Tests cover branching graphs, reused values, gradient accumulation, and numerical agreement.

12

Neurons, Layers, and Gradient Descent

Soon

Build an MLP from the custom autodiff values and train it on a plotted two-dimensional dataset. Broken learning rates and missing gradient resets become debugging exercises.

13

Capstone: Build a Neural-Network Engine

Soon

Package autodiff, layers, optimization, and tests into a small library. Train a nonlinear classifier and submit the gradients, loss curve, and decision surface as evidence.

Part III: From Raw Text to Training Data

5 chapters
14

Constructing a Corpus

Soon

Create a public-domain corpus whose documents have recorded sources, licenses, and checksums. Cleaning, deduplication, rejected records, and train-validation splits remain inspectable.

15

Characters, Bytes, Unicode, and Tokens

Soon

Inspect English, accented text, Chinese characters, emoji, and code as Unicode and UTF-8 bytes. Then write reversible character and byte tokenizers.

16

Byte-Pair Encoding from Scratch

Soon

Count byte pairs, apply merges, and train a BPE tokenizer on the book corpus. Each learned token can be traced through its merge history.

17

Training Examples, Splits, and Batches

Soon

Turn encoded documents into shifted input-target windows and deterministic batches. Decode sampled rows to catch boundary, mask, and split errors early.

18

Capstone: Produce a Training-Ready Dataset

Soon

Run the data pipeline from source documents to encoded shards. Deliver the tokenizer, manifests, leakage checks, and decoded sample batches needed for training.

Part IV: Language Models Before Transformers

5 chapters
19

The Count-Based Bigram Model

Soon

Count token transitions, smooth the table, score held-out text, and generate samples. Because the table fits on the page, every probability can be inspected.

20

The Neural Bigram Model

Soon

Replace the count table with learned logits and optimize it with gradients. Direct comparison shows what changed and what remained a bigram model.

21

Embeddings and Fixed Context

Soon

Look up dense token vectors and feed several previous tokens into an MLP. Experiments vary the context length and test whether order matters.

22

A Reliable Training Loop

Soon

Move training out of ad hoc notebook cells. The shared loop handles updates, validation, metrics, checkpoints, and the one-batch overfit test.

23

Capstone: Compare Three Language Models

Soon

Train the count bigram, neural bigram, and fixed-context model on the same data. Compare loss, runtime, parameter count, context, and fixed-seed samples.

Part V: Build GPT One Component at a Time

11 chapters
24

The Token-Communication Problem

Soon

Let each token gather information from earlier positions through causal averaging. Loop, cumulative-sum, and matrix versions must return the same values.

25

Attention as Learned Retrieval

Soon

Calculate queries, keys, values, attention scores, and weighted sums for three small vectors. The same numbers are then produced by one attention head.

26

Causal Attention and Numerical Stability

Soon

Add the causal mask, scaled dot products, and stable softmax. Intervention tests prove that changing a future token cannot alter an earlier output.

27

Multi-Head Attention

Soon

Split channels across heads and put them back together without losing their meaning. A readable reference version checks the vectorized implementation.

28

Position Information

Soon

Show what attention does with permuted input when it has no positions. Learned position embeddings make order available and introduce a fixed context limit.

29

The Feed-Forward Network

Soon

Build the per-token MLP and reconcile its dimensions and parameter count. Activation plots and short runs compare ReLU, GELU, and expansion size.

30

Residual Connections and Normalization

Soon

Calculate LayerNorm for one token vector and check the implementation against PyTorch. Deep-stack experiments measure what residual paths and normalization do to gradients.

31

The Transformer Block

Soon

Combine attention and the MLP in a pre-norm residual block. A shape trace follows one batch through every projection, normalization, and addition.

32

Assembling GPT

Soon

Stack the decoder blocks between token embeddings and vocabulary logits. Verify the forward contract, initialization, parameter count, and causal behavior.

33

Autoregressive Text Generation

Soon

Write the decoding loop and compare greedy, temperature, top-k, and top-p sampling on fixed logits and prompts. Seeded runs make the comparison repeatable.

34

Capstone: Train Tiny GPT

Soon

Train the complete model on the book corpus. Submit causal tests, shape and parameter ledgers, loss curves, checkpoints, runtime measurements, and fixed-seed samples.

Part VI: Train a Base Model Reliably

8 chapters
35

Designing the Model and Training Budget

Soon

Calculate model parameters, memory use, token count, training time, and cost before choosing a run. Measured throughput checks the estimate on available hardware.

36

Initialization and Trusted Baselines

Soon

Check expected initial loss, activation variance, gradient flow, and one-batch overfitting before a long run. Bad initializations provide useful counterexamples.

37

AdamW and Learning-Rate Scheduling

Soon

Work through the first AdamW updates by hand, including moment estimates and bias correction. Then add parameter groups, warmup, decay, clipping, and accumulation.

38

Diagnosing Training Failures

Soon

Investigate deliberately broken runs with high and low learning rates, bad masks, shifted targets, corrupt data, and non-finite gradients. Each confirmed bug becomes a regression test.

39

Evaluating the Base Model

Soon

Measure token loss on fixed held-out data, inspect samples, and test memorization. Small ablations and uncertainty estimates keep the conclusions within the evidence.

40

Checkpoints and Reproducibility

Soon

Save the full state needed to resume training, including the random streams and data position. A split run must match an uninterrupted run step for step.

41

Efficient GPU Training

Soon

Establish a timing baseline, find the bottleneck, and change one thing at a time. Mixed precision, fused attention, compilation, and data transfer are kept only when measurements support them.

42

Capstone: Run a Defensible Pretraining Experiment

Soon

Plan and run pretraining within a stated budget. The report records the configuration, artifact hashes, performance, loss curves, checkpoint choice, samples, and limitations.

Part VII: Scaling Training

4 chapters
43

Scaling the Data Pipeline

Soon

Store tokens in shards and read datasets larger than memory. Tests cover deterministic shuffling, worker partitioning, prefetching, and resume position.

44

Distributed Training

Soon

Calculate gradient averaging for two replicas before running a small multiprocess job. The optional GPU track measures communication cost and scaling efficiency.

45

Scaling Laws and Experiment Design

Soon

Run a small grid of model and token budgets, fit learning curves, and test the fit on a held-out configuration. Noisy pilots set bounds on what can be extrapolated.

46

Capstone: Scale the Training Run

Soon

Use measured loader speed, training throughput, memory, and pilot loss to choose the largest sensible run. A supported decision to stay small also satisfies the project.

Part VIII: Turn the Base Model into an Assistant

5 chapters
47

Preparing Instruction Data

Soon

Create conversation records with source and license fields, render the chat template, and inspect the token-level loss mask. Packing and truncation receive explicit tests.

48

Supervised Fine-Tuning

Soon

Fine-tune the base checkpoint on assistant responses and compare it with the untouched model. Measure instruction behavior alongside forgetting on base text.

49

Preference Alignment

Soon

Calculate sequence log probabilities for chosen and rejected responses, then implement a small DPO loss. The chapter also locates reward models and policy optimization within RLHF.

50

Safety and Responsible Development

Soon

Test the actual small model for memorization, privacy leakage, harmful output, bias, and prompt injection. Use the results to write the model card and release decision.

51

Capstone: Build a Tiny Assistant

Soon

Instruction-tune the base model and compare both checkpoints on a frozen test set. Deliver the lineage, response table, forgetting results, safety checks, and model card.

Part IX: Inference, Evaluation, and Deployment

6 chapters
52

Understanding Inference

Soon

Time checkpoint loading, tokenization, prefill, and token-by-token decoding separately. Memory and latency are measured as prompts and outputs grow.

53

The Key-Value Cache

Soon

Reuse keys and values from earlier positions instead of recomputing them. Cached and uncached logits must agree before speed and memory are compared.

54

Quantization and Efficient Generation

Soon

Quantize a short weight vector by hand, then apply the same ideas to the model. Report storage, runtime memory, speed, and evaluation changes on the target hardware.

55

Serving the Model

Soon

Package the tokenizer, weights, and configuration behind a small streaming API. Validate requests and test limits, cancellation, concurrency, and startup failures.

56

Evaluating the Assistant

Soon

Build a versioned test set with exact checks, pairwise review, prompt variations, and controlled factual questions. Quality results sit beside latency and failure rates.

57

Capstone: Deploy and Evaluate the Assistant

Soon

Serve the selected checkpoint with a verified KV cache and optional quantization. Compare the final service with the original baseline on the same prompts and hardware.

Part X: From GPT-2 to Modern LLMs

5 chapters
58

Modernizing the Architecture

Soon

Replace LayerNorm, learned positions, GELU, and standard multi-head attention one component at a time. RMSNorm, RoPE, SwiGLU, and GQA each get a numerical example and unit tests.

59

Controlled Architecture Experiments

Soon

Compare architecture changes under a stated matching rule, such as equal parameters, tokens, compute, or time. Repeated runs show how much of the result is noise.

60

Reading and Reproducing Research

Soon

Take one paper equation, map its symbols to tensor shapes, and implement the smallest useful test. A reduced experiment records every assumption the paper leaves open.

61

Where to Go Next

Soon

Connect the model already built to continued pretraining, retrieval, tools, sparse models, long context, multimodality, and distillation. Each path starts from a specific limitation.

62

Capstone: Build a Modern Model Variant

Soon

Train a small Llama-style variant beside the original GPT under a matched budget. Compare correctness, loss, training cost, cache memory, decoding speed, and samples.

Part XI: Final Capstone

1 chapter
63

Final Capstone: From Raw Documents to a Working LLM

Soon

Start with raw documents and produce the tokenizer, base model, assistant checkpoint, evaluation, inference service, and documentation. Every result must trace back to its data and configuration.

In Progress

This comprehensive handbook is currently in development. Each chapter will be published as it's completed, with practical examples, code implementations, and real-world applications.

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@book{brenndoerfer2026gptfromscratch, author = {Michael Brenndoerfer}, title = {Build a GPT from Scratch}, year = {2026}, url = {https://mbrenndoerfer.com/books/gpt-from-scratch}, publisher = {mbrenndoerfer.com}, note = {Accessed: 2026-10-11} }
APAAcademic
Michael Brenndoerfer (2026). Build a GPT from Scratch. Retrieved from https://mbrenndoerfer.com/books/gpt-from-scratch
MLAAcademic
Michael Brenndoerfer. "Build a GPT from Scratch." 2026. Web. October 11, 2026. <https://mbrenndoerfer.com/books/gpt-from-scratch>.
CHICAGOAcademic
Michael Brenndoerfer. "Build a GPT from Scratch." Accessed October 11, 2026. https://mbrenndoerfer.com/books/gpt-from-scratch.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Build a GPT from Scratch'. Available at: https://mbrenndoerfer.com/books/gpt-from-scratch (Accessed: October 11, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Build a GPT from Scratch. https://mbrenndoerfer.com/books/gpt-from-scratch
Newsletter

Stay up to date

Get articles, book updates, and news delivered to your inbox.

No spam, unsubscribe anytime.

or

Join the community

Sign in to remove popups, track your reading progress, and join the discussion.